<?php

declare(strict_types=1);

require_once __DIR__ . '/../Core/Database.php';

session_start();

$pdo = Database::connection();

/*
|--------------------------------------------------------------------------
| AUTHENTICATION
|--------------------------------------------------------------------------
*/

if (empty($_SESSION['admin_id'])) {
    header('Location: ../public/login.php');
    exit;
}

/*
|--------------------------------------------------------------------------
| HELPERS
|--------------------------------------------------------------------------
*/

function e(mixed $value): string
{
    return htmlspecialchars(
        (string)($value ?? ''),
        ENT_QUOTES,
        'UTF-8'
    );
}

function setting(
    PDO $pdo,
    string $key,
    string $default = ''
): string {

    $stmt = $pdo->prepare("
        SELECT setting_value
        FROM app_settings
        WHERE setting_key = ?
        LIMIT 1
    ");

    $stmt->execute([$key]);

    $value = $stmt->fetchColumn();

    return $value !== false
        ? (string)$value
        : $default;
}

/*
|--------------------------------------------------------------------------
| MESSAGES
|--------------------------------------------------------------------------
*/

$successMessage = '';
$errorMessage   = '';

/*
|--------------------------------------------------------------------------
| SAVE SETTINGS
|--------------------------------------------------------------------------
*/

if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
    && isset($_POST['save_settings'])
) {

    /*
    |--------------------------------------------------------------------------
    | APPLICATION STATUS
    |--------------------------------------------------------------------------
    */

    $applicationStatus =
        $_POST['application_status'] ?? 'OPEN';

    if (
        !in_array(
            $applicationStatus,
            ['OPEN', 'CLOSED'],
            true
        )
    ) {
        $applicationStatus = 'OPEN';
    }

    /*
    |--------------------------------------------------------------------------
    | APPLICATION PRICE
    |--------------------------------------------------------------------------
    */

    $applicationPrice =
        trim($_POST['application_price'] ?? '0');

    /*
     * Keep only numbers and decimal point.
     */
    $applicationPrice =
        preg_replace(
            '/[^0-9.]/',
            '',
            $applicationPrice
        );

    if (
        $applicationPrice === ''
        || !is_numeric($applicationPrice)
    ) {
        $applicationPrice = '0';
    }

    /*
     * Prevent negative values.
     */
    if ((float)$applicationPrice < 0) {
        $applicationPrice = '0';
    }

    /*
    |--------------------------------------------------------------------------
    | OTHER SETTINGS
    |--------------------------------------------------------------------------
    */

    $settings = [

        'application_status'
            => $applicationStatus,

        'application_price'
            => $applicationPrice,

        'contact_name'
            => trim($_POST['contact_name'] ?? ''),

        'phone'
            => trim($_POST['phone'] ?? ''),

        'whatsapp'
            => trim($_POST['whatsapp'] ?? ''),

        'email'
            => trim($_POST['email'] ?? ''),

        'instagram'
            => trim($_POST['instagram'] ?? ''),

        'payment_code'
            => trim($_POST['payment_code'] ?? ''),

        'whatsapp_group'
            => trim($_POST['whatsapp_group'] ?? ''),
    ];

    try {

        $pdo->beginTransaction();

        $stmt = $pdo->prepare("
            INSERT INTO app_settings
                (
                    setting_key,
                    setting_value
                )
            VALUES
                (?, ?)
            ON DUPLICATE KEY UPDATE
                setting_value = VALUES(setting_value)
        ");

        foreach ($settings as $key => $value) {

            $stmt->execute([
                $key,
                $value
            ]);
        }

        $pdo->commit();

        $successMessage =
            'Settings saved successfully.';

    } catch (Throwable $e) {

        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        $errorMessage =
            'Unable to save settings. '
            . $e->getMessage();
    }
}

/*
|--------------------------------------------------------------------------
| LOAD SETTINGS
|--------------------------------------------------------------------------
*/

$applicationStatus = setting(
    $pdo,
    'application_status',
    'OPEN'
);

/*
|--------------------------------------------------------------------------
| APPLICATION PRICE
|--------------------------------------------------------------------------
*/

$applicationPrice = setting(
    $pdo,
    'application_price',
    '0'
);

$contactName = setting(
    $pdo,
    'contact_name'
);

$phone = setting(
    $pdo,
    'phone'
);

$whatsapp = setting(
    $pdo,
    'whatsapp'
);

$email = setting(
    $pdo,
    'email'
);

$instagram = setting(
    $pdo,
    'instagram'
);

$paymentCode = setting(
    $pdo,
    'payment_code'
);

$whatsappGroup = setting(
    $pdo,
    'whatsapp_group'
);

/*
|--------------------------------------------------------------------------
| ADMIN
|--------------------------------------------------------------------------
*/

$adminName = 'Administrator';

try {

    $adminId =
        (int)$_SESSION['admin_id'];

    $stmt = $pdo->prepare("
        SELECT *
        FROM admin_users
        WHERE id = ?
        LIMIT 1
    ");

    $stmt->execute([
        $adminId
    ]);

    $admin =
        $stmt->fetch(
            PDO::FETCH_ASSOC
        );

    if ($admin) {

        if (!empty($admin['name'])) {

            $adminName =
                $admin['name'];

        } elseif (!empty($admin['full_name'])) {

            $adminName =
                $admin['full_name'];

        } elseif (!empty($admin['username'])) {

            $adminName =
                $admin['username'];
        }
    }

} catch (Throwable $e) {
    // Keep default administrator name.
}

/*
|--------------------------------------------------------------------------
| STATISTICS
|--------------------------------------------------------------------------
*/

$totalApplications = (int)$pdo->query("
    SELECT COUNT(*)
    FROM applications
")->fetchColumn();

$submittedApplications = (int)$pdo->query("
    SELECT COUNT(*)
    FROM applications
    WHERE status = 'SUBMITTED'
")->fetchColumn();

$processingApplications = (int)$pdo->query("
    SELECT COUNT(*)
    FROM applications
    WHERE status = 'PROCESSING'
")->fetchColumn();

$needsCorrectionApplications = (int)$pdo->query("
    SELECT COUNT(*)
    FROM applications
    WHERE status = 'NEEDS_CORRECTION'
")->fetchColumn();

$completedApplications = (int)$pdo->query("
    SELECT COUNT(*)
    FROM applications
    WHERE status = 'COMPLETED'
")->fetchColumn();

$cancelledApplications = (int)$pdo->query("
    SELECT COUNT(*)
    FROM applications
    WHERE status = 'CANCELLED'
")->fetchColumn();

/*
|--------------------------------------------------------------------------
| FILTERS
|--------------------------------------------------------------------------
*/

$search =
    trim($_GET['search'] ?? '');

$statusFilter =
    trim($_GET['status'] ?? '');

$allowedStatuses = [

    'SUBMITTED',
    'PROCESSING',
    'NEEDS_CORRECTION',
    'CANCELLED'
];

$where = [];
$params = [];

/*
|--------------------------------------------------------------------------
| SEARCH
|--------------------------------------------------------------------------
*/

if ($search !== '') {

    $where[] = "
        (
            a.application_number LIKE ?
            OR a.full_name LIKE ?
            OR a.phone LIKE ?
            OR a.index_number LIKE ?
            OR a.email LIKE ?
        )
    ";

    $searchValue =
        '%' . $search . '%';

    for ($i = 0; $i < 5; $i++) {

        $params[] =
            $searchValue;
    }
}

/*
|--------------------------------------------------------------------------
| STATUS FILTER
|--------------------------------------------------------------------------
*/

if (
    in_array(
        $statusFilter,
        $allowedStatuses,
        true
    )
) {

    $where[] =
        "a.status = ?";

    $params[] =
        $statusFilter;
}

/*
|--------------------------------------------------------------------------
| COMPLETED APPLICATIONS
|--------------------------------------------------------------------------
|
| Completed applications are intentionally excluded
| from the main Applications list.
|
*/

$where[] =
    "a.status <> 'COMPLETED'";

$whereSql =
    'WHERE ' .
    implode(
        ' AND ',
        $where
    );

/*
|--------------------------------------------------------------------------
| APPLICATIONS
|--------------------------------------------------------------------------
*/

$sql = "

    SELECT

        a.id,

        a.application_number,

        a.university_id,
        a.department_id,
        a.program_id,

        a.email,
        a.index_number,
        a.nid_passport,

        a.full_name,
        a.phone,

        a.father_name,
        a.father_phone,

        a.mother_name,
        a.mother_phone,

        a.province,
        a.district,
        a.sector,
        a.cell,
        a.village,
        a.address,

        a.education_school,
        a.education_combination,
        a.education_year,

        a.applicant_type,

        a.passport_photo,
        a.nid_photo,
        a.result_slip,

        a.status,
        a.admin_note,

        a.application_price,

        a.created_at,
        a.updated_at,

        u.name AS university_name,
        u.code AS university_code,
        u.application_url AS university_application_url,

        d.name AS department_name,

        p.option_name

    FROM applications a

    LEFT JOIN universities u
        ON u.id = a.university_id

    LEFT JOIN departments d
        ON d.id = a.department_id

    LEFT JOIN programs p
        ON p.id = a.program_id

    $whereSql

    ORDER BY a.created_at DESC

    LIMIT 200
";

$stmt =
    $pdo->prepare($sql);

$stmt->execute($params);

$applications =
    $stmt->fetchAll(
        PDO::FETCH_ASSOC
    );

/*
|--------------------------------------------------------------------------
| COMPLETED APPLICATIONS
|--------------------------------------------------------------------------
*/

$completedStmt = $pdo->query("
    SELECT

        a.id,
        a.application_number,

        a.full_name,
        a.phone,

        a.application_price,

        a.status,
        a.updated_at,

        u.name AS university_name,

        d.name AS department_name,

        p.option_name

    FROM applications a

    LEFT JOIN universities u
        ON u.id = a.university_id

    LEFT JOIN departments d
        ON d.id = a.department_id

    LEFT JOIN programs p
        ON p.id = a.program_id

    WHERE a.status = 'COMPLETED'

    ORDER BY a.updated_at DESC

    LIMIT 200
");

$completedList =
    $completedStmt->fetchAll(
        PDO::FETCH_ASSOC
    );

?>
<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta
    name="viewport"
    content="width=device-width, initial-scale=1.0"
>

<title>SmartApply Admin</title>

<style>

:root {

    --primary: #2563eb;
    --primary-dark: #1d4ed8;

    --bg: #f5f7fb;
    --card: #ffffff;

    --text: #172033;
    --muted: #6b7280;

    --border: #e5e7eb;

    --success: #15803d;
    --danger: #dc2626;
    --warning: #d97706;

    --shadow:
        0 8px 30px rgba(
            15,
            23,
            42,
            .07
        );
}

* {
    box-sizing: border-box;
}

body {

    margin: 0;

    font-family:
        Inter,
        ui-sans-serif,
        system-ui,
        -apple-system,
        BlinkMacSystemFont,
        "Segoe UI",
        sans-serif;

    background: var(--bg);

    color: var(--text);
}

a {
    text-decoration: none;
    color: inherit;
}

button,
input,
select,
textarea {
    font: inherit;
}

.layout {

    min-height: 100vh;

    display: flex;
}

/* SIDEBAR */

.sidebar {

    width: 250px;

    background: #111827;

    color: white;

    padding: 24px 18px;

    position: fixed;

    inset: 0 auto 0 0;

    z-index: 20;
}

.brand {

    font-size: 22px;

    font-weight: 800;

    padding:
        10px 12px 28px;
}

.brand span {
    color: #60a5fa;
}

.nav {

    display: flex;

    flex-direction: column;

    gap: 7px;
}

.nav a {

    padding: 12px 14px;

    border-radius: 10px;

    color: #cbd5e1;

    transition: .2s;
}

.nav a:hover,
.nav a.active {

    background: #1e293b;

    color: white;
}

.logout {
    margin-top: 30px;
}

/* MAIN */

.main {

    width: 100%;

    margin-left: 250px;

    padding: 28px;
}

.topbar {

    display: flex;

    justify-content: space-between;

    align-items: center;

    gap: 20px;

    margin-bottom: 28px;
}

.topbar h1 {

    margin: 0;

    font-size: 28px;
}

.topbar p {

    margin: 6px 0 0;

    color: var(--muted);
}

.admin-badge {

    background: white;

    border:
        1px solid var(--border);

    padding: 10px 15px;

    border-radius: 12px;
}

/* STATS */

.stats {

    display: grid;

    grid-template-columns:
        repeat(6, minmax(0, 1fr));

    gap: 16px;

    margin-bottom: 28px;
}

.card {

    background: var(--card);

    border:
        1px solid var(--border);

    border-radius: 16px;

    box-shadow: var(--shadow);
}

.stat {

    padding: 20px;
}

.stat-title {

    color: var(--muted);

    font-size: 13px;
}

.stat-number {

    font-size: 29px;

    font-weight: 800;

    margin-top: 7px;
}

/* SECTION */

.section {

    padding: 24px;

    margin-bottom: 28px;
}

.section-header {

    margin-bottom: 22px;
}

.section-header h2 {

    margin: 0;

    font-size: 20px;
}

.section-header p {

    margin: 5px 0 0;

    color: var(--muted);
}

/* ALERT */

.alert {

    padding: 13px 15px;

    border-radius: 10px;

    margin-bottom: 18px;
}

.alert.success {

    background: #dcfce7;

    color: #166534;
}

.alert.error {

    background: #fee2e2;

    color: #991b1b;
}

/* SETTINGS */

.settings-grid {

    display: grid;

    grid-template-columns:
        repeat(2, minmax(0, 1fr));

    gap: 18px;
}

.field {

    display: flex;

    flex-direction: column;

    gap: 7px;
}

.field.full {

    grid-column: 1 / -1;
}

.field label {

    font-size: 14px;

    font-weight: 700;
}

.field input,
.field select,
.field textarea {

    width: 100%;

    padding: 12px 13px;

    border:
        1px solid var(--border);

    border-radius: 10px;

    outline: none;

    background: white;
}

.field textarea {

    min-height: 100px;

    resize: vertical;
}

.field input:focus,
.field select:focus,
.field textarea:focus {

    border-color:
        var(--primary);
}

.status-options {

    display: flex;

    gap: 12px;
}

.status-option {

    flex: 1;
}

.status-option input {

    display: none;
}

.status-option label {

    display: block;

    text-align: center;

    padding: 13px;

    border:
        2px solid var(--border);

    border-radius: 10px;

    cursor: pointer;
}

.status-option input:checked + label {

    border-color:
        var(--primary);

    background: #eff6ff;

    color: var(--primary);
}

/* PRICE */

.price-box {

    background: #eff6ff;

    border:
        1px solid #bfdbfe;

    border-radius: 12px;

    padding: 15px;

    min-height: 73px;

    display: flex;

    flex-direction: column;

    justify-content: center;
}

.price-box strong {

    display: block;

    font-size: 13px;

    color: var(--muted);
}

.price-value {

    font-size: 25px;

    font-weight: 800;

    color: var(--primary);

    margin-top: 4px;
}

/* BUTTONS */

.btn {

    border: 0;

    border-radius: 9px;

    padding: 10px 14px;

    cursor: pointer;

    font-weight: 700;
}

.btn-primary {

    background: var(--primary);

    color: white;
}

.btn-primary:hover {

    background:
        var(--primary-dark);
}

.btn-success {

    background: #16a34a;

    color: white;
}

.btn-warning {

    background: #f59e0b;

    color: white;
}

.btn-danger {

    background: #dc2626;

    color: white;
}

.btn-secondary {

    background: #e5e7eb;

    color: #111827;
}

.save-area {

    margin-top: 22px;
}

/* TOOLBAR */

.toolbar {

    display: flex;

    gap: 10px;

    flex-wrap: wrap;

    margin-bottom: 18px;
}

.toolbar input,
.toolbar select {

    padding: 11px 13px;

    border:
        1px solid var(--border);

    border-radius: 9px;

    background: white;
}

.toolbar input {

    min-width: 250px;
}

/* TABLE */

.table-wrapper {

    overflow-x: auto;
}

table {

    width: 100%;

    border-collapse: collapse;

    min-width: 1250px;
}

th,
td {

    padding: 13px 12px;

    text-align: left;

    border-bottom:
        1px solid var(--border);

    vertical-align: middle;
}

th {

    color: var(--muted);

    font-size: 13px;

    background: #f9fafb;
}

td {

    font-size: 14px;
}

.actions {

    display: flex;

    gap: 6px;

    flex-wrap: wrap;
}

.action-btn {

    border: 0;

    border-radius: 7px;

    padding: 7px 9px;

    cursor: pointer;

    font-size: 12px;

    font-weight: 700;
}

.action-view {

    background: #eff6ff;

    color: #1d4ed8;
}

.action-edit {

    background: #f3f4f6;

    color: #374151;
}

.action-start {

    background: #dcfce7;

    color: #166534;
}

.action-status {

    background: #fef3c7;

    color: #92400e;
}

.action-delete {

    background: #fee2e2;

    color: #991b1b;
}

.price {

    font-weight: 800;

    color: #166534;
}

.status {

    display: inline-flex;

    padding: 5px 9px;

    border-radius: 999px;

    font-size: 12px;

    font-weight: 700;
}

.status.submitted {

    background: #dbeafe;

    color: #1d4ed8;
}

.status.processing {

    background: #fef3c7;

    color: #92400e;
}

.status.completed {

    background: #dcfce7;

    color: #166534;
}

.status.needs {

    background: #ffedd5;

    color: #c2410c;
}

.status.cancelled {

    background: #fee2e2;

    color: #991b1b;
}

/* MODAL */

.modal {

    position: fixed;

    inset: 0;

    background:
        rgba(
            15,
            23,
            42,
            .55
        );

    display: none;

    align-items: center;

    justify-content: center;

    padding: 20px;

    z-index: 100;
}

.modal.show {

    display: flex;
}

.modal-box {

    background: white;

    width:
        min(
            950px,
            100%
        );

    max-height: 90vh;

    overflow-y: auto;

    border-radius: 18px;

    padding: 25px;
}

.modal-header {

    display: flex;

    justify-content: space-between;

    align-items: center;

    gap: 15px;

    margin-bottom: 20px;
}

.modal-header h2 {

    margin: 0;
}

.close-btn {

    border: 0;

    background: #f3f4f6;

    width: 36px;

    height: 36px;

    border-radius: 50%;

    cursor: pointer;

    font-size: 20px;
}

.details-grid {

    display: grid;

    grid-template-columns:
        repeat(2, minmax(0, 1fr));

    gap: 12px;
}

.detail {

    padding: 13px;

    background: #f8fafc;

    border-radius: 10px;
}

.detail strong {

    display: block;

    font-size: 12px;

    color: var(--muted);

    margin-bottom: 4px;
}

.empty {

    text-align: center;

    padding: 35px;

    color: var(--muted);
}

/* RESPONSIVE */

@media (max-width: 1350px) {

    .stats {

        grid-template-columns:
            repeat(3, minmax(0, 1fr));
    }
}

@media (max-width: 900px) {

    .sidebar {

        width: 210px;
    }

    .main {

        margin-left: 210px;

        padding: 20px;
    }

    .settings-grid {

        grid-template-columns: 1fr;
    }

    .field.full {

        grid-column: auto;
    }
}

@media (max-width: 700px) {

    .sidebar {

        position: static;

        width: 100%;

        min-height: auto;
    }

    .layout {

        display: block;
    }

    .main {

        margin-left: 0;

        padding: 15px;
    }

    .stats {

        grid-template-columns:
            repeat(2, minmax(0, 1fr));
    }

    .topbar {

        align-items: flex-start;

        flex-direction: column;
    }
}

@media (max-width: 450px) {

    .stats {

        grid-template-columns: 1fr;
    }

    .section {

        padding: 17px;
    }

    .status-options {

        flex-direction: column;
    }
}

</style>

</head>

<body>

<div class="layout">

<!-- SIDEBAR -->

<aside class="sidebar">

    <div class="brand">
        Smart<span>Apply</span>
    </div>

    <nav class="nav">

        <a
            href="#dashboard"
            class="active"
        >
            📊 Dashboard
        </a>

        <a href="#applications">
            📄 Applications
        </a>

        <a href="#completed">
            ✅ Completed
        </a>

        <a href="#settings">
            ⚙ Settings
        </a>

        <a
            href="../index.php"
            target="_blank"
        >
            🌐 Open Application Form
        </a>

        <a
            href="../public/logout.php"
            class="logout"
        >
            🚪 Logout
        </a>

    </nav>

</aside>


<!-- MAIN -->

<main class="main">

    <!-- TOPBAR -->

    <div class="topbar">

        <div>

            <h1>
                Admin Dashboard
            </h1>

            <p>
                Manage SmartApply applications.
            </p>

        </div>

        <div class="admin-badge">
            👤 <?= e($adminName) ?>
        </div>

    </div>


    <!-- STATISTICS -->

    <section id="dashboard">

        <div class="stats">

            <div class="card stat">

                <div class="stat-title">
                    Total Applications
                </div>

                <div class="stat-number">
                    <?= $totalApplications ?>
                </div>

            </div>

            <div class="card stat">

                <div class="stat-title">
                    Submitted
                </div>

                <div class="stat-number">
                    <?= $submittedApplications ?>
                </div>

            </div>

            <div class="card stat">

                <div class="stat-title">
                    Processing
                </div>

                <div class="stat-number">
                    <?= $processingApplications ?>
                </div>

            </div>

            <div class="card stat">

                <div class="stat-title">
                    Needs Correction
                </div>

                <div class="stat-number">
                    <?= $needsCorrectionApplications ?>
                </div>

            </div>

            <div class="card stat">

                <div class="stat-title">
                    Completed
                </div>

                <div class="stat-number">
                    <?= $completedApplications ?>
                </div>

            </div>

            <div class="card stat">

                <div class="stat-title">
                    Cancelled
                </div>

                <div class="stat-number">
                    <?= $cancelledApplications ?>
                </div>

            </div>

        </div>

    </section>


    <!-- APPLICATIONS -->

    <section
        id="applications"
        class="card section"
    >

        <div class="section-header">

            <h2>
                Applications
            </h2>

            <p>
                Applications that still require attention.
                Completed applications are moved to the Completed section.
            </p>

        </div>


        <form
            method="GET"
            class="toolbar"
        >

            <input
                type="text"
                name="search"
                value="<?= e($search) ?>"
                placeholder="Search name, phone, index..."
            >

            <select name="status">

                <option value="">
                    All Active Statuses
                </option>

                <?php foreach ($allowedStatuses as $status): ?>

                    <option
                        value="<?= e($status) ?>"
                        <?= $statusFilter === $status
                            ? 'selected'
                            : '' ?>
                    >
                        <?= e(
                            ucwords(
                                strtolower(
                                    str_replace(
                                        '_',
                                        ' ',
                                        $status
                                    )
                                )
                            )
                        ) ?>
                    </option>

                <?php endforeach; ?>

            </select>

            <button
                type="submit"
                class="btn btn-primary"
            >
                Search
            </button>

        </form>


        <div class="table-wrapper">

            <table>

                <thead>

                    <tr>

                        <th>
                            Application
                        </th>

                        <th>
                            Applicant
                        </th>

                        <th>
                            University
                        </th>

                        <th>
                            Department
                        </th>

                        <th>
                            Option
                        </th>

                        <th>
                            Price
                        </th>

                        <th>
                            Status
                        </th>

                        <th>
                            Date
                        </th>

                        <th>
                            Actions
                        </th>

                    </tr>

                </thead>

                <tbody>

                <?php if (!$applications): ?>

                    <tr>

                        <td
                            colspan="9"
                            class="empty"
                        >
                            No active applications found.
                        </td>

                    </tr>

                <?php else: ?>

                    <?php foreach ($applications as $application): ?>

                        <?php

                        $statusClass = match (
                            $application['status']
                        ) {

                            'SUBMITTED'
                                => 'submitted',

                            'PROCESSING'
                                => 'processing',

                            'NEEDS_CORRECTION'
                                => 'needs',

                            'CANCELLED'
                                => 'cancelled',

                            default
                                => ''
                        };

                        ?>

                        <tr>

                            <td>

                                <strong>
                                    <?= e(
                                        $application[
                                            'application_number'
                                        ]
                                    ) ?>
                                </strong>

                            </td>


                            <td>

                                <strong>
                                    <?= e(
                                        $application['full_name']
                                    ) ?>
                                </strong>

                                <br>

                                <small>
                                    <?= e(
                                        $application['phone']
                                    ) ?>
                                </small>

                            </td>


                            <td>

                                <?= e(
                                    $application[
                                        'university_name'
                                    ] ?? '-'
                                ) ?>

                            </td>


                            <td>

                                <?= e(
                                    $application[
                                        'department_name'
                                    ] ?? '-'
                                ) ?>

                            </td>


                            <td>

                                <?= e(
                                    $application[
                                        'option_name'
                                    ] ?? '-'
                                ) ?>

                            </td>


                            <td class="price">

                                <?= number_format(
                                    (float)(
                                        $application[
                                            'application_price'
                                        ] ?? 0
                                    ),
                                    2
                                ) ?>

                                RWF

                            </td>


                            <td>

                                <span
                                    class="status
                                    <?= e($statusClass) ?>"
                                >

                                    <?= e(
                                        str_replace(
                                            '_',
                                            ' ',
                                            $application['status']
                                        )
                                    ) ?>

                                </span>

                            </td>


                            <td>

                                <?= e(
                                    date(
                                        'd M Y',
                                        strtotime(
                                            $application[
                                                'created_at'
                                            ]
                                        )
                                    )
                                ) ?>

                            </td>


                            <td>

                                <div class="actions">

                                    <!-- VIEW -->

                                    <button
                                        type="button"
                                        class="
                                            action-btn
                                            action-view
                                        "
                                        onclick="showApplication(
                                            <?= htmlspecialchars(
                                                json_encode(
                                                    $application,
                                                    JSON_HEX_TAG |
                                                    JSON_HEX_APOS |
                                                    JSON_HEX_QUOT |
                                                    JSON_HEX_AMP
                                                ),
                                                ENT_QUOTES,
                                                'UTF-8'
                                            ) ?>
                                        )"
                                    >
                                        View
                                    </button>


                                    <!-- EDIT -->

                                    <a
                                        class="
                                            action-btn
                                            action-edit
                                        "
                                        href="edit_application.php?id=<?= (int)$application['id'] ?>"
                                    >
                                        Edit
                                    </a>


                                    <!-- START -->

                                    <?php if (
                                        !empty(
                                            $application[
                                                'university_application_url'
                                            ]
                                        )
                                    ): ?>

                                        <a
                                            class="
                                                action-btn
                                                action-start
                                            "
                                            href="start_application.php?id=<?= (int)$application['id'] ?>"
                                        >
                                            ▶ Start
                                        </a>

                                    <?php else: ?>

                                        <button
                                            type="button"
                                            class="
                                                action-btn
                                                action-start
                                            "
                                            onclick="alert(
                                                'This university does not have an application URL configured yet.'
                                            )"
                                        >
                                            ▶ Start
                                        </button>

                                    <?php endif; ?>


                                    <!-- STATUS -->

                                    <button
                                        type="button"
                                        class="
                                            action-btn
                                            action-status
                                        "
                                        onclick="openStatusModal(
                                            <?= (int)$application['id'] ?>,
                                            '<?= e(
                                                $application['status']
                                            ) ?>',
                                            '<?= e(
                                                $application['application_number']
                                            ) ?>'
                                        )"
                                    >
                                        Status
                                    </button>


                                    <!-- DELETE -->

                                    <button
                                        type="button"
                                        class="
                                            action-btn
                                            action-delete
                                        "
                                        onclick="deleteApplication(
                                            <?= (int)$application['id'] ?>
                                        )"
                                    >
                                        Delete
                                    </button>

                                </div>

                            </td>

                        </tr>

                    <?php endforeach; ?>

                <?php endif; ?>

                </tbody>

            </table>

        </div>

    </section>


    <!-- COMPLETED -->

    <section
        id="completed"
        class="card section"
    >

        <div class="section-header">

            <h2>
                ✅ Completed Applications
            </h2>

            <p>
                These applications are already completed and
                no longer appear in the active Applications list.
            </p>

        </div>


        <div class="table-wrapper">

            <table>

                <thead>

                    <tr>

                        <th>
                            Application
                        </th>

                        <th>
                            Applicant
                        </th>

                        <th>
                            University
                        </th>

                        <th>
                            Department
                        </th>

                        <th>
                            Option
                        </th>

                        <th>
                            Price
                        </th>

                        <th>
                            Completed At
                        </th>

                    </tr>

                </thead>

                <tbody>

                <?php if (!$completedList): ?>

                    <tr>

                        <td
                            colspan="7"
                            class="empty"
                        >
                            No completed applications yet.
                        </td>

                    </tr>

                <?php else: ?>

                    <?php foreach ($completedList as $completed): ?>

                        <tr>

                            <td>

                                <strong>
                                    <?= e(
                                        $completed[
                                            'application_number'
                                        ]
                                    ) ?>
                                </strong>

                            </td>

                            <td>

                                <?= e(
                                    $completed['full_name']
                                ) ?>

                                <br>

                                <small>
                                    <?= e(
                                        $completed['phone']
                                    ) ?>
                                </small>

                            </td>

                            <td>

                                <?= e(
                                    $completed[
                                        'university_name'
                                    ] ?? '-'
                                ) ?>

                            </td>

                            <td>

                                <?= e(
                                    $completed[
                                        'department_name'
                                    ] ?? '-'
                                ) ?>

                            </td>

                            <td>

                                <?= e(
                                    $completed[
                                        'option_name'
                                    ] ?? '-'
                                ) ?>

                            </td>

                            <td class="price">

                                <?= number_format(
                                    (float)(
                                        $completed[
                                            'application_price'
                                        ] ?? 0
                                    ),
                                    2
                                ) ?>

                                RWF

                            </td>

                            <td>

                                <?= e(
                                    date(
                                        'd M Y H:i',
                                        strtotime(
                                            $completed[
                                                'updated_at'
                                            ]
                                        )
                                    )
                                ) ?>

                            </td>

                        </tr>

                    <?php endforeach; ?>

                <?php endif; ?>

                </tbody>

            </table>

        </div>

    </section>


    <!-- SETTINGS -->

    <section
        id="settings"
        class="card section"
    >

        <div class="section-header">

            <h2>
                Application & Contact Settings
            </h2>

            <p>
                Manage public application status, service price
                and contact information.
            </p>

        </div>


        <?php if ($successMessage): ?>

            <div class="alert success">
                <?= e($successMessage) ?>
            </div>

        <?php endif; ?>


        <?php if ($errorMessage): ?>

            <div class="alert error">
                <?= e($errorMessage) ?>
            </div>

        <?php endif; ?>


        <form method="POST">

            <div class="settings-grid">

                <!-- APPLICATION STATUS -->

                <div class="field full">

                    <label>
                        Application Status
                    </label>

                    <div class="status-options">

                        <div class="status-option">

                            <input
                                type="radio"
                                name="application_status"
                                id="status_open"
                                value="OPEN"
                                <?= $applicationStatus === 'OPEN'
                                    ? 'checked'
                                    : '' ?>
                            >

                            <label for="status_open">
                                🟢 OPEN
                            </label>

                        </div>


                        <div class="status-option">

                            <input
                                type="radio"
                                name="application_status"
                                id="status_closed"
                                value="CLOSED"
                                <?= $applicationStatus === 'CLOSED'
                                    ? 'checked'
                                    : '' ?>
                            >

                            <label for="status_closed">
                                🔴 CLOSED
                            </label>

                        </div>

                    </div>

                </div>


                <!-- PRICE -->

                <div class="field">

                    <label for="application_price">
                        Application Price (RWF)
                    </label>

                    <input
                        type="number"
                        min="0"
                        step="1"
                        id="application_price"
                        name="application_price"
                        value="<?= e($applicationPrice) ?>"
                        placeholder="5000"
                    >

                </div>


                <!-- CURRENT PRICE -->

                <div class="field">

                    <label>
                        Current Application Price
                    </label>

                    <div class="price-box">

                        <strong>
                            SERVICE PRICE
                        </strong>

                        <div class="price-value">

                            <?= number_format(
                                (float)$applicationPrice
                            ) ?>

                            RWF

                        </div>

                    </div>

                </div>


                <!-- CONTACT NAME -->

                <div class="field">

                    <label for="contact_name">
                        Your Name
                    </label>

                    <input
                        type="text"
                        id="contact_name"
                        name="contact_name"
                        value="<?= e($contactName) ?>"
                    >

                </div>


                <!-- PHONE -->

                <div class="field">

                    <label for="phone">
                        Phone Number
                    </label>

                    <input
                        type="text"
                        id="phone"
                        name="phone"
                        value="<?= e($phone) ?>"
                    >

                </div>


                <!-- WHATSAPP -->

                <div class="field">

                    <label for="whatsapp">
                        WhatsApp Number
                    </label>

                    <input
                        type="text"
                        id="whatsapp"
                        name="whatsapp"
                        value="<?= e($whatsapp) ?>"
                    >

                </div>


                <!-- EMAIL -->

                <div class="field">

                    <label for="email">
                        Email
                    </label>

                    <input
                        type="email"
                        id="email"
                        name="email"
                        value="<?= e($email) ?>"
                    >

                </div>


                <!-- INSTAGRAM -->

                <div class="field">

                    <label for="instagram">
                        Instagram Username
                    </label>

                    <input
                        type="text"
                        id="instagram"
                        name="instagram"
                        value="<?= e($instagram) ?>"
                    >

                </div>


                <!-- PAYMENT CODE -->

                <div class="field">

                    <label for="payment_code">
                        Payment Code
                    </label>

                    <input
                        type="text"
                        id="payment_code"
                        name="payment_code"
                        value="<?= e($paymentCode) ?>"
                    >

                </div>


                <!-- WHATSAPP GROUP -->

                <div class="field full">

                    <label for="whatsapp_group">
                        WhatsApp Group Link
                    </label>

                    <input
                        type="url"
                        id="whatsapp_group"
                        name="whatsapp_group"
                        value="<?= e($whatsappGroup) ?>"
                    >

                </div>

            </div>


            <div class="save-area">

                <button
                    type="submit"
                    name="save_settings"
                    class="btn btn-primary"
                >
                    Save Settings
                </button>

            </div>

        </form>

    </section>

</main>

</div>


<!-- VIEW MODAL -->

<div
    class="modal"
    id="applicationModal"
>

    <div class="modal-box">

        <div class="modal-header">

            <h2>
                Application Details
            </h2>

            <button
                type="button"
                class="close-btn"
                onclick="closeApplication()"
            >
                ×
            </button>

        </div>

        <div
            id="applicationDetails"
            class="details-grid"
        ></div>

    </div>

</div>


<!-- STATUS MODAL -->

<div
    class="modal"
    id="statusModal"
>

    <div class="modal-box">

        <div class="modal-header">

            <div>

                <h2>
                    Change Application Status
                </h2>

                <p id="statusApplicationNumber"></p>

            </div>

            <button
                type="button"
                class="close-btn"
                onclick="closeStatusModal()"
            >
                ×
            </button>

        </div>


        <form
            method="POST"
            action="update_status.php"
        >

            <input
                type="hidden"
                name="application_id"
                id="statusApplicationId"
            >


            <div class="field">

                <label for="new_status">
                    New Status
                </label>

                <select
                    name="status"
                    id="new_status"
                    required
                >

                    <option value="SUBMITTED">
                        SUBMITTED
                    </option>

                    <option value="PROCESSING">
                        PROCESSING
                    </option>

                    <option value="COMPLETED">
                        COMPLETED
                    </option>

                    <option value="NEEDS_CORRECTION">
                        NEEDS CORRECTION
                    </option>

                    <option value="CANCELLED">
                        CANCELLED
                    </option>

                </select>

            </div>


            <br>


            <div class="field">

                <label for="admin_note">
                    Admin Note
                </label>

                <textarea
                    name="admin_note"
                    id="admin_note"
                    placeholder="Optional note..."
                ></textarea>

            </div>


            <br>


            <button
                type="submit"
                class="btn btn-primary"
            >
                Save Status
            </button>

            <button
                type="button"
                class="btn btn-secondary"
                onclick="closeStatusModal()"
            >
                Cancel
            </button>

        </form>

    </div>

</div>


<script>

/*
|--------------------------------------------------------------------------
| ESCAPE HTML
|--------------------------------------------------------------------------
*/

function escapeHtml(value) {

    if (
        value === null ||
        value === undefined ||
        value === ''
    ) {
        return '-';
    }

    const div =
        document.createElement('div');

    div.textContent =
        String(value);

    return div.innerHTML;
}


/*
|--------------------------------------------------------------------------
| VIEW APPLICATION
|--------------------------------------------------------------------------
*/

function showApplication(application) {

    const details =
        document.getElementById(
            'applicationDetails'
        );

    const fields = [

        [
            'Application Number',
            application.application_number
        ],

        [
            'Full Name',
            application.full_name
        ],

        [
            'Email',
            application.email
        ],

        [
            'Phone',
            application.phone
        ],

        [
            'Index Number',
            application.index_number
        ],

        [
            'NID / Passport',
            application.nid_passport
        ],

        [
            'University',
            application.university_name
        ],

        [
            'Department',
            application.department_name
        ],

        [
            'Programme / Option',
            application.option_name
        ],

        [
            'Application Price',
            application.application_price
                ? Number(
                    application.application_price
                ).toLocaleString() + ' RWF'
                : '0 RWF'
        ],

        [
            'Father Name',
            application.father_name
        ],

        [
            'Father Phone',
            application.father_phone
        ],

        [
            'Mother Name',
            application.mother_name
        ],

        [
            'Mother Phone',
            application.mother_phone
        ],

        [
            'Province',
            application.province
        ],

        [
            'District',
            application.district
        ],

        [
            'Sector',
            application.sector
        ],

        [
            'Cell',
            application.cell
        ],

        [
            'Village',
            application.village
        ],

        [
            'Address',
            application.address
        ],

        [
            'Secondary School',
            application.education_school
        ],

        [
            'Combination',
            application.education_combination
        ],

        [
            'Education Year',
            application.education_year
        ],

        [
            'Applicant Type',
            application.applicant_type
        ],

        [
            'Status',
            application.status
        ],

        [
            'Admin Note',
            application.admin_note
        ],

        [
            'Created At',
            application.created_at
        ],

        [
            'Updated At',
            application.updated_at
        ]

    ];


    details.innerHTML =
        fields.map(
            ([label, value]) => `

                <div class="detail">

                    <strong>
                        ${escapeHtml(label)}
                    </strong>

                    <span>
                        ${escapeHtml(value)}
                    </span>

                </div>

            `
        ).join('');


    document
        .getElementById(
            'applicationModal'
        )
        .classList
        .add('show');
}


/*
|--------------------------------------------------------------------------
| CLOSE APPLICATION MODAL
|--------------------------------------------------------------------------
*/

function closeApplication() {

    document
        .getElementById(
            'applicationModal'
        )
        .classList
        .remove('show');
}


/*
|--------------------------------------------------------------------------
| STATUS MODAL
|--------------------------------------------------------------------------
*/

function openStatusModal(
    id,
    currentStatus,
    applicationNumber
) {

    document.getElementById(
        'statusApplicationId'
    ).value = id;

    document.getElementById(
        'statusApplicationNumber'
    ).textContent =
        'Application: ' +
        applicationNumber;

    document.getElementById(
        'new_status'
    ).value = currentStatus;

    document
        .getElementById(
            'statusModal'
        )
        .classList
        .add('show');
}


/*
|--------------------------------------------------------------------------
| CLOSE STATUS MODAL
|--------------------------------------------------------------------------
*/

function closeStatusModal() {

    document
        .getElementById(
            'statusModal'
        )
        .classList
        .remove('show');
}


/*
|--------------------------------------------------------------------------
| DELETE
|--------------------------------------------------------------------------
*/

function deleteApplication(id) {

    const confirmed =
        confirm(
            'Are you sure you want to permanently delete this application?'
        );

    if (!confirmed) {
        return;
    }

    window.location.href =
        'delete_application.php?id=' +
        encodeURIComponent(id);
}


/*
|--------------------------------------------------------------------------
| CLOSE MODALS BY BACKDROP
|--------------------------------------------------------------------------
*/

document
    .getElementById(
        'applicationModal'
    )
    .addEventListener(
        'click',
        function(event) {

            if (event.target === this) {

                closeApplication();
            }

        }
    );


document
    .getElementById(
        'statusModal'
    )
    .addEventListener(
        'click',
        function(event) {

            if (event.target === this) {

                closeStatusModal();
            }

        }
    );

</script>

</body>

</html>