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

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

// Load user profile data for pre-filling forms
$profileStmt = $pdo->prepare("SELECT * FROM user_profiles WHERE user_id = ?");
$profileStmt->execute([$uid]);
$userProfile = $profileStmt->fetch(PDO::FETCH_ASSOC) ?: [];

function finish_step($url) {
    global $isAjax;
    if ($isAjax) {
        $url .= (strpos($url,'?')===false?'?':'&').'ajax=1';
        header('Content-Type: application/json');
        echo json_encode(['status'=>'success', 'next'=>$url]);
        exit;
    }
    redirect($url);
}

// Step 1: Create Draft (POST only usually, but GET shows list)
if ($step === 1 && is_post()) {
    ensure_csrf();
    $service_id = (int)($_POST['service_id'] ?? 0);
    $svc = $pdo->prepare("SELECT * FROM services WHERE id=? AND status='active'"); $svc->execute([$service_id]); $svc = $svc->fetch();
    if ($svc) {
        $now = date('c');
        $stmt = $pdo->prepare('INSERT INTO applications (user_id, service_id, status, total_price, cac_fee, service_fee, admin_notes, created_at, updated_at) VALUES (?,?,"draft",0,0,0,NULL,?,?)');
        $stmt->execute([$uid,$service_id,$now,$now]);
        $aid = (int)$pdo->lastInsertId();
        finish_step(url('customer/new_application.php?step=2&id='.$aid));
    }
}

// Step 2: Details (POST)
if ($step === 2 && is_post()) {
    ensure_csrf();
    $aid = (int)($_POST['application_id'] ?? 0);
    $app = $pdo->prepare('SELECT * FROM applications WHERE id=? AND user_id=?'); $app->execute([$aid,$uid]); $app = $app->fetch();
    if ($app && $app['status']==='draft') {
        $max = 2*1024*1024;
        $id_doc = $_FILES['id_document'] ?? null;
        $passport = $_FILES['passport_photo'] ?? null;
        $id_name = $id_doc ? save_uploaded_file($id_doc, ['pdf','jpg','jpeg','png'], $max, __DIR__ . '/../uploads/ids') : null;
        $pass_name = $passport ? save_uploaded_file($passport, ['jpg','jpeg','png'], $max, __DIR__ . '/../uploads/ids') : null;
        $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) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)');
        $stmt->execute([
            $aid,
            sanitize_str($_POST['proposed_name_1'] ?? ''),
            sanitize_str($_POST['proposed_name_2'] ?? ''),
            sanitize_str($_POST['nature_of_business'] ?? ''),
            sanitize_str($_POST['business_address'] ?? ''),
            sanitize_str($_POST['date_of_birth'] ?? ''),
            sanitize_str($_POST['nationality'] ?? ''),
            sanitize_str($_POST['id_type'] ?? ''),
            sanitize_str($_POST['id_number'] ?? ''),
            $id_name? url('uploads/ids/'.$id_name) : null,
            $pass_name? url('uploads/ids/'.$pass_name) : null,
            sanitize_str($_POST['full_name'] ?? ''),
            sanitize_str($_POST['email'] ?? ''),
            sanitize_str($_POST['phone'] ?? '')
        ]);
        finish_step(url('customer/new_application.php?step=3&id='.$aid));
    }
}

// Step 3: Addons (POST)
if ($step === 3 && is_post()) {
    ensure_csrf();
    $aid = (int)($_POST['application_id'] ?? 0);
    $app = $pdo->prepare('SELECT a.*, s.cac_fee, s.service_fee FROM applications a JOIN services s ON a.service_id=s.id WHERE a.id=? AND a.user_id=?'); $app->execute([$aid,$uid]); $app = $app->fetch();
    if ($app && $app['status']==='draft') {
        $pdo->exec('CREATE TABLE IF NOT EXISTS application_addons (id INTEGER PRIMARY KEY AUTOINCREMENT, application_id INTEGER NOT NULL, name TEXT NOT NULL, price REAL NOT NULL)');
        $pdo->prepare('DELETE FROM application_addons WHERE application_id=?')->execute([$aid]);
        $addons = $_POST['addons'] ?? [];
        $map = [
            'FIRS TIN' => 4000,
            'JTB TIN' => 3000,
            'Company TIN' => 4000,
            'Status Report' => 10000,
            'Certified True Copy (Extra)' => 8000,
            'Same Day Filing (Company)' => 50000,
            'Same Day Filing (NGO)' => 45000,
            'Increase Share Capital (+₦1M)' => 20000,
            'Restrict Director Address' => 40000,
            'Trustee Address Restriction' => 40000,
            'Annual Returns Filing (Company)' => 10000,
            'Annual Returns Filing (BN)' => 3000,
            'Due Diligence Search' => 75000,
            'SCUML' => 45000,
            'Trademark' => 85000,
            'TaxProMax' => 30000,
            'Express Processing' => 15000
        ];
        foreach ($addons as $a) {
            if (isset($map[$a])) {
                $pdo->prepare('INSERT INTO application_addons (application_id,name,price) VALUES (?,?,?)')->execute([$aid,$a,(float)$map[$a]]);
            }
        }
        finish_step(url('customer/new_application.php?step=4&id='.$aid));
    }
}

// Step 4: Submit (POST)
if ($step === 4 && is_post()) {
    ensure_csrf();
    $aid = (int)($_POST['application_id'] ?? 0);
    $app = $pdo->prepare('SELECT a.*, s.cac_fee, s.service_fee FROM applications a JOIN services s ON a.service_id=s.id WHERE a.id=? AND a.user_id=?'); $app->execute([$aid,$uid]); $app = $app->fetch();
    if ($app && $app['status']==='draft') {
        $addons = $pdo->prepare('SELECT SUM(price) as sum FROM application_addons WHERE application_id=?'); $addons->execute([$aid]); $addons = $addons->fetch();
        $addonSum = (float)($addons['sum'] ?? 0);
        $base = (float)$app['cac_fee'] + (float)$app['service_fee'];
        $total = $base + $addonSum;
        $pdo->prepare('UPDATE applications SET status="submitted", total_price=?, cac_fee=?, service_fee=?, updated_at=? WHERE id=?')->execute([$total,(float)$app['cac_fee'],(float)$app['service_fee'],date('c'),$aid]);
        
        if ($isAjax) {
            echo json_encode(['status'=>'success', 'redirect'=>url('customer/view_application.php?id='.$aid)]);
            exit;
        }
        set_flash('success','Application submitted');
        redirect(url('customer/view_application.php?id='.$aid));
    }
}

// --- VIEW RENDERING ---

if (!$isAjax) include __DIR__ . '/../includes/header.php';

// Helper for wizard progress
function render_wizard_progress($step) {
    $steps = [1=>'Service', 2=>'Details', 3=>'Add-ons', 4=>'Review'];
    $html = '<div class="wizard-progress">';
    foreach ($steps as $n => $label) {
        $active = ($step === $n) ? 'active' : '';
        $completed = ($step > $n) ? 'completed' : ''; // Optional: add checkmark logic if desired
        // If step is completed, we might want to show it as active or completed. 
        // For simplicity, let's just mark current as active.
        // Actually, let's use the logic from dashboard:
        // .active class on current step.
        // .completed class on past steps? Dashboard CSS didn't fully implement .completed style except green background.
        
        $cls = '';
        if ($step === $n) $cls = 'active';
        else if ($step > $n) $cls = 'completed';
        
        $icon = ($step > $n) ? '✓' : $n;
        
        $html .= '<div class="step '.$cls.'">
            <div class="step-icon">'.$icon.'</div>
            <div class="step-label">'.$label.'</div>
        </div>';
    }
    $html .= '</div>';
    return $html;
}
?>

<div id="wizard-container">
  
  <?php echo render_wizard_progress($step); ?>

<?php
if ($step === 1) {
    // Only used if accessing page directly
    $services = $pdo->query("SELECT *, (cac_fee + service_fee) as total FROM services WHERE status='active' ORDER BY created_at DESC")->fetchAll();
    ?>
    <div class="step-header">
      <h4>Select Service</h4>
      <p>Choose the service that matches your goal.</p>
    </div>
    
    <div class="service-grid">
      <?php foreach ($services as $s): ?>
      <form method="post" class="service-form">
        <?=csrf_field()?>
        <input type="hidden" name="service_id" value="<?=e((string)$s['id'])?>">
        <button type="submit" class="service-card">
          <div class="service-icon">1</div>
          <div class="service-info">
            <div class="service-name"><?=e($s['service_name'])?></div>
            <div class="service-desc">Includes CAC registration + Service Fee</div>
            <div class="service-price">₦<?=e(money((float)$s['total']))?></div>
          </div>
          <div class="service-arrow">></div>
        </button>
      </form>
      <?php endforeach; ?>
    </div>
    <?php
}

if ($step === 2) {
    $aid = (int)($_GET['id'] ?? 0);
    $app = $pdo->prepare('SELECT * FROM applications WHERE id=? AND user_id=?'); $app->execute([$aid,$uid]); $app = $app->fetch();
    if (!$app) { echo '<div class="alert alert-error">Application not found</div>'; if(!$isAjax) include __DIR__ . '/../includes/footer.php'; exit; }
    $user = $_SESSION['user'];
    $hasProfileData = !empty($userProfile);
    ?>
    <div class="step-header">
      <h4>Application Details</h4>
      <p>Provide business and identity information.</p>
    </div>
    
    <?php if ($hasProfileData): ?>
    <div style="background: #f0fdf4; border: 1px solid #86efac; border-radius: 10px; padding: 16px; margin-bottom: 24px;">
        <div style="display: flex; align-items: center; gap: 12px;">
            <div style="font-size: 24px;">✓</div>
            <div>
                <div style="font-weight: 600; color: #166534;">Profile Information Loaded</div>
                <div style="font-size: 14px; color: #15803d;">Your saved profile data has been pre-filled. You can update any field if needed.</div>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <form method="post" enctype="multipart/form-data" action="<?=url('customer/new_application.php?step=2&ajax=1')?>">
      <?=csrf_field()?>
      <input type="hidden" name="application_id" value="<?=e((string)$aid)?>">
      
      <div class="form-group">
        <label class="form-label">Business Info</label>
        <div class="form-grid">
            <div>
                <label class="form-label">Proposed Name 1</label>
                <input type="text" name="proposed_name_1" class="form-input" required placeholder="First preference">
            </div>
            <div>
                <label class="form-label">Proposed Name 2</label>
                <input type="text" name="proposed_name_2" class="form-input" placeholder="Alternative name">
            </div>
        </div>
        <div style="margin-top:12px">
            <label class="form-label">Nature of Business</label>
            <textarea name="nature_of_business" class="form-textarea" rows="2" placeholder="Describe what your business does..."><?=e($userProfile['nature_of_business'] ?? '')?></textarea>
        </div>
        <div style="margin-top:12px">
            <label class="form-label">Business Address</label>
            <textarea name="business_address" class="form-textarea" rows="2" placeholder="Full office address..."><?=e($userProfile['business_address'] ?? '')?></textarea>
        </div>
      </div>

      <div class="form-group">
        <label class="form-label">Personal Details</label>
        <div class="form-grid">
          <div><label class="form-label">Full Name</label><input type="text" name="full_name" value="<?=e($userProfile['full_name'] ?? $user['full_name'])?>" class="form-input" required></div>
          <div><label class="form-label">Date of Birth</label><input type="date" name="date_of_birth" class="form-input" value="<?=e($userProfile['date_of_birth'] ?? '')?>"></div>
          <div><label class="form-label">Nationality</label><input type="text" name="nationality" class="form-input" value="<?=e($userProfile['nationality'] ?? 'Nigerian')?>"></div>
          <div><label class="form-label">Email</label><input type="email" name="email" value="<?=e($userProfile['email'] ?? $user['email'])?>" class="form-input" required></div>
          <div><label class="form-label">Phone</label><input type="text" name="phone" class="form-input" value="<?=e($userProfile['phone'] ?? '')?>"></div>
          <div><label class="form-label">ID Type</label>
            <select name="id_type" class="form-select">
                <option value="">Select ID Type...</option>
                <option value="NIN" <?= ($userProfile['id_type'] ?? '') === 'NIN' ? 'selected' : '' ?>>NIN</option>
                <option value="Passport" <?= ($userProfile['id_type'] ?? '') === 'Passport' ? 'selected' : '' ?>>International Passport</option>
                <option value="Voters Card" <?= ($userProfile['id_type'] ?? '') === 'Voters Card' ? 'selected' : '' ?>>Voter's Card</option>
                <option value="Drivers License" <?= ($userProfile['id_type'] ?? '') === 'Drivers License' ? 'selected' : '' ?>>Driver's License</option>
            </select>
          </div>
        </div>
      </div>
      
      <div class="form-group">
          <label class="form-label">Identity Documents</label>
          <div class="form-grid">
              <div>
                  <label class="form-label">ID Number</label>
                  <input type="text" name="id_number" class="form-input" placeholder="Enter ID number" value="<?=e($userProfile['id_number'] ?? '')?>">
              </div>
          </div>
          <?php if (!empty($userProfile['id_document_path']) || !empty($userProfile['passport_path'])): ?>
          <div style="background: #f0fdf4; border: 1px solid #86efac; border-radius: 8px; padding: 12px; margin: 12px 0;">
              <div style="font-size: 13px; color: #166534; font-weight: 600; margin-bottom: 8px;">✓ Documents from your profile:</div>
              <div style="display: flex; gap: 16px; flex-wrap: wrap;">
                  <?php if (!empty($userProfile['id_document_path'])): ?>
                  <a href="<?=e($userProfile['id_document_path'])?>" target="_blank" style="font-size: 13px; color: #059669;">📄 View ID Document →</a>
                  <?php endif; ?>
                  <?php if (!empty($userProfile['passport_path'])): ?>
                  <a href="<?=e($userProfile['passport_path'])?>" target="_blank" style="font-size: 13px; color: #059669;">📷 View Passport Photo →</a>
                  <?php endif; ?>
              </div>
              <div style="font-size: 12px; color: #6b7280; margin-top: 8px;">Your profile documents will be used. Upload below only if you need different documents for this application.</div>
          </div>
          <?php endif; ?>
          <div class="form-grid" style="margin-top:12px">
              <div>
                  <label class="file-upload-box">
                      <input type="file" name="id_document" accept=".pdf,.jpg,.jpeg,.png">
                      <div class="file-label-strong">Upload ID Document</div>
                      <div class="file-label-text">PDF, JPG, PNG (Max 2MB)</div>
                  </label>
              </div>
              <div>
                  <label class="file-upload-box">
                      <input type="file" name="passport_photo" accept=".jpg,.jpeg,.png">
                      <div class="file-label-strong">Upload Passport Photo</div>
                      <div class="file-label-text">JPG, PNG (Max 2MB)</div>
                  </label>
              </div>
          </div>
      </div>

      <div class="inline" style="margin-top:24px; padding-top:16px; border-top:1px solid var(--border); justify-content: flex-end;">
        <button class="btn primary" type="submit">Save & Continue &rarr;</button>
      </div>
    </form>
    <?php
}

if ($step === 3) {
    $aid = (int)($_GET['id'] ?? 0);
    $app = $pdo->prepare('SELECT a.*, s.service_name FROM applications a JOIN services s ON a.service_id=s.id WHERE a.id=? AND a.user_id=?'); $app->execute([$aid,$uid]); $app = $app->fetch();
    if (!$app) { echo '<div class="alert alert-error">Not found</div>'; if(!$isAjax) include __DIR__ . '/../includes/footer.php'; exit; }
    
    // Grouped Add-ons (Same array as before)
    $groups = [
        'Tax & Regulatory' => [
            ['FIRS TIN', 4000, 'Tax Identification Number from Federal Inland Revenue'],
            ['JTB TIN', 3000, 'Joint Tax Board TIN for individuals/enterprises'],
            ['Company TIN', 4000, 'Corporate Tax ID'],
            ['TaxProMax', 30000, 'FIRS TaxProMax registration setup'],
            ['SCUML', 45000, 'Special Control Unit Against Money Laundering certificate'],
        ],
        'Speed & Priority' => [
            ['Same Day Filing (Company)', 50000, 'Get your company registered in 24 hours'],
            ['Same Day Filing (NGO)', 45000, 'Expedited NGO registration'],
            ['Express Processing', 15000, 'Priority handling for faster delivery'],
        ],
        'Post-Incorporation' => [
            ['Status Report', 10000, 'Official CAC Status Report'],
            ['Certified True Copy (Extra)', 8000, 'Extra set of certified documents'],
            ['Increase Share Capital (+₦1M)', 20000, 'Boost your company share capital'],
            ['Annual Returns Filing (Company)', 10000, 'File your annual returns'],
            ['Annual Returns Filing (BN)', 3000, 'File Business Name returns'],
        ],
        'Legal & Protection' => [
            ['Trademark', 85000, 'Protect your brand name/logo'],
            ['Due Diligence Search', 75000, 'Comprehensive legal search'],
            ['Restrict Director Address', 40000, 'Keep residential address private'],
            ['Trustee Address Restriction', 40000, 'Privacy for NGO trustees'],
        ]
    ];
    ?>
    
    <div class="step-header">
      <h4>Enhance Your Application</h4>
      <p>Select optional add-on services.</p>
    </div>
      
    <form method="post" action="<?=url('customer/new_application.php?step=3&ajax=1')?>">
      <?=csrf_field()?>
      <input type="hidden" name="application_id" value="<?=e((string)$aid)?>">
      
      <?php foreach ($groups as $category => $items): ?>
        <div style="margin-bottom: 24px;">
          <h5 style="margin: 0 0 12px; font-size: 13px; text-transform: uppercase; color: var(--muted); letter-spacing: 0.5px; border-bottom: 1px solid var(--border); padding-bottom: 8px;"><?=$category?></h5>
          <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 12px;">
            <?php foreach ($items as $item): ?>
              <label class="addon-card">
                <input type="checkbox" name="addons[]" value="<?=$item[0]?>" class="addon-checkbox" onchange="this.closest('.addon-card').classList.toggle('selected', this.checked)">
                <div class="addon-info">
                  <span class="addon-name"><?=$item[0]?></span>
                  <span class="addon-desc"><?=$item[2]?></span>
                  <span class="addon-price">₦<?=e(money((float)$item[1]))?></span>
                </div>
              </label>
            <?php endforeach; ?>
          </div>
        </div>
      <?php endforeach; ?>

      <div class="inline" style="margin-top:24px; padding-top:16px; border-top:1px solid var(--border); justify-content: space-between;">
        <button class="btn btn-outline" type="button" onclick="loadStep('<?=url('customer/new_application.php?step=2&id='.e((string)$aid).'&ajax=1')?>')">&larr; Back</button>
        <button class="btn primary" type="submit">Continue to Review &rarr;</button>
      </div>
    </form>
    <?php
}

if ($step === 4) {
    $aid = (int)($_GET['id'] ?? 0);
    $app = $pdo->prepare('SELECT a.*, s.service_name, s.cac_fee, s.service_fee FROM applications a JOIN services s ON a.service_id=s.id WHERE a.id=? AND a.user_id=?'); $app->execute([$aid,$uid]); $app = $app->fetch();
    $det = $pdo->prepare('SELECT * FROM application_details WHERE application_id=?'); $det->execute([$aid]); $det = $det->fetch();
    if (!$app) { echo '<div class="alert alert-error">Not found</div>'; if(!$isAjax) include __DIR__ . '/../includes/footer.php'; exit; }
    $addons = $pdo->prepare('SELECT name, price FROM application_addons WHERE application_id=?'); $addons->execute([$aid]); $addonRows = $addons->fetchAll();
    $addonSum = 0.0; foreach ($addonRows as $r) { $addonSum += (float)$r['price']; }
    $base = (float)$app['cac_fee'] + (float)$app['service_fee'];
    $total = $base + $addonSum;
    ?>
    <div class="step-header">
      <h4>Review & Submit</h4>
      <p>Please confirm your selection and details.</p>
    </div>

    <div class="review-card">
        <div class="review-row">
            <span class="review-label">Service</span>
            <span class="review-val"><?=e($app['service_name'])?></span>
        </div>
        <div class="review-row">
            <span class="review-label">Proposed Name</span>
            <span class="review-val"><?=e($det['proposed_name_1'] ?? 'N/A')?></span>
        </div>
        <?php if ($addonRows): ?>
        <div class="review-row">
            <span class="review-label">Add-ons</span>
            <span class="review-val" style="text-align:right">
                <?php foreach ($addonRows as $r): ?>
                    <div style="font-size:12px"><?=e($r['name'])?></div>
                <?php endforeach; ?>
            </span>
        </div>
        <?php endif; ?>
        <div class="review-row" style="border-top:1px solid #e2e8f0; margin-top:8px; padding-top:12px">
            <span class="review-label" style="font-weight:600; color:var(--text)">Total Payable</span>
            <span class="review-val" style="font-size:16px; color:var(--primary)">₦<?=e(money($total))?></span>
        </div>
    </div>

    <form method="post" action="<?=url('customer/new_application.php?step=4&ajax=1')?>">
      <?=csrf_field()?>
      <input type="hidden" name="application_id" value="<?=e((string)$aid)?>">
      <div class="inline" style="justify-content: space-between;">
        <button class="btn btn-outline" type="button" onclick="loadStep('<?=url('customer/new_application.php?step=3&id='.e((string)$aid).'&ajax=1')?>')">&larr; Back</button>
        <button class="btn primary" type="submit">Confirm & Submit</button>
      </div>
    </form>
    <?php
}
?>
</div>
<?php
if (!$isAjax) include __DIR__ . '/../includes/footer.php';
