<?php
/**
 * IBVTE – Affiliation Application Status Tracker
 */
require_once __DIR__ . '/../config.php';
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/../includes/db.php';
$db = DB();

$app    = null;
$error  = null;
$refId  = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $refId = strtoupper(trim($_POST['ref_id'] ?? ''));
    if (empty($refId)) {
        $error = 'Please enter your Application Reference Number.';
    } else {
        $app = $db->fetchOne(
            "SELECT * FROM affiliation_applications WHERE application_number = ?",
            [$refId]
        );
        if (!$app) {
            $error = 'No application found with reference number <strong>' . htmlspecialchars($refId) . '</strong>. Please check and try again.';
        }
    }
}

// Status config
$statusMap = [
    'draft'                => ['label'=>'Draft',              'icon'=>'fas fa-pencil-alt',   'color'=>'secondary', 'pct'=>5],
    'submitted'            => ['label'=>'Submitted',          'icon'=>'fas fa-paper-plane',  'color'=>'info',      'pct'=>25],
    'under_review'         => ['label'=>'Under Review',       'icon'=>'fas fa-search',       'color'=>'warning',   'pct'=>50],
    'inspection_scheduled' => ['label'=>'Inspection Scheduled','icon'=>'fas fa-calendar-check','color'=>'primary', 'pct'=>75],
    'approved'             => ['label'=>'Approved ✓',         'icon'=>'fas fa-check-circle', 'color'=>'success',   'pct'=>100],
    'rejected'             => ['label'=>'Rejected',           'icon'=>'fas fa-times-circle', 'color'=>'danger',    'pct'=>100],
    'suspended'            => ['label'=>'Suspended',          'icon'=>'fas fa-pause-circle', 'color'=>'dark',      'pct'=>100],
];
$currentStatus = $app ? ($statusMap[$app['application_status']] ?? $statusMap['submitted']) : null;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Application Status – <?= APP_SHORT_NAME ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root { --primary:#3b0b7c; --secondary:#6c4ab6; --accent:#ffd700; }
        body { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; font-family:'Segoe UI',sans-serif; }
        .tracker-card { background:#fff; border-radius:20px; box-shadow:0 20px 60px rgba(0,0,0,.2); overflow:hidden; max-width:780px; margin:40px auto; }
        .tracker-header { background:linear-gradient(135deg,var(--primary),var(--secondary)); color:#fff; padding:35px 40px; text-align:center; }
        .tracker-body { padding:40px; }

        /* Search box */
        .search-box { background:#f8f9fa; border-radius:15px; padding:30px; margin-bottom:0; }
        .search-box .input-group { box-shadow:0 4px 20px rgba(0,0,0,.08); border-radius:12px; overflow:hidden; }
        .search-box input { border:none; font-size:1.1rem; padding:14px 20px; }
        .search-box input:focus { box-shadow:none; outline:none; }
        .search-btn { background:linear-gradient(135deg,var(--primary),var(--secondary)); color:#fff; border:none; padding:14px 30px; font-weight:600; }

        /* Progress steps */
        .steps-wrap { display:flex; justify-content:space-between; position:relative; margin:30px 0 20px; }
        .steps-wrap::before { content:''; position:absolute; top:22px; left:0; right:0; height:4px; background:#e9ecef; z-index:0; }
        .step-bar { position:absolute; top:22px; left:0; height:4px; background:linear-gradient(90deg,var(--primary),var(--secondary)); z-index:1; transition:width .8s ease; }
        .step { flex:1; text-align:center; position:relative; z-index:2; }
        .step-dot { width:44px; height:44px; border-radius:50%; background:#e9ecef; color:#999; display:flex; align-items:center; justify-content:center; margin:0 auto 8px; font-size:1.1rem; transition:all .4s; }
        .step.done   .step-dot { background:var(--primary); color:#fff; }
        .step.active .step-dot { background:var(--accent); color:#333; box-shadow:0 0 0 4px rgba(255,215,0,.4); transform:scale(1.15); }
        .step.fail   .step-dot { background:#dc3545; color:#fff; }
        .step-lbl { font-size:.75rem; font-weight:600; color:#888; }
        .step.done .step-lbl, .step.active .step-lbl { color:var(--primary); }
        .step.fail .step-lbl { color:#dc3545; }

        /* Result card */
        .info-grid { display:grid; grid-template-columns:1fr 1fr; gap:16px; }
        .info-item { background:#f8f9fa; border-radius:10px; padding:14px 18px; }
        .info-item .label { font-size:.78rem; text-transform:uppercase; letter-spacing:.05em; color:#888; font-weight:600; }
        .info-item .value { font-size:1rem; font-weight:700; color:#333; margin-top:4px; }
        .status-badge { display:inline-flex; align-items:center; gap:8px; padding:8px 20px; border-radius:50px; font-weight:700; font-size:1rem; }
        @media(max-width:600px){ .info-grid{grid-template-columns:1fr;} .tracker-body{padding:24px;} }
    </style>
</head>
<body>
<div class="container px-3">
    <div class="tracker-card">
        <!-- Header -->
        <div class="tracker-header">
            <img src="../assets/images/logo.jpeg" alt="IBVTE" style="height:70px;border-radius:50%;border:4px solid rgba(255,255,255,.3);margin-bottom:16px;">
            <h4 class="fw-bold mb-1"><?= APP_NAME ?></h4>
            <p class="mb-0 opacity-75">Affiliation Application Status Tracker</p>
        </div>

        <div class="tracker-body">

            <!-- Search Form -->
            <div class="search-box">
                <h5 class="fw-bold mb-3"><i class="fas fa-search me-2 text-primary"></i>Track Your Application</h5>
                <form method="POST" autocomplete="off">
                    <div class="input-group">
                        <input type="text" name="ref_id" class="form-control"
                               placeholder="Enter Application Reference No. (e.g. AFF20260507XXXXXX)"
                               value="<?= htmlspecialchars($refId) ?>" required>
                        <button type="submit" class="search-btn">
                            <i class="fas fa-search me-2"></i>Check Status
                        </button>
                    </div>
                </form>
            </div>

            <!-- Error -->
            <?php if ($error): ?>
            <div class="alert alert-danger mt-4 d-flex align-items-center gap-2">
                <i class="fas fa-exclamation-circle fa-lg"></i>
                <div><?= $error ?></div>
            </div>
            <?php endif; ?>

            <!-- Result -->
            <?php if ($app): ?>
            <div class="mt-4">

                <!-- Status Badge -->
                <div class="text-center mb-4">
                    <div class="status-badge bg-<?= $currentStatus['color'] ?> text-white d-inline-flex">
                        <i class="<?= $currentStatus['icon'] ?>"></i>
                        <?= $currentStatus['label'] ?>
                    </div>
                </div>

                <!-- Progress Steps -->
                <?php
                $steps = ['submitted','under_review','inspection_scheduled','approved'];
                $isRejected = $app['application_status'] === 'rejected';
                $pct = $isRejected ? 0 : ($currentStatus['pct'] ?? 0);
                $currentIdx = array_search($app['application_status'], $steps);
                ?>
                <div class="steps-wrap">
                    <div class="step-bar" style="width:<?= $pct ?>%;"></div>
                    <?php foreach ($steps as $i => $s):
                        $cls = 'step';
                        if ($isRejected) { $cls = 'step'; }
                        elseif ($i < $currentIdx || $app['application_status'] === 'approved') $cls = 'step done';
                        elseif ($i === $currentIdx) $cls = 'step active';
                        $icons = ['fas fa-paper-plane','fas fa-search','fas fa-clipboard-check','fas fa-graduation-cap'];
                        $lbls  = ['Submitted','Under Review','Inspection','Approved'];
                    ?>
                    <div class="<?= $cls ?>">
                        <div class="step-dot"><i class="<?= $icons[$i] ?>"></i></div>
                        <div class="step-lbl"><?= $lbls[$i] ?></div>
                    </div>
                    <?php endforeach; ?>
                </div>

                <?php if ($isRejected): ?>
                <div class="alert alert-danger text-center mb-4">
                    <i class="fas fa-times-circle me-2"></i>Your application has been <strong>rejected</strong>.
                    <?php if ($app['review_remarks']): ?>
                        <br><small>Reason: <?= htmlspecialchars($app['review_remarks']) ?></small>
                    <?php endif; ?>
                    <br><a href="apply.php" class="btn btn-sm btn-danger mt-2">Apply Again</a>
                </div>
                <?php endif; ?>

                <!-- Application Details Grid -->
                <div class="info-grid mb-4">
                    <div class="info-item">
                        <div class="label">Reference Number</div>
                        <div class="value text-primary"><?= htmlspecialchars($app['application_number'] ?? '#'.$app['id']) ?></div>
                    </div>
                    <div class="info-item">
                        <div class="label">Submitted On</div>
                        <div class="value"><?= $app['submitted_at'] ? date('d M Y', strtotime($app['submitted_at'])) : date('d M Y', strtotime($app['created_at'])) ?></div>
                    </div>
                    <div class="info-item">
                        <div class="label">Institution Name</div>
                        <div class="value"><?= htmlspecialchars($app['institution_name']) ?></div>
                    </div>
                    <div class="info-item">
                        <div class="label">Director / Principal</div>
                        <div class="value"><?= htmlspecialchars($app['director_name']) ?></div>
                    </div>
                    <div class="info-item">
                        <div class="label">Location</div>
                        <div class="value"><?= htmlspecialchars(($app['city'] ?? '') . ', ' . ($app['state'] ?? '')) ?></div>
                    </div>
                    <div class="info-item">
                        <div class="label">Contact Mobile</div>
                        <div class="value"><?= htmlspecialchars($app['director_mobile']) ?></div>
                    </div>
                </div>

                <?php if ($app['application_status'] === 'approved'): ?>
                <div class="alert alert-success text-center">
                    <i class="fas fa-check-circle fa-2x mb-2 d-block"></i>
                    <strong>Congratulations! Your affiliation has been approved.</strong><br>
                    <?php if ($app['approval_valid_until']): ?>
                    <small>Valid until: <strong><?= date('d M Y', strtotime($app['approval_valid_until'])) ?></strong></small><br>
                    <?php endif; ?>
                    <small class="text-muted">Your login credentials have been shared with you by IBVTE.</small>
                </div>
                <?php endif; ?>

                <!-- Status Timeline -->
                <div class="border-top pt-3 mt-2">
                    <h6 class="fw-bold mb-3 text-muted"><i class="fas fa-history me-2"></i>Application Timeline</h6>
                    <ul class="list-unstyled">
                        <li class="d-flex gap-3 mb-3">
                            <div class="text-center" style="width:36px;">
                                <div class="rounded-circle bg-info d-flex align-items-center justify-content-center text-white" style="width:36px;height:36px;">
                                    <i class="fas fa-paper-plane" style="font-size:.85rem;"></i>
                                </div>
                            </div>
                            <div>
                                <div class="fw-bold">Application Submitted</div>
                                <small class="text-muted"><?= $app['submitted_at'] ? date('d M Y, h:i A', strtotime($app['submitted_at'])) : date('d M Y, h:i A', strtotime($app['created_at'])) ?></small>
                            </div>
                        </li>
                        <?php if (in_array($app['application_status'], ['under_review','inspection_scheduled','approved','rejected'])): ?>
                        <li class="d-flex gap-3 mb-3">
                            <div class="text-center" style="width:36px;">
                                <div class="rounded-circle bg-warning d-flex align-items-center justify-content-center text-dark" style="width:36px;height:36px;">
                                    <i class="fas fa-search" style="font-size:.85rem;"></i>
                                </div>
                            </div>
                            <div>
                                <div class="fw-bold">Taken Under Review</div>
                                <small class="text-muted">By IBVTE Affiliation Committee</small>
                            </div>
                        </li>
                        <?php endif; ?>
                        <?php if (in_array($app['application_status'], ['approved','rejected'])): ?>
                        <li class="d-flex gap-3 mb-3">
                            <div class="text-center" style="width:36px;">
                                <div class="rounded-circle bg-<?= $app['application_status'] === 'approved' ? 'success' : 'danger' ?> d-flex align-items-center justify-content-center text-white" style="width:36px;height:36px;">
                                    <i class="fas fa-<?= $app['application_status'] === 'approved' ? 'check' : 'times' ?>" style="font-size:.85rem;"></i>
                                </div>
                            </div>
                            <div>
                                <div class="fw-bold"><?= $app['application_status'] === 'approved' ? 'Application Approved' : 'Application Rejected' ?></div>
                                <small class="text-muted"><?= $app['approved_at'] ? date('d M Y, h:i A', strtotime($app['approved_at'])) : 'Decision date not recorded' ?></small>
                            </div>
                        </li>
                        <?php endif; ?>
                    </ul>
                </div>

            </div>
            <?php endif; ?>

            <!-- Help text -->
            <?php if (!$app && !$error): ?>
            <div class="mt-4 text-center text-muted">
                <i class="fas fa-info-circle me-2"></i>
                Enter the Reference Number you received after submitting your affiliation application.
                <br><small>e.g. <code>AFF20260507XXXXXX</code></small>
                <hr>
                <p class="small">Have not applied yet? <a href="apply.php" class="text-primary fw-bold">Apply for Affiliation →</a></p>
            </div>
            <?php endif; ?>

        </div><!-- /.tracker-body -->
    </div><!-- /.tracker-card -->

    <p class="text-center text-white opacity-75 pb-4 small">
        For help, contact IBVTE: <?= INSTITUTION_PHONE ?> | <?= INSTITUTION_EMAIL ?>
    </p>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
