<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/middleware.php';
require_once __DIR__ . '/../config/database.php';
require_customer();

$uid = $_SESSION['user']['id'];
$step = (int)($_GET['step'] ?? 1);
$isAjax = isset($_GET['ajax']);

// Generate unique application identifier
function generateApplicationId(): string {
    return 'GL-' . date('Y') . '-' . strtoupper(bin2hex(random_bytes(4)));
}

// Create verification checkpoints based on service type
function createVerificationCheckpoints(PDO $pdo, int $applicationId, string $serviceType): void {
    $checkpoints = match($serviceType) {
        'business_name' => ['name_screening', 'document_verification', 'compliance_check'],
        'company' => ['name_screening', 'document_verification', 'share_structure', 'compliance_check', 'risk_assessment'],
        'ngo' => ['name_screening', 'document_verification', 'compliance_check', 'risk_assessment'],
        'tax' => ['document_verification', 'compliance_check', 'tax_registration'],
        'scuml' => ['document_verification', 'compliance_check', 'scuml_approval'],
        'trademark' => ['name_search', 'document_verification', 'trademark_filing'],
        default => ['document_verification', 'compliance_check']
    };
    
    foreach ($checkpoints as $checkpoint) {
        $stmt = $pdo->prepare("INSERT INTO verification_checkpoints (application_id, checkpoint_type, status, created_at, updated_at) VALUES (?, ?, 'pending', ?, ?)");
        $stmt->execute([$applicationId, $checkpoint, date('c'), date('c')]);
    }
}

// Enhanced validation for professional intake
function validateApplicationData(array $data, string $step): array {
    $errors = [];
    
    match($step) {
        '1' => null, // Service selection validated elsewhere
        '2' => [
            // Personal information
            empty($data['full_name']) && $errors[] = 'Full legal name is required',
            strlen($data['full_name'] ?? '') < 3 && $errors[] = 'Full name must be at least 3 characters',
            
            // Contact information
            empty($data['email']) && $errors[] = 'Email is required',
            !filter_var($data['email'] ?? '', FILTER_VALIDATE_EMAIL) && $errors[] = 'Invalid email address',
            
            empty($data['phone']) && $errors[] = 'Phone number is required',
            !preg_match('/^(\+234|0)?[789][01]\d{8}$/', $data['phone'] ?? '') && $errors[] = 'Invalid Nigerian phone number format',
            
            empty($data['address']) && $errors[] = 'Residential address is required',
            
            // Business information
            empty($data['proposed_name_1']) && $errors[] = 'Primary business name is required',
            empty($data['nature_of_business']) && $errors[] = 'Nature of business is required',
            empty($data['business_address']) && $errors[] = 'Business address is required',
            
            // ID verification
            empty($data['id_type']) && $errors[] = 'ID type is required',
            empty($data['id_number']) && $errors[] = 'ID number is required',
        ],
        '3' => [
            // Addons validation
            isset($data['addons']) && !is_array($data['addons']) && $errors[] = 'Invalid addons selection',
        ],
        default => null
    };
    
    return array_filter($errors);
}

// Handle AJAX responses
function ajaxResponse(string $status, array $data = []): void {
    header('Content-Type: application/json');
    echo json_encode(['status' => $status] + $data);
    exit;
}

// Step 1: Service Selection & Application Creation
if ($step === 1) {
    if (is_post()) {
        ensure_csrf();
        $serviceId = (int)($_POST['service_id'] ?? 0);
        
        $stmt = $pdo->prepare("SELECT * FROM services WHERE id=? AND status='active'");
        $stmt->execute([$serviceId]);
        $service = $stmt->fetch();
        
        if (!$service) {
            if ($isAjax) ajaxResponse('error', ['message' => 'Invalid service selected']);
            set_flash('error', 'Invalid service selected');
            redirect('/customer/dashboard.php');
        }
        
        // Create unique application with professional tracking
        $applicationRef = generateApplicationId();
        $now = date('c');
        
        $stmt = $pdo->prepare('INSERT INTO applications (
            user_id, service_id, application_ref, status, total_price, cac_fee, service_fee, 
            service_category, priority_level, risk_score, internal_status, created_at, updated_at
        ) VALUES (?, ?, ?, "draft", 0, 0, 0, ?, "normal", 0, "new", ?, ?)');
        
        $stmt->execute([
            $uid, 
            $serviceId, 
            $applicationRef,
            $service['service_type'], 
            $now, 
            $now
        ]);
        
        $applicationId = (int)$pdo->lastInsertId();
        
        // Create verification checkpoints
        createVerificationCheckpoints($pdo, $applicationId, $service['service_type']);
        
        $nextUrl = "/customer/application.php?step=2&id={$applicationId}";
        
        if ($isAjax) {
            ajaxResponse('success', [
                'application_id' => $applicationId,
                'application_ref' => $applicationRef,
                'next' => $nextUrl
            ]);
        }
        
        redirect($nextUrl);
    }
    
    // Show service selection
    $services = $pdo->query("
        SELECT s.*, COUNT(a.id) as active_applications 
        FROM services s 
        LEFT JOIN applications a ON s.id = a.service_id AND a.status != 'cancelled'
        WHERE s.status = 'active' 
        GROUP BY s.id 
        ORDER BY s.service_type, s.service_name
    ")->fetchAll();
    
    $groupedServices = [];
    foreach ($services as $service) {
        $groupedServices[$service['service_type']][] = $service;
    }
    
    include __DIR__ . '/../includes/header.php';
    ?>
    <style>
    .application-container { max-width: 1200px; margin: 0 auto; padding: 40px 20px; }
    .progress-bar { background: #f1f5f9; border-radius: 10px; padding: 4px; margin-bottom: 32px; }
    .progress-fill { background: linear-gradient(90deg, var(--primary), #059669); height: 8px; border-radius: 6px; transition: width 0.3s ease; }
    .progress-steps { display: flex; justify-content: space-between; margin-top: 12px; font-size: 12px; color: var(--muted); }
    .progress-step { display: flex; align-items: center; gap: 4px; }
    .progress-step.active { color: var(--primary); font-weight: 600; }
    .progress-step.completed { color: #16a34a; }
    .service-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 24px; margin-bottom: 40px; }
    .service-category { margin-bottom: 48px; }
    .category-title { font-size: 24px; font-weight: 700; color: var(--text); margin-bottom: 20px; display: flex; align-items: center; gap: 12px; }
    .service-card { background: #fff; border: 1px solid var(--border); border-radius: 16px; padding: 24px; cursor: pointer; transition: all 0.3s; position: relative; overflow: hidden; }
    .service-card::before { content: ''; position: absolute; top: 0; left: 0; right: 0; height: 4px; background: linear-gradient(90deg, var(--primary), #059669); }
    .service-card:hover { transform: translateY(-4px); box-shadow: 0 12px 24px rgba(0,0,0,0.15); border-color: var(--primary); }
    .service-header { display: flex; justify-content: space-between; align-items: start; margin-bottom: 16px; }
    .service-title { font-size: 18px; font-weight: 700; color: var(--text); margin: 0; }
    .service-price { font-size: 24px; font-weight: 800; color: var(--primary); margin: 0; }
    .service-description { color: var(--muted); line-height: 1.6; margin-bottom: 20px; }
    .service-features { list-style: none; padding: 0; margin: 0; }
    .service-feature { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; font-size: 14px; color: var(--text); }
    .feature-icon { color: var(--primary); font-weight: bold; }
    .service-stats { display: flex; justify-content: space-between; align-items: center; margin-top: 20px; padding-top: 16px; border-top: 1px solid var(--border); }
    .stat-item { text-align: center; }
    .stat-value { font-size: 18px; font-weight: 700; color: var(--text); }
    .stat-label { font-size: 12px; color: var(--muted); text-transform: uppercase; }
    .processing-time { display: inline-block; background: #f0fdf4; color: #16a34a; padding: 4px 8px; border-radius: 4px; font-size: 12px; font-weight: 600; }
    .form-hint { font-size: 12px; color: var(--muted); margin-top: 4px; }
    .field-group { margin-bottom: 24px; }
    .field-label { font-weight: 600; margin-bottom: 8px; display: block; }
    .field-input { width: 100%; padding: 12px; border: 1px solid var(--border); border-radius: 8px; font-size: 14px; }
    .field-input:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1); }
    .quick-start { background: linear-gradient(135deg, #10b981, #059669); color: white; padding: 16px 24px; border-radius: 12px; margin-bottom: 32px; }
    .quick-start h3 { margin: 0 0 8px 0; }
    .quick-start p { margin: 0; opacity: 0.9; }
    .time-estimate { background: #fef3c7; color: #92400e; padding: 8px 12px; border-radius: 6px; font-size: 12px; font-weight: 600; margin-bottom: 16px; }
    </style>
    
    <div class="application-container">
        <div class="wizard-header">
            <h1 class="dashboard-title">Start Your Application</h1>
            <p class="dashboard-subtitle">Choose a service and begin your professional registration journey</p>
        </div>
        
        <!-- Progress Bar -->
        <div class="progress-bar">
            <div class="progress-fill" style="width: 25%;"></div>
        </div>
        <div class="progress-steps">
            <div class="progress-step active">✓ 1. Choose Service</div>
            <div class="progress-step">2. Your Details</div>
            <div class="progress-step">3. Add-ons</div>
            <div class="progress-step">4. Review & Submit</div>
        </div>
        
        <!-- Quick Start Section -->
        <div class="quick-start">
            <h3>🚀 Quick Start: Business Name Registration</h3>
            <p>Most popular choice - Complete in just 10 minutes. Perfect for sole proprietors and small businesses.</p>
            <button type="button" class="btn" style="background: white; color: var(--primary); margin-top: 12px;" onclick="selectService(1)">Start Business Name →</button>
        </div>
        
        <!-- Time Estimate -->
        <div class="time-estimate">
            ⏱️ Estimated time to complete: 5-10 minutes
        </div>
        
        <form method="post" id="serviceForm">
            <?=csrf_field()?>
            
            <?php foreach ($groupedServices as $category => $services): ?>
                <div class="service-category">
                    <h2 class="category-title">
                        <?=ucwords(str_replace('_', ' ', $category))?>
                        <span style="font-size: 14px; color: var(--muted); font-weight: 400;"><?=count($services)?> services</span>
                    </h2>
                    
                    <div class="service-grid">
                        <?php foreach ($services as $service): ?>
                            <div class="service-card" onclick="selectService(<?=$service['id']?>)">
                                <div class="service-header">
                                    <h3 class="service-title"><?=e($service['service_name'])?></h3>
                                    <div class="service-price">₦<?=number_format($service['cac_fee'] + $service['service_fee'])?></div>
                                </div>
                                
                                <p class="service-description"><?=e($service['description'] ?? 'Professional registration service with expert support')?></p>
                                
                                <ul class="service-features">
                                    <li class="service-feature">
                                        <span class="feature-icon">✓</span>
                                        <?=match($service['service_type']) {
                                            'business_name' => 'Business Name Registration',
                                            'company' => 'Company Incorporation',
                                            'ngo' => 'NGO Registration',
                                            'tax' => 'Tax Registration',
                                            'scuml' => 'SCUML Registration',
                                            'trademark' => 'Trademark Registration',
                                            default => 'Professional Registration Service'
                                        }?>
                                    </li>
                                    <li class="service-feature">
                                        <span class="feature-icon">✓</span>
                                        Expert Documentation Support
                                    </li>
                                    <li class="service-feature">
                                        <span class="feature-icon">✓</span>
                                        Real-time Progress Tracking
                                    </li>
                                </ul>
                                
                                <div class="service-stats">
                                    <div class="stat-item">
                                        <div class="stat-value"><?=number_format($service['active_applications'] ?? 0)?></div>
                                        <div class="stat-label">Active</div>
                                    </div>
                                    <div class="stat-item">
                                        <span class="processing-time">
                                            <?=match($service['service_type']) {
                                                'business_name' => '1-2 days',
                                                'company' => '3-5 days',
                                                'ngo' => '5-7 days',
                                                default => '3-5 days'
                                            }?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </form>
    </div>
    
    <script>
    function selectService(serviceId) {
        const form = document.getElementById('serviceForm');
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'service_id';
        input.value = serviceId;
        form.appendChild(input);
        form.submit();
    }
    </script>
    
    <?php
    include __DIR__ . '/../includes/footer.php';
    exit;
}

// Step 2: Professional Intake Form
if ($step === 2) {
    $applicationId = (int)($_GET['id'] ?? 0);
    
    $stmt = $pdo->prepare("SELECT a.*, s.service_name, s.service_type FROM applications a JOIN services s ON a.service_id = s.id WHERE a.id = ? AND a.user_id = ?");
    $stmt->execute([$applicationId, $uid]);
    $application = $stmt->fetch();
    
    if (!$application || $application['status'] !== 'draft') {
        set_flash('error', 'Invalid application or already submitted');
        redirect('/customer/dashboard.php');
    }
    
    if (is_post()) {
        ensure_csrf();
        $data = $_POST;
        $errors = validateApplicationData($data, '2');
        
        if (empty($errors)) {
            // Handle file uploads
            $maxSize = 2 * 1024 * 1024; // 2MB
            $allowedTypes = ['pdf', 'jpg', 'jpeg', 'png'];
            
            $idDocument = null;
            $passportPhoto = null;
            
            if (!empty($_FILES['id_document']['name'])) {
                $idDocument = save_uploaded_file($_FILES['id_document'], $allowedTypes, $maxSize, __DIR__ . '/../uploads/ids');
                if (!$idDocument) {
                    $errors[] = 'Failed to upload ID document. Please check file format and size.';
                }
            }
            
            if (!empty($_FILES['passport_photo']['name'])) {
                $passportPhoto = save_uploaded_file($_FILES['passport_photo'], $allowedTypes, $maxSize, __DIR__ . '/../uploads/ids');
                if (!$passportPhoto) {
                    $errors[] = 'Failed to upload passport photo. Please check file format and size.';
                }
            }
            
            if (empty($errors)) {
                // Save application details
                $stmt = $pdo->prepare('INSERT OR REPLACE INTO application_details (
                    application_id, proposed_name_1, proposed_name_2, nature_of_business, business_address,
                    date_of_birth, nationality, id_type, id_number, id_document_path, passport_path,
                    full_name, email, phone, residential_address
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
                
                $stmt->execute([
                    $applicationId,
                    $data['proposed_name_1'],
                    $data['proposed_name_2'] ?? '',
                    $data['nature_of_business'],
                    $data['business_address'],
                    $data['date_of_birth'] ?? '',
                    $data['nationality'] ?? 'Nigerian',
                    $data['id_type'],
                    $data['id_number'],
                    $idDocument ? '/uploads/ids/' . $idDocument : null,
                    $passportPhoto ? '/uploads/ids/' . $passportPhoto : null,
                    $data['full_name'],
                    $data['email'],
                    $data['phone'],
                    $data['address']
                ]);
                
                // Update application status
                $pdo->prepare("UPDATE applications SET status='details_completed', updated_at=? WHERE id=?")->execute([date('c'), $applicationId]);
                
                $nextUrl = "/customer/application.php?step=3&id={$applicationId}";
                
                if ($isAjax) {
                    ajaxResponse('success', ['next' => $nextUrl]);
                }
                
                redirect($nextUrl);
            }
        }
        
        if ($isAjax && !empty($errors)) {
            ajaxResponse('error', ['message' => implode('<br>', $errors)]);
        }
    }
    
    // Load existing details if any
    $stmt = $pdo->prepare("SELECT * FROM application_details WHERE application_id = ?");
    $stmt->execute([$applicationId]);
    $details = $stmt->fetch();
    
    include __DIR__ . '/../includes/header.php';
    ?>
    <style>
    .application-container { max-width: 800px; margin: 0 auto; padding: 40px 20px; }
    .progress-bar { background: #f1f5f9; border-radius: 10px; padding: 4px; margin-bottom: 32px; }
    .progress-fill { background: linear-gradient(90deg, var(--primary), #059669); height: 8px; border-radius: 6px; transition: width 0.3s ease; }
    .progress-steps { display: flex; justify-content: space-between; margin-top: 12px; font-size: 12px; color: var(--muted); }
    .progress-step { display: flex; align-items: center; gap: 4px; }
    .progress-step.active { color: var(--primary); font-weight: 600; }
    .progress-step.completed { color: #16a34a; }
    .form-section { background: #fff; border: 1px solid var(--border); border-radius: 16px; padding: 32px; margin-bottom: 24px; }
    .section-title { font-size: 20px; font-weight: 700; color: var(--text); margin-bottom: 24px; display: flex; align-items: center; gap: 8px; }
    .form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
    .form-group { margin-bottom: 20px; }
    .form-label { font-weight: 600; margin-bottom: 8px; display: block; color: var(--text); }
    .form-input { width: 100%; padding: 12px; border: 1px solid var(--border); border-radius: 8px; font-size: 14px; }
    .form-input:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1); }
    .form-hint { font-size: 12px; color: var(--muted); margin-top: 4px; }
    .form-error { color: #ef4444; font-size: 12px; margin-top: 4px; }
    .file-upload { border: 2px dashed var(--border); border-radius: 8px; padding: 20px; text-align: center; cursor: pointer; transition: all 0.3s; }
    .file-upload:hover { border-color: var(--primary); background: #f0fdf4; }
    .file-upload.has-file { border-color: var(--primary); background: #f0fdf4; }
    .quick-tips { background: #fef3c7; border-radius: 8px; padding: 16px; margin-bottom: 24px; }
    .quick-tips h4 { margin: 0 0 8px 0; color: #92400e; }
    .quick-tips ul { margin: 0; padding-left: 20px; }
    .quick-tips li { margin-bottom: 4px; font-size: 14px; }
    .time-estimate { background: #f0fdf4; color: #16a34a; padding: 8px 12px; border-radius: 6px; font-size: 12px; font-weight: 600; margin-bottom: 16px; }
    .btn-primary { background: var(--primary); color: white; padding: 12px 24px; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; }
    .btn-primary:hover { background: var(--primary-hover); }
    .btn-secondary { background: #f1f5f9; color: var(--text); padding: 12px 24px; border: 1px solid var(--border); border-radius: 8px; font-weight: 600; cursor: pointer; }
    </style>
    
    <div class="application-container">
        <div class="wizard-header">
            <h1 class="dashboard-title">Your Information</h1>
            <p class="dashboard-subtitle">Tell us about yourself and your business</p>
        </div>
        
        <!-- Progress Bar -->
        <div class="progress-bar">
            <div class="progress-fill" style="width: 50%;"></div>
        </div>
        <div class="progress-steps">
            <div class="progress-step completed">✓ 1. Choose Service</div>
            <div class="progress-step active">✓ 2. Your Details</div>
            <div class="progress-step">3. Add-ons</div>
            <div class="progress-step">4. Review & Submit</div>
        </div>
        
        <!-- Time Estimate -->
        <div class="time-estimate">
            ⏱️ Estimated time to complete: 3-5 minutes
        </div>
        
        <!-- Quick Tips -->
        <div class="quick-tips">
            <h4>💡 Quick Tips:</h4>
            <ul>
                <li>Have your ID document ready (NIN, Driver's License, or Passport)</li>
                <li>Use your personal email and phone number</li>
                <li>Business address can be different from residential address</li>
                <li>All fields marked with * are required</li>
            </ul>
        </div>
        
        <form method="post" enctype="multipart/form-data" id="detailsForm">
            <?=csrf_field()?>
            
            <!-- Personal Information -->
            <div class="form-section">
                <h2 class="section-title">👤 Personal Information</h2>
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">Full Legal Name *</label>
                        <input type="text" name="full_name" class="form-input" value="<?=e($details['full_name'] ?? '')?>" placeholder="John Doe" required>
                        <div class="form-hint">As it appears on your ID document</div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Email Address *</label>
                        <input type="email" name="email" class="form-input" value="<?=e($details['email'] ?? '')?>" placeholder="john@example.com" required>
                        <div class="form-hint">We'll send updates here</div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Phone Number *</label>
                        <input type="tel" name="phone" class="form-input" value="<?=e($details['phone'] ?? '')?>" placeholder="+2348000000000" required>
                        <div class="form-hint">Format: +2348000000000 or 08000000000</div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Date of Birth</label>
                        <input type="date" name="date_of_birth" class="form-input" value="<?=e($details['date_of_birth'] ?? '')?>">
                        <div class="form-hint">Optional but recommended</div>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Residential Address *</label>
                    <input type="text" name="address" class="form-input" value="<?=e($details['residential_address'] ?? '')?>" placeholder="123 Lagos Street, Ikeja, Lagos" required>
                    <div class="form-hint">Your home address</div>
                </div>
            </div>
            
            <!-- Business Information -->
            <div class="form-section">
                <h2 class="section-title">🏢 Business Information</h2>
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">Proposed Business Name *</label>
                        <input type="text" name="proposed_name_1" class="form-input" value="<?=e($details['proposed_name_1'] ?? '')?>" placeholder="John's Ventures" required>
                        <div class="form-hint">Primary business name choice</div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Alternative Business Name</label>
                        <input type="text" name="proposed_name_2" class="form-input" value="<?=e($details['proposed_name_2'] ?? '')?>" placeholder="John Ventures Nigeria">
                        <div class="form-hint">Optional backup choice</div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Nature of Business *</label>
                        <input type="text" name="nature_of_business" class="form-input" value="<?=e($details['nature_of_business'] ?? '')?>" placeholder="Retail, Consulting, Technology" required>
                        <div class="form-hint">What does your business do?</div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Business Address *</label>
                        <input type="text" name="business_address" class="form-input" value="<?=e($details['business_address'] ?? '')?>" placeholder="456 Business Avenue, Victoria Island, Lagos" required>
                        <div class="form-hint">Where your business operates</div>
                    </div>
                </div>
            </div>
            
            <!-- ID Verification -->
            <div class="form-section">
                <h2 class="section-title">🆔 ID Verification</h2>
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">ID Type *</label>
                        <select name="id_type" class="form-input" required>
                            <option value="">Select ID Type</option>
                            <option value="nin" <?=($details['id_type'] ?? '') === 'nin' ? 'selected' : ''?>>National ID (NIN)</option>
                            <option value="drivers_license" <?=($details['id_type'] ?? '') === 'drivers_license' ? 'selected' : ''?>>Driver's License</option>
                            <option value="passport" <?=($details['id_type'] ?? '') === 'passport' ? 'selected' : ''?>>International Passport</option>
                            <option value="voters_card" <?=($details['id_type'] ?? '') === 'voters_card' ? 'selected' : ''?>>Voter's Card</option>
                        </select>
                        <div class="form-hint">Choose your primary ID document</div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">ID Number *</label>
                        <input type="text" name="id_number" class="form-input" value="<?=e($details['id_number'] ?? '')?>" placeholder="12345678901" required>
                        <div class="form-hint">ID document number</div>
                    </div>
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label class="form-label">Upload ID Document *</label>
                        <div class="file-upload" onclick="document.getElementById('id_document').click()">
                            <input type="file" id="id_document" name="id_document" accept=".pdf,.jpg,.jpeg,.png" style="display: none;" onchange="handleFileSelect(this, 'id-upload')">
                            <div id="id-upload">
                                <div>📄 Click to upload ID document</div>
                                <div class="form-hint">PDF, JPG, or PNG (Max 2MB)</div>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Upload Passport Photo *</label>
                        <div class="file-upload" onclick="document.getElementById('passport_photo').click()">
                            <input type="file" id="passport_photo" name="passport_photo" accept=".jpg,.jpeg,.png" style="display: none;" onchange="handleFileSelect(this, 'passport-upload')">
                            <div id="passport-upload">
                                <div>📸 Click to upload passport photo</div>
                                <div class="form-hint">JPG or PNG (Max 2MB)</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Form Actions -->
            <div style="display: flex; gap: 16px; justify-content: flex-end; margin-top: 32px;">
                <a href="/customer/dashboard.php" class="btn-secondary">Cancel</a>
                <button type="submit" class="btn-primary">Continue to Add-ons →</button>
            </div>
        </form>
    </div>
    
    <script>
    function handleFileSelect(input, targetId) {
        const file = input.files[0];
        const target = document.getElementById(targetId);
        
        if (file) {
            target.classList.add('has-file');
            target.innerHTML = `
                <div>✅ ${file.name}</div>
                <div class="form-hint">${(file.size / 1024 / 1024).toFixed(2)} MB</div>
            `;
        }
    }
    
    // Auto-save functionality
    let autoSaveTimer;
    const form = document.getElementById('detailsForm');
    
    function autoSave() {
        const formData = new FormData(form);
        // Implement auto-save logic here
        console.log('Auto-saving...');
    }
    
    // Auto-save on input change
    form.addEventListener('input', () => {
        clearTimeout(autoSaveTimer);
        autoSaveTimer = setTimeout(autoSave, 5000);
    });
    </script>
    
    <?php
    include __DIR__ . '/../includes/footer.php';
    exit;
}
    
    include __DIR__ . '/../includes/header.php';
    
    // Render professional intake form (similar to professional_intake.php but enhanced)
    // ... form rendering code here ...
    
    include __DIR__ . '/../includes/footer.php';
    exit;
}

// Step 3: Add-ons and Additional Services
if ($step === 3) {
    // Similar structure for addons selection
    // ... implementation here ...
}

// Step 4: Review and Submit
if ($step === 4) {
    // Review page with all details and final submission
    // ... implementation here ...
}

// Invalid step
set_flash('error', 'Invalid application step');
redirect('/customer/dashboard.php');
?>
