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

$uid = $_SESSION['user']['id'];
$user = $_SESSION['user'];

// Fetch stats
$rowsStmt = $pdo->prepare("SELECT a.*, s.service_name FROM applications a JOIN services s ON a.service_id=s.id WHERE a.user_id=? ORDER BY a.created_at DESC");
$rowsStmt->execute([$uid]); 
$rows = $rowsStmt->fetchAll();

$activeApps = 0; 
$awaitingPayment = 0; 
$approvedApps = 0;

foreach ($rows as $r) {
  if (in_array($r['status'], ['draft','submitted','processing'], true)) { $activeApps++; }
  if ($r['status'] === 'approved') { $approvedApps++; }
  // Check payment for awaiting
  $payStmt = $pdo->prepare('SELECT status FROM payments WHERE application_id=? ORDER BY id DESC LIMIT 1');
  $payStmt->execute([$r['id']]); 
  $p = $payStmt->fetch();
  
  if ($r['status'] !== 'approved' && (!$p || $p['status'] === 'pending')) { 
      $awaitingPayment++; 
  }
}

// Referral stats
require_once __DIR__ . '/../includes/referrals.php';
$refStats = get_referral_stats($pdo, $uid);
$refCode = ensure_user_ref_code($pdo, $uid);
$baseUrl = BASE_URL;
$refLink = $baseUrl . "/register.php?ref=" . $refCode;

// Load profile data to check completion
$profileStmt = $pdo->prepare("SELECT * FROM user_profiles WHERE user_id = ?");
$profileStmt->execute([$uid]);
$userProfile = $profileStmt->fetch(PDO::FETCH_ASSOC) ?: [];

// Check if profile is complete enough for quick start
$requiredFields = ['phone', 'date_of_birth', 'residential_address', 'city', 'state'];
$profileComplete = true;
foreach ($requiredFields as $field) {
    if (empty($userProfile[$field])) {
        $profileComplete = false;
        break;
    }
}

include __DIR__ . '/../includes/header.php';
?>
<style>
/* Dashboard Header */
.dash-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 32px;
}
.welcome-text {
    font-size: 24px;
    font-weight: 700;
    color: var(--text);
    margin: 0;
}
.date-text {
    color: var(--muted);
    font-size: 14px;
    margin-top: 4px;
}

/* KPI Cards */
.kpi-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    gap: 20px;
    margin-bottom: 32px;
}
.kpi-card {
    background: #fff;
    border: 1px solid var(--border);
    border-radius: 20px;
    padding: 24px;
    display: flex;
    align-items: center;
    gap: 16px;
    transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    box-shadow: var(--shadow-sm);
}
.kpi-card:hover {
    transform: translateY(-4px);
    box-shadow: var(--shadow);
    border-color: var(--primary);
}
.kpi-icon {
    width: 54px;
    height: 54px;
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
}
.kpi-content { flex: 1; }
.kpi-value { font-size: 28px; font-weight: 700; color: var(--text); line-height: 1.1; margin-bottom: 2px; }
.kpi-label { font-size: 13px; color: var(--muted); font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; }


/* Colors */
.bg-blue { background: #eff6ff; color: #2563eb; }
.bg-orange { background: #fff7ed; color: #ea580c; }
.bg-green { background: #f0fdf4; color: #16a34a; }
.bg-purple { background: #f5f3ff; color: #7c3aed; }

/* Content Grid */
.content-grid {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 24px;
}
@media (max-width: 767px) {
    .dash-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 16px;
    }
    .kpi-grid {
        grid-template-columns: 1fr; /* Stack KPI cards on small screens */
    }
    .content-grid {
        grid-template-columns: 1fr; /* Already handled, but good to confirm */
    }
    .referral-card {
        padding: 20px;
    }
    .ref-stats {
        flex-direction: column; /* Stack referral stats */
        gap: 12px;
    }
    .ref-input-group {
        flex-direction: column; /* Stack input and button */
        gap: 8px;
    }
    .ref-input {
        width: 100%;
    }
    .ref-btn {
        width: 100%;
        justify-content: center;
    }
    .modal-card {
        width: calc(100% - 32px); /* Full width minus padding */
        margin: 0 auto;
    }
    .wizard-progress {
        padding: 0;
        margin-bottom: 24px;
    }
    .wizard-progress::before {
        left: 20px;
        right: 20px;
    }
    .step-label {
        font-size: 10px;
    }
    .service-card {
        flex-direction: column;
        align-items: flex-start;
        text-align: left;
        padding: 16px;
    }
    .service-arrow {
        position: absolute;
        top: 16px;
        right: 16px;
    }
    .service-info {
        width: 100%;
    }
    .service-price {
        margin-top: 8px;
    }
}

/* Recent Apps Table */
.apps-card {
    background: #fff;
    border: 1px solid var(--border);
    border-radius: 12px;
    overflow: hidden;
}
.card-header {
    padding: 16px 20px;
    border-bottom: 1px solid var(--border);
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.card-title { font-size: 16px; font-weight: 600; margin: 0; }
.app-item {
    display: flex;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid var(--border);
    gap: 16px;
    transition: background 0.1s;
    text-decoration: none;
    color: inherit;
}
.app-item:last-child { border-bottom: none; }
.app-item:hover { background: #f8fafc; }
.app-icon {
    width: 40px; height: 40px;
    background: #f1f5f9;
    border-radius: 8px;
    display: flex; align-items: center; justify-content: center;
    color: #64748b;
}
.app-info { flex: 1; }
.app-name { font-weight: 600; font-size: 14px; margin-bottom: 2px; }
.app-meta { font-size: 12px; color: var(--muted); }
.app-status { font-size: 12px; font-weight: 600; }

/* Referral Widget */
.referral-card {
    background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
    color: #fff;
    border-radius: 12px;
    padding: 24px;
    position: relative;
    overflow: hidden;
}
.referral-card::before {
    content: '';
    position: absolute;
    top: -20px; right: -20px;
    width: 100px; height: 100px;
    background: rgba(255,255,255,0.1);
    border-radius: 50%;
}
.ref-title { font-size: 18px; font-weight: 700; margin: 0 0 8px; }
.ref-desc { font-size: 13px; opacity: 0.9; margin-bottom: 20px; line-height: 1.4; }
.ref-stats {
    display: flex;
    gap: 16px;
    margin-bottom: 20px;
}
.ref-stat-item {
    background: rgba(255,255,255,0.15);
    padding: 8px 12px;
    border-radius: 8px;
    flex: 1;
}
.ref-val { font-size: 18px; font-weight: 700; }
.ref-lbl { font-size: 11px; opacity: 0.8; text-transform: uppercase; }
.ref-input-group {
    display: flex;
    background: rgba(255,255,255,0.2);
    border-radius: 8px;
    padding: 4px;
}
.ref-input {
    background: transparent;
    border: none;
    color: #fff;
    flex: 1;
    padding: 8px;
    font-size: 13px;
    outline: none;
}
.kpi-trend {
    font-size: 12px;
    color: #64748b;
    margin-top: 4px;
    font-weight: 500;
}

/* Quick Actions Panel */
.quick-actions-panel {
    background: white;
    border: 1px solid var(--border);
    border-radius: 24px;
    padding: 32px;
    margin-bottom: 32px;
    box-shadow: var(--shadow-sm);
}


.panel-title {
    font-size: 20px;
    font-weight: 700;
    margin: 0 0 20px 0;
    color: #1f2937;
}

.actions-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 16px;
}

.action-card {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 24px;
    border: 1px solid var(--border);
    border-radius: 20px;
    text-decoration: none;
    color: inherit;
    transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    background: #fcfcfd;
}

.action-card:hover {
    border-color: var(--primary);
    background: white;
    box-shadow: var(--shadow);
    transform: translateY(-4px);
}


.action-icon {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    flex-shrink: 0;
}

.bg-purple { background: #f3e8ff; color: #9333ea; }
.bg-yellow { background: #fef3c7; color: #f59e0b; }
.bg-red { background: #fef2f2; color: #dc2626; }

.action-content {
    flex: 1;
}

.action-title {
    font-size: 16px;
    font-weight: 600;
    color: #1f2937;
    margin-bottom: 4px;
}

.action-desc {
    font-size: 13px;
    color: #64748b;
    line-height: 1.4;
}

.action-arrow {
    font-size: 20px;
    color: #9ca3af;
    transition: color 0.2s ease;
}

.action-card:hover .action-arrow {
    color: var(--primary);
}

/* Enhanced Recent Applications */
.apps-card {
    background: white;
    border: 1px solid var(--border);
    border-radius: 24px;
    overflow: hidden;
    box-shadow: var(--shadow-sm);
}


.card-header {
    padding: 20px 24px;
    border-bottom: 1px solid #e5e7eb;
    background: #f8fafc;
}

.card-title {
    font-size: 18px;
    font-weight: 700;
    margin: 0;
    color: #1f2937;
}

.app-item {
    display: flex;
    align-items: center;
    padding: 20px 24px;
    border-bottom: 1px solid #f3f4f6;
    gap: 16px;
    transition: all 0.2s ease;
    text-decoration: none;
    color: inherit;
}

.app-item:last-child {
    border-bottom: none;
}

.app-item:hover {
    background: #f8fafc;
    border-left: 4px solid var(--primary);
}

.app-icon {
    width: 48px;
    height: 48px;
    background: #eff6ff;
    color: var(--primary);
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    flex-shrink: 0;
}

.app-info {
    flex: 1;
}

.app-name {
    font-weight: 600;
    font-size: 16px;
    color: #1f2937;
    margin-bottom: 4px;
}

.app-meta {
    font-size: 13px;
    color: #64748b;
}

.app-status {
    margin-left: auto;
}

.chip {
    padding: 6px 14px;
    border-radius: 999px;
    font-size: 11px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.05em;
}


.chip-draft { background: #f3f4f6; color: #6b7280; }
.chip-submitted { background: #dbeafe; color: #1e40af; }
.chip-processing { background: #fef3c7; color: #92400e; }
.chip-approved { background: #d1fae5; color: #065f46; }

/* Enhanced Referral Card */
.referral-card {
    background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
    color: white;
    border-radius: 24px;
    padding: 32px;
    position: relative;
    overflow: hidden;
    box-shadow: 0 10px 25px rgba(79, 70, 229, 0.2);
}


.referral-card::before {
    content: '';
    position: absolute;
    top: -20px;
    right: -20px;
    width: 120px;
    height: 120px;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 50%;
}

.ref-title {
    font-size: 20px;
    font-weight: 700;
    margin: 0 0 12px 0;
}

.ref-desc {
    font-size: 14px;
    opacity: 0.9;
    margin-bottom: 24px;
    line-height: 1.5;
}

.ref-stats {
    display: flex;
    gap: 24px;
    margin-bottom: 24px;
}

.ref-stat-item {
    text-align: center;
}

.ref-val {
    font-size: 24px;
    font-weight: 700;
    margin-bottom: 4px;
}

.ref-lbl {
    font-size: 12px;
    opacity: 0.8;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.ref-input-group {
    display: flex;
    gap: 8px;
    margin-bottom: 16px;
}

.ref-input {
    flex: 1;
    padding: 10px 14px;
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 8px;
    background: rgba(255, 255, 255, 0.1);
    color: white;
    font-size: 14px;
}

.ref-input::placeholder {
    color: rgba(255, 255, 255, 0.6);
}

.ref-btn {
    background: white;
    color: #4f46e5;
    border: none;
    border-radius: 8px;
    padding: 10px 16px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s ease;
}

.ref-btn:hover {
    background: #f8fafc;
    transform: translateY(-1px);
}

/* Mobile Responsive Enhancements */
@media (max-width: 768px) {
    .dash-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 16px;
    }
    
    .dash-header > div:last-child {
        width: 100%;
        display: flex;
        flex-direction: column;
        gap: 12px;
    }
    
    .kpi-grid {
        grid-template-columns: 1fr;
        gap: 16px;
    }
    
    .actions-grid {
        grid-template-columns: 1fr;
        gap: 12px;
    }
    
    .action-card {
        padding: 16px;
    }
    
    .ref-stats {
        flex-direction: column;
        gap: 16px;
    }
    
    .ref-input-group {
        flex-direction: column;
        gap: 12px;
    }
    
    .ref-input {
        width: 100%;
    }
    
    .ref-btn {
        width: 100%;
        padding: 12px;
    }
}
</style>

<!-- Enhanced Dashboard Header -->
<div class="dash-header">
    <div>
        <h1 class="welcome-text">Welcome back, <?=e(explode(' ', $user['full_name'])[0])?> 👋</h1>
        <div class="date-text"><?=date('l, F j, Y')?> • Here's your business registration overview</div>
    </div>
    <div style="display: flex; gap: 12px;">
        <button onclick="window.location.href='<?=url('customer/master-service.php?step=1')?>'" class="btn primary">
            <?=ui_icon('new', 18)?> Start New Application
        </button>
        <button onclick="openNewAppModal()" class="btn secondary">
            <?=ui_icon('new', 18)?> Quick Start
        </button>
    </div>
</div>

<!-- Enhanced KPI Cards -->
<div class="kpi-grid">
    <div class="kpi-card">
        <div class="kpi-icon bg-blue"><?=ui_icon('dashboard', 24)?></div>
        <div class="kpi-content">
            <div class="kpi-value"><?=number_format($activeApps)?></div>
            <div class="kpi-label">Active Applications</div>
            <div class="kpi-trend"><?= $activeApps > 0 ? '📈' : '📊' ?> <?= $activeApps > 0 ? 'In Progress' : 'No active apps' ?></div>
        </div>
    </div>
    <div class="kpi-card">
        <div class="kpi-icon bg-orange"><?=ui_icon('pricing', 24)?></div>
        <div class="kpi-content">
            <div class="kpi-value"><?=number_format($awaitingPayment)?></div>
            <div class="kpi-label">Awaiting Payment</div>
            <div class="kpi-trend">💳 <?= $awaitingPayment > 0 ? 'Action Required' : 'All paid' ?></div>
        </div>
    </div>
    <div class="kpi-card">
        <div class="kpi-icon bg-green"><?=ui_icon('check', 24)?></div>
        <div class="kpi-content">
            <div class="kpi-value"><?=number_format($approvedApps)?></div>
            <div class="kpi-label">Approved</div>
            <div class="kpi-trend">✅ <?= $approvedApps > 0 ? 'Completed' : 'None yet' ?></div>
        </div>
    </div>
</div>

<!-- Welcome Tips Section -->
<div class="welcome-tips" style="background: linear-gradient(135deg, #f0f9ff, #e0f2fe); border: 1px solid #bae6fd; border-radius: 16px; padding: 24px; margin-bottom: 32px;">
    <h3 style="color: #0c4a6e; margin-bottom: 16px; font-size: 18px;">🚀 Getting Started with Go Legal</h3>
    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 16px;">
        <div style="display: flex; gap: 12px;">
            <div style="font-size: 24px;">1️⃣</div>
            <div>
                <div style="font-weight: 600; color: #0c4a6e; margin-bottom: 4px;">Start Application</div>
                <div style="color: #075985; font-size: 14px;">Choose your service type and begin the registration process</div>
            </div>
        </div>
        <div style="display: flex; gap: 12px;">
            <div style="font-size: 24px;">2️⃣</div>
            <div>
                <div style="font-weight: 600; color: #0c4a6e; margin-bottom: 4px;">Upload Documents</div>
                <div style="color: #075985; font-size: 14px;">Provide required documents and information securely</div>
            </div>
        </div>
        <div style="display: flex; gap: 12px;">
            <div style="font-size: 24px;">3️⃣</div>
            <div>
                <div style="font-weight: 600; color: #0c4a6e; margin-bottom: 4px;">Track Progress</div>
                <div style="color: #075985; font-size: 14px;">Monitor your application status in real-time</div>
            </div>
        </div>
    </div>
</div>

<?php if ($profileComplete): ?>
<!-- Quick Start Banner for Returning Users -->
<div class="quick-start-banner" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%); border-radius: 16px; padding: 24px; margin-bottom: 32px; color: white; display: flex; align-items: center; gap: 20px; flex-wrap: wrap;">
    <div style="font-size: 40px;">⚡</div>
    <div style="flex: 1;">
        <h3 style="margin: 0 0 4px 0; font-size: 18px; font-weight: 700;">Quick Start Available!</h3>
        <p style="margin: 0; font-size: 14px; opacity: 0.95;">Your profile is complete. Start a new application with one click - no need to re-enter your information.</p>
    </div>
    <a href="<?=url('customer/master-service.php?step=1')?>" style="background: white; color: #059669; padding: 12px 24px; border-radius: 10px; font-weight: 600; text-decoration: none; white-space: nowrap; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
        Start Application →
    </a>
</div>
<?php endif; ?>

<!-- Quick Actions Panel -->
<div class="quick-actions-panel">
    <h3 class="panel-title">Quick Actions</h3>
    <div class="actions-grid">
        <a href="<?=url('customer/master-service.php?step=1')?>" class="action-card">
            <div class="action-icon bg-blue"><?=ui_icon('new', 20)?></div>
            <div class="action-content">
                <div class="action-title">Service Application</div>
                <div class="action-desc">Business registration, company formation, NGO setup</div>
            </div>
            <div class="action-arrow">→</div>
        </a>
        <a href="<?=url('customer/trademark-application.php?step=1')?>" class="action-card">
            <div class="action-icon bg-purple"><?=ui_icon('applications', 20)?></div>
            <div class="action-content">
                <div class="action-title">Trademark Registration</div>
                <div class="action-desc">Protect your brand identity</div>
            </div>
            <div class="action-arrow">→</div>
        </a>
        <a href="<?=url('customer/service-dashboard.php')?>" class="action-card">
            <div class="action-icon bg-green"><?=ui_icon('applications', 20)?></div>
            <div class="action-content">
                <div class="action-title">My Applications</div>
                <div class="action-desc">Track all your service applications</div>
            </div>
            <div class="action-arrow">→</div>
        </a>
        <a href="<?=url('customer/trademark-dashboard.php')?>" class="action-card">
            <div class="action-icon bg-orange"><?=ui_icon('applications', 20)?></div>
            <div class="action-content">
                <div class="action-title">Trademark Applications</div>
                <div class="action-desc">Monitor trademark registration progress</div>
            </div>
            <div class="action-arrow">→</div>
        </a>
        <a href="<?=url('customer/payments.php')?>" class="action-card">
            <div class="action-icon bg-red"><?=ui_icon('pricing', 20)?></div>
            <div class="action-content">
                <div class="action-title">Payment Center</div>
                <div class="action-desc">Complete pending payments</div>
            </div>
            <div class="action-arrow">→</div>
        </a>
        <a href="<?=url('customer/referrals.php')?>" class="action-card">
            <div class="action-icon bg-yellow"><?=ui_icon('users', 20)?></div>
            <div class="action-content">
                <div class="action-title">Referral Program</div>
                <div class="action-desc">Earn commissions from referrals</div>
            </div>
            <div class="action-arrow">→</div>
        </a>
        <a href="<?=url('customer/profile.php')?>" class="action-card">
            <div class="action-icon bg-purple"><?=ui_icon('user', 20)?></div>
            <div class="action-content">
                <div class="action-title">My Profile</div>
                <div class="action-desc">Manage your personal information</div>
            </div>
            <div class="action-arrow">→</div>
        </a>
    </div>
</div>

<div class="content-grid">
    <!-- Left Column: Recent Applications -->
    <div>
        <div class="apps-card">
            <div class="card-header">
                <h3 class="card-title">Recent Applications</h3>
            </div>
            
            <?php if (empty($rows)): ?>
                <div style="padding: 40px; text-align: center;">
                    <div style="font-size: 48px; margin-bottom: 16px; opacity: 0.5;">📋</div>
                    <h3 style="font-size: 18px; margin-bottom: 8px; color: #1f2937;">No applications yet</h3>
                    <p style="color: #64748b; margin-bottom: 24px;">Start your first business registration or trademark application</p>
                    <button onclick="window.location.href='<?=url('customer/master-service.php?step=1')?>'" class="btn primary">Start Your First Application</button>
                </div>
            <?php else: ?>
                <?php foreach (array_slice($rows, 0, 5) as $r): ?>
                <a href="<?=url('customer/view_application.php?id='.e((string)$r['id']))?>" class="app-item">
                    <div class="app-icon">
                        <?=ui_icon('applications', 20)?>
                    </div>
                    <div class="app-info">
                        <div class="app-name"><?=e($r['service_name'])?></div>
                        <div class="app-meta">ID: #<?=e((string)$r['id'])?> • <?=date('M j, Y', strtotime($r['created_at']))?></div>
                    </div>
                    <div class="app-status">
                        <span class="chip chip-<?=e($r['status'])?>"><?=ucfirst($r['status'])?></span>
                    </div>
                </a>
                <?php endforeach; ?>
                
                <?php if (count($rows) > 5): ?>
                <div style="padding: 16px 24px; text-align: center;">
                    <a href="<?=url('customer/service-dashboard.php')?>" style="color: var(--primary); text-decoration: none; font-weight: 600;">
                        View All Applications (<?=count($rows)?> total) →
                    </a>
                </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>

    <!-- Right Column: Referral & Promo -->
    <div>
        <div class="referral-card">
            <h3 class="ref-title">Refer & Earn</h3>
            <p class="ref-desc">Share your link and earn commissions for every successful business registration.</p>
            
            <div class="ref-stats">
                <div class="ref-stat-item">
                    <div class="ref-val"><?=number_format($refStats['registrations'])?></div>
                    <div class="ref-lbl">Signups</div>
                </div>
                <div class="ref-stat-item">
                    <div class="ref-val">₦<?=number_format($refStats['total_earnings'])?></div>
                    <div class="ref-lbl">Earned</div>
                </div>
            </div>
            
            <div class="ref-input-group">
                <input type="text" value="<?=e($refLink)?>" readonly class="ref-input" id="ref-link">
                <button class="ref-btn" onclick="
                    document.getElementById('ref-link').select();
                    document.execCommand('copy');
                    alert('Link copied!');
                ">Copy</button>
            </div>
            
            <div style="margin-top:16px; text-align:center">
                <a href="/customer/referrals.php" style="color:#fff; font-size:13px; text-decoration:none; opacity:0.9">View Dashboard →</a>
            </div>
        </div>
    </div>
</div>

<!-- New Application Modal -->
<div id="new-app-modal" class="modal-backdrop">
  <div class="modal-card">
    <div class="modal-header">
      <h3 class="modal-title">Start New Application</h3>
      <button onclick="closeModal()" class="modal-close-btn">&times;</button>
    </div>
    
    <div id="modal-step-content" class="modal-body">
      <!-- Initial Step 1 Content -->
      <div id="wizard-container">
        <div class="wizard-progress">
          <div class="step active">
            <div class="step-icon">1</div>
            <div class="step-label">Service</div>
          </div>
          <div class="step">
            <div class="step-icon">2</div>
            <div class="step-label">Details</div>
          </div>
          <div class="step">
            <div class="step-icon">3</div>
            <div class="step-label">Add-ons</div>
          </div>
          <div class="step">
            <div class="step-icon">4</div>
            <div class="step-label">Review</div>
          </div>
        </div>

        <div class="step-header">
          <h4>Select a Service</h4>
          <p>Choose the registration type that best fits your business needs.</p>
        </div>

        <div class="service-grid">
          <?php 
          $services = $pdo->query("SELECT * FROM services WHERE status='active'")->fetchAll();
          foreach($services as $s): 
          ?>
          <form method="post" action="/customer/new_application.php" 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">
                <?=ui_icon('check', 20)?>
              </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['cac_fee'] + (float)$s['service_fee']))?></div>
              </div>
              <div class="service-arrow">
                <?=ui_icon('arrow-right', 16)?>
              </div>
            </button>
          </form>
          <?php endforeach; ?>
        </div>
      </div>
    </div>
  </div>
</div>

<style>
/* Modal Core */
.modal-backdrop {
    display: none;
    position: fixed;
    inset: 0;
    background: rgba(15, 23, 42, 0.6);
    backdrop-filter: blur(8px);
    z-index: 1000;
    align-items: center;
    justify-content: center;
    padding: 16px;
    opacity: 0;
    transition: opacity 0.3s ease;
}
.modal-backdrop.show {
    display: flex;
    opacity: 1;
}
.modal-card {
    background: #fff;
    width: 100%;
    max-width: 640px;
    max-height: 90vh;
    border-radius: 24px;
    box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
    display: flex;
    flex-direction: column;
    overflow: hidden;
    transform: scale(0.95) translateY(10px);
    transition: transform 0.3s cubic-bezier(0.16, 1, 0.3, 1);
}
.modal-backdrop.show .modal-card {
    transform: scale(1) translateY(0);
}
.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    border-bottom: 1px solid var(--border);
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(8px);
    position: sticky;
    top: 0;
    z-index: 10;
}
.modal-title {
    font-size: 18px;
    font-weight: 700;
    color: var(--text);
    margin: 0;
}
.modal-close-btn {
    border: none;
    background: transparent;
    font-size: 24px;
    line-height: 1;
    color: var(--muted);
    cursor: pointer;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
}
.modal-close-btn:hover {
    background: #f1f5f9;
    color: var(--text);
}
.modal-body {
    padding: 0;
    overflow-y: auto;
    flex: 1;
    background: #f8fafc;
}
/* Custom Scrollbar */
.modal-body::-webkit-scrollbar { width: 6px; }
.modal-body::-webkit-scrollbar-track { background: transparent; }
.modal-body::-webkit-scrollbar-thumb { background-color: #cbd5e1; border-radius: 3px; }

/* Wizard Styles */
#wizard-container {
    padding: 24px;
    animation: fadeIn 0.3s ease;
}
@keyframes fadeIn { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); } }

.wizard-progress {
    display: flex;
    justify-content: space-between;
    margin-bottom: 32px;
    position: relative;
    padding: 0 12px;
}
.wizard-progress::before {
    content: '';
    position: absolute;
    top: 14px;
    left: 40px;
    right: 40px;
    height: 2px;
    background: #e2e8f0;
    z-index: 0;
}
.wizard-progress .step {
    position: relative;
    z-index: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    flex: 1;
}
.step-icon {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background: #fff;
    border: 2px solid #e2e8f0;
    color: #94a3b8;
    font-weight: 600;
    font-size: 13px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;
}
.step-label {
    font-size: 11px;
    font-weight: 600;
    color: #94a3b8;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    transition: all 0.3s;
}
.step.active .step-icon {
    border-color: var(--primary);
    background: var(--primary);
    color: #fff;
    box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.1);
}
.step.active .step-label {
    color: var(--primary);
}
.step.completed .step-icon {
    background: #10b981;
    border-color: #10b981;
    color: #fff;
}

/* Step Header */
.step-header {
    text-align: center;
    margin-bottom: 24px;
}
.step-header h4 {
    font-size: 20px;
    font-weight: 700;
    color: var(--text);
    margin: 0 0 8px;
}
.step-header p {
    font-size: 14px;
    color: var(--muted);
    margin: 0;
}

/* Service Grid */
.service-grid {
    display: grid;
    grid-template-columns: 1fr;
    gap: 16px;
}
.service-form { margin: 0; }
.service-card {
    width: 100%;
    text-align: left;
    background: #fff;
    border: 1px solid var(--border);
    border-radius: 16px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 16px;
    cursor: pointer;
    transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
    overflow: hidden;
}
.service-card:hover {
    border-color: var(--primary);
    transform: translateY(-2px);
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.05);
}
.service-icon {
    width: 48px;
    height: 48px;
    background: #eff6ff;
    color: var(--primary);
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    flex-shrink: 0;
}
.service-info { flex: 1; }
.service-name {
    font-size: 16px;
    font-weight: 700;
    color: var(--text);
    margin-bottom: 4px;
}
.service-desc {
    font-size: 13px;
    color: var(--muted);
    margin-bottom: 8px;
}
.service-price {
    font-size: 15px;
    font-weight: 700;
    color: var(--primary);
    background: #f0f9ff;
    padding: 4px 10px;
    border-radius: 8px;
    display: inline-block;
}
.service-arrow {
    color: #cbd5e1;
    transition: color 0.2s;
}
.service-card:hover .service-arrow {
    color: var(--primary);
}

/* Common Form Styles for subsequent steps */
.form-group { margin-bottom: 20px; }
.form-label {
    display: block;
    font-size: 13px;
    font-weight: 600;
    color: var(--text);
    margin-bottom: 6px;
}
.form-input, .form-select, .form-textarea {
    width: 100%;
    padding: 10px 14px;
    border: 1px solid var(--border);
    border-radius: 8px;
    font-size: 14px;
    transition: border-color 0.2s, box-shadow 0.2s;
    background: #fff;
}
.form-input:focus, .form-select:focus, .form-textarea:focus {
    border-color: var(--primary);
    outline: none;
    box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
}
.form-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
}
@media (max-width: 600px) {
    .form-grid { grid-template-columns: 1fr; }
}
.btn-block { width: 100%; justify-content: center; }
.btn-outline {
    background: transparent;
    border: 1px solid var(--border);
    color: var(--text);
}
.btn-outline:hover {
    background: #f8fafc;
    border-color: #cbd5e1;
}

/* Addon Card */
.addon-card {
    border: 1px solid var(--border);
    border-radius: 12px;
    padding: 16px;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: flex-start;
    gap: 12px;
    background: #fff;
    position: relative;
}
.addon-card:hover { border-color: var(--primary); background: #f8fafc; }
.addon-card.selected {
    border-color: var(--primary);
    background: #eff6ff;
    box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05);
}
.addon-checkbox { margin-top: 4px; accent-color: var(--primary); width: 18px; height: 18px; }
.addon-info { flex: 1; }
.addon-name { font-weight: 600; font-size: 14px; color: var(--text); display: block; margin-bottom: 2px; }
.addon-desc { font-size: 12px; color: var(--muted); line-height: 1.4; display: block; margin-bottom: 6px; }
.addon-price {
    font-size: 12px; font-weight: 700; color: var(--primary);
    background: #e0f2fe; padding: 2px 8px; border-radius: 6px; display: inline-block;
}

/* File Upload */
.file-upload-box {
    border: 2px dashed var(--border);
    border-radius: 12px;
    padding: 16px;
    text-align: center;
    cursor: pointer;
    transition: all 0.2s;
    background: #fff;
    position: relative;
}
.file-upload-box:hover { border-color: var(--primary); background: #f0f9ff; }
.file-upload-box input[type="file"] {
    position: absolute; inset: 0; opacity: 0; cursor: pointer; width: 100%; height: 100%;
}
.file-label-text { font-size: 13px; color: var(--muted); pointer-events: none; }
.file-label-strong { font-weight: 600; color: var(--primary); }

/* Review Summary */
.review-card {
    background: #fff;
    border: 1px solid var(--border);
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 20px;
}
.review-row {
    display: flex;
    justify-content: space-between;
    padding: 8px 0;
    border-bottom: 1px solid #f1f5f9;
    font-size: 14px;
}
.review-row:last-child { border-bottom: none; }
.review-label { color: var(--muted); }
.review-val { font-weight: 600; color: var(--text); text-align: right; }
</style>

<script>
function openNewAppModal() {
    var modal = document.getElementById('new-app-modal');
    modal.style.display = 'flex';
    // Force reflow
    void modal.offsetWidth;
    modal.classList.add('show');
}
function closeModal() {
    var modal = document.getElementById('new-app-modal');
    modal.classList.remove('show');
    setTimeout(function() {
        modal.style.display = 'none';
    }, 300); // Match transition duration
}
document.getElementById('new-app-modal').addEventListener('click', function(e) {
    if (e.target === this) closeModal();
});

// Modal Wizard Logic
function bindModalForms() {
    var forms = document.querySelectorAll('#new-app-modal form');
    forms.forEach(f => {
        // Avoid double binding
        if(f.dataset.bound) return;
        f.dataset.bound = true;
        
        f.onsubmit = function(e) {
            e.preventDefault();
            var btn = f.querySelector('button[type="submit"]');
            var originalText = btn.innerHTML; // Use innerHTML to preserve icons
            btn.disabled = true;
            btn.textContent = 'Processing...';
            
            var fd = new FormData(f);
            var url = f.action;
            if (!url.includes('ajax=1')) url += (url.includes('?')?'&':'?') + 'ajax=1';
            
            fetch(url, { method: 'POST', body: fd, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
                .then(r => r.json())
                .then(res => {
                    if (res.status === 'success') {
                        if (res.redirect) {
                            window.location.href = res.redirect;
                        } else if (res.next) {
                            loadStep(res.next);
                        }
                    } else {
                        alert('Error: ' + (res.message || 'Unknown error'));
                        btn.disabled = false;
                        btn.innerHTML = originalText;
                    }
                })
                .catch(err => {
                    console.error(err);
                    alert('Network error');
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                });
        };
    });
}

function loadStep(url) {
    var container = document.getElementById('modal-step-content');
    container.style.opacity = '0.5';
    
    // Ensure ajax=1 is present
    if (!url.includes('ajax=1')) url += (url.includes('?')?'&':'?') + 'ajax=1';

    fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
        .then(r => r.text())
        .then(html => {
            // Extract wizard container
            var parser = new DOMParser();
            var doc = parser.parseFromString(html, 'text/html');
            var newContent = doc.getElementById('wizard-container');
            
            if (newContent) {
                container.innerHTML = '';
                container.appendChild(newContent);
                
                // Re-bind forms in the new content
                bindModalForms();
                
                // Also bind back buttons (which are just type="button" with onclick)
                // Note: My PHP code generates onclick="loadStep(...)". This works because loadStep is global.
            } else {
                console.error('Wizard container not found in response');
            }
            container.style.opacity = '1';
        });
}

// Bind initial Step 1 forms
document.addEventListener('DOMContentLoaded', function() {
    bindModalForms();
});
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
