<?php

declare(strict_types=1);

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

$pdo = Database::connection();

$errors = [];

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

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

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

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

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

        $value = $stmt->fetchColumn();

        if ($value === false || $value === null) {
            return $default;
        }

        return trim((string) $value);

    } catch (Throwable $e) {

        return $default;
    }
}


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

$applicationStatus = strtoupper(
    getSetting(
        $pdo,
        'application_status',
        'OPEN'
    )
);

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

$applicationsOpen = ($applicationStatus === 'OPEN');


/*
|--------------------------------------------------------------------------
| CONTACT / PAYMENT SETTINGS
|--------------------------------------------------------------------------
*/

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

$contactPhone = getSetting(
    $pdo,
    'phone'
);

$contactWhatsApp = getSetting(
    $pdo,
    'whatsapp'
);

$contactEmail = getSetting(
    $pdo,
    'email'
);

$contactInstagram = getSetting(
    $pdo,
    'instagram'
);

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

$whatsappGroupLink = getSetting(
    $pdo,
    'whatsapp_group'
);


/*
|--------------------------------------------------------------------------
| APPLICATION PRICE
|--------------------------------------------------------------------------
|
| Price comes directly from app_settings.
|
*/

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

$currency = getSetting(
    $pdo,
    'currency',
    'RWF'
);


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

$applicationPriceNumber = (float) $applicationPrice;

$formattedApplicationPrice =
    number_format(
        $applicationPriceNumber,
        0,
        '.',
        ','
    );


/*
|--------------------------------------------------------------------------
| WHATSAPP URL
|--------------------------------------------------------------------------
*/

$whatsappDigits = preg_replace(
    '/\D+/',
    '',
    $contactWhatsApp
);

$whatsappUrl = '';

if ($whatsappDigits !== '') {

    /*
     * Rwanda numbers normally begin with 07...
     * Convert 07XXXXXXXX to 2507XXXXXXXX.
     */

    if (str_starts_with($whatsappDigits, '07')) {

        $whatsappDigits =
            '250' .
            substr($whatsappDigits, 1);

    } elseif (str_starts_with($whatsappDigits, '250')) {

        // Already international.
    }

    $whatsappUrl =
        'https://wa.me/' .
        $whatsappDigits;
}


/*
|--------------------------------------------------------------------------
| INSTAGRAM URL
|--------------------------------------------------------------------------
*/

$instagramUrl = '';

if ($contactInstagram !== '') {

    $instagramValue =
        trim($contactInstagram);

    /*
     * If admin stores the complete Instagram URL,
     * use it directly.
     */

    if (
        str_starts_with(
            $instagramValue,
            'http://'
        ) ||
        str_starts_with(
            $instagramValue,
            'https://'
        )
    ) {

        $instagramUrl =
            $instagramValue;

    } else {

        $instagramUrl =
            'https://instagram.com/' .
            ltrim(
                $instagramValue,
                '@'
            );
    }
}


/*
|--------------------------------------------------------------------------
| LOAD RWANDA LOCATIONS
|--------------------------------------------------------------------------
*/

$locations = [];

$locationsFile =
    __DIR__ .
    '/data/rwanda_locations.json';

if (is_file($locationsFile)) {

    $json = file_get_contents(
        $locationsFile
    );

    if ($json !== false) {

        $decoded = json_decode(
            $json,
            true
        );

        if (
            json_last_error() === JSON_ERROR_NONE &&
            is_array($decoded)
        ) {

            $locations = $decoded;
        }
    }
}


/*
|--------------------------------------------------------------------------
| LOAD UNIVERSITIES
|--------------------------------------------------------------------------
*/

$universities = [];

try {

    $universities = $pdo->query("
        SELECT
            id,
            name,
            code
        FROM universities
        WHERE status = 'ACTIVE'
        ORDER BY name ASC
    ")->fetchAll(PDO::FETCH_ASSOC);

} catch (Throwable $e) {

    $errors[] =
        'Unable to load universities. Please contact the administrator.';
}


/*
|--------------------------------------------------------------------------
| LOAD DEPARTMENTS
|--------------------------------------------------------------------------
*/

$departments = [];

try {

    $departments = $pdo->query("
        SELECT
            id,
            university_id,
            name
        FROM departments
        WHERE status = 'ACTIVE'
        ORDER BY name ASC
    ")->fetchAll(PDO::FETCH_ASSOC);

} catch (Throwable $e) {

    $errors[] =
        'Unable to load departments. Please contact the administrator.';
}


/*
|--------------------------------------------------------------------------
| LOAD PROGRAMS
|--------------------------------------------------------------------------
*/

$programs = [];

try {

    $programs = $pdo->query("
        SELECT
            id,
            university_id,
            department,
            option_name
        FROM programs
        WHERE status = 'ACTIVE'
        ORDER BY department ASC, option_name ASC
    ")->fetchAll(PDO::FETCH_ASSOC);

} catch (Throwable $e) {

    $errors[] =
        'Unable to load study options. Please contact the administrator.';
}


/*
|--------------------------------------------------------------------------
| PREPARE UNIVERSITY DATA
|--------------------------------------------------------------------------
*/

$departmentData = [];

foreach ($departments as $department) {

    $universityId =
        (int) $department['university_id'];

    if (!isset($departmentData[$universityId])) {

        $departmentData[$universityId] = [];
    }

    $departmentData[$universityId][] = [

        'id' =>
            (int) $department['id'],

        'name' =>
            (string) $department['name']
    ];
}


/*
|--------------------------------------------------------------------------
| PREPARE PROGRAM DATA
|--------------------------------------------------------------------------
*/

$programData = [];

foreach ($programs as $program) {

    $universityId =
        (int) $program['university_id'];

    $departmentName =
        (string) $program['department'];

    if (!isset($programData[$universityId])) {

        $programData[$universityId] = [];
    }

    if (!isset(
        $programData[$universityId][$departmentName]
    )) {

        $programData[$universityId][$departmentName] = [];
    }

    $programData[$universityId][$departmentName][] = [

        'id' =>
            (int) $program['id'],

        'option' =>
            (string) $program['option_name']
    ];
}


/*
|--------------------------------------------------------------------------
| FORM VALUES
|--------------------------------------------------------------------------
*/

$post = $_POST;


/*
|--------------------------------------------------------------------------
| HANDLE SUBMISSION
|--------------------------------------------------------------------------
*/

if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    $applicationsOpen
) {

    /*
    |--------------------------------------------------------------------------
    | BASIC INFORMATION
    |--------------------------------------------------------------------------
    */

    $email =
        trim($post['email'] ?? '');

    $indexNumber =
        trim($post['index_number'] ?? '');

    $nidPassport =
        trim($post['nid_passport'] ?? '');

    $fullName =
        trim($post['full_name'] ?? '');

    $phone =
        trim($post['phone'] ?? '');


    /*
    |--------------------------------------------------------------------------
    | PARENTS
    |--------------------------------------------------------------------------
    */

    $fatherName =
        trim($post['father_name'] ?? '');

    $fatherPhone =
        trim($post['father_phone'] ?? '');

    $motherName =
        trim($post['mother_name'] ?? '');

    $motherPhone =
        trim($post['mother_phone'] ?? '');


    /*
    |--------------------------------------------------------------------------
    | RWANDA ADDRESS
    |--------------------------------------------------------------------------
    */

    $province =
        trim($post['province'] ?? '');

    $district =
        trim($post['district'] ?? '');

    $sector =
        trim($post['sector'] ?? '');

    $cell =
        trim($post['cell'] ?? '');

    $village =
        trim($post['village'] ?? '');

    $address =
        trim($post['address'] ?? '');


    /*
    |--------------------------------------------------------------------------
    | EDUCATION
    |--------------------------------------------------------------------------
    */

    $educationSchool =
        trim($post['education_school'] ?? '');

    $educationCombination =
        trim($post['education_combination'] ?? '');

    $educationYear =
        trim($post['education_year'] ?? '');


    /*
    |--------------------------------------------------------------------------
    | APPLICANT TYPE
    |--------------------------------------------------------------------------
    */

    $applicantType =
        trim($post['applicant_type'] ?? '');


    /*
    |--------------------------------------------------------------------------
    | UNIVERSITY / DEPARTMENT / PROGRAM
    |--------------------------------------------------------------------------
    */

    $universityId =
        (int) ($post['university_id'] ?? 0);

    $departmentId =
        (int) ($post['department_id'] ?? 0);

    $programId =
        (int) ($post['program_id'] ?? 0);


    /*
    |--------------------------------------------------------------------------
    | VALIDATION
    |--------------------------------------------------------------------------
    */

    if ($indexNumber === '') {

        $errors[] =
            'Index Number is required.';
    }


    if ($nidPassport === '') {

        $errors[] =
            'NID / Passport ID is required.';
    }


    if ($fullName === '') {

        $errors[] =
            'Full Name is required.';
    }


    if ($phone === '') {

        $errors[] =
            'Phone Number is required.';
    }


    if (
        $email !== '' &&
        !filter_var(
            $email,
            FILTER_VALIDATE_EMAIL
        )
    ) {

        $errors[] =
            'Please enter a valid email address.';
    }


    if ($province === '') {

        $errors[] =
            'Please select Province.';
    }


    if ($district === '') {

        $errors[] =
            'Please select District.';
    }


    if ($sector === '') {

        $errors[] =
            'Please select Sector.';
    }


    if ($cell === '') {

        $errors[] =
            'Please select Cell.';
    }


    if ($village === '') {

        $errors[] =
            'Please select Village.';
    }


    if ($universityId <= 0) {

        $errors[] =
            'Please select a university.';
    }


    if ($departmentId <= 0) {

        $errors[] =
            'Please select a department.';
    }


    if ($programId <= 0) {

        $errors[] =
            'Please select an option.';
    }


    if (
        !in_array(
            $applicantType,
            ['Government', 'Private'],
            true
        )
    ) {

        $errors[] =
            'Please select Government or Private.';
    }


    /*
    |--------------------------------------------------------------------------
    | VERIFY RWANDA LOCATION
    |--------------------------------------------------------------------------
    */

    if (
        $province !== '' &&
        $district !== '' &&
        $sector !== '' &&
        $cell !== '' &&
        $village !== ''
    ) {

        if (
            !isset($locations[$province]) ||
            !isset(
                $locations[$province][$district]
            ) ||
            !isset(
                $locations[$province][$district][$sector]
            ) ||
            !isset(
                $locations[$province][$district][$sector][$cell]
            ) ||
            !is_array(
                $locations[$province][$district][$sector][$cell]
            ) ||
            !in_array(
                $village,
                $locations[
                    $province
                ][
                    $district
                ][
                    $sector
                ][
                    $cell
                ],
                true
            )
        ) {

            $errors[] =
                'Invalid Rwanda location selected.';
        }
    }


    /*
    |--------------------------------------------------------------------------
    | VERIFY UNIVERSITY
    |--------------------------------------------------------------------------
    */

    $selectedUniversity = null;

    if ($universityId > 0) {

        $stmt = $pdo->prepare("
            SELECT
                id,
                name,
                code
            FROM universities
            WHERE id = ?
              AND status = 'ACTIVE'
            LIMIT 1
        ");

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

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

        if (!$selectedUniversity) {

            $errors[] =
                'Invalid university selected.';
        }
    }


    /*
    |--------------------------------------------------------------------------
    | VERIFY DEPARTMENT
    |--------------------------------------------------------------------------
    */

    $selectedDepartment = null;

    if (
        $universityId > 0 &&
        $departmentId > 0
    ) {

        $stmt = $pdo->prepare("
            SELECT
                id,
                university_id,
                name
            FROM departments
            WHERE id = ?
              AND university_id = ?
              AND status = 'ACTIVE'
            LIMIT 1
        ");

        $stmt->execute([
            $departmentId,
            $universityId
        ]);

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

        if (!$selectedDepartment) {

            $errors[] =
                'Invalid department selected.';
        }
    }


    /*
    |--------------------------------------------------------------------------
    | VERIFY PROGRAM
    |--------------------------------------------------------------------------
    */

    $selectedProgram = null;

    if (
        $universityId > 0 &&
        $programId > 0
    ) {

        $stmt = $pdo->prepare("
            SELECT
                id,
                university_id,
                department,
                option_name
            FROM programs
            WHERE id = ?
              AND university_id = ?
              AND status = 'ACTIVE'
            LIMIT 1
        ");

        $stmt->execute([
            $programId,
            $universityId
        ]);

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

        if (!$selectedProgram) {

            $errors[] =
                'Invalid study option selected.';
        }
    }


    /*
    |--------------------------------------------------------------------------
    | VERIFY PROGRAM DEPARTMENT
    |--------------------------------------------------------------------------
    */

    if (
        $selectedDepartment &&
        $selectedProgram
    ) {

        if (
            trim(
                $selectedDepartment['name']
            ) !== trim(
                $selectedProgram['department']
            )
        ) {

            $errors[] =
                'The selected option does not belong to the selected department.';
        }
    }


    /*
    |--------------------------------------------------------------------------
    | SAVE APPLICATION
    |--------------------------------------------------------------------------
    */

    if (!$errors) {

        try {

            $pdo->beginTransaction();


            /*
            |--------------------------------------------------------------------------
            | APPLICATION NUMBER
            |--------------------------------------------------------------------------
            */

            do {

                $applicationNumber =
                    'SA-' .
                    date('Ymd') .
                    '-' .
                    strtoupper(
                        bin2hex(
                            random_bytes(3)
                        )
                    );

                $check = $pdo->prepare("
                    SELECT id
                    FROM applications
                    WHERE application_number = ?
                    LIMIT 1
                ");

                $check->execute([
                    $applicationNumber
                ]);

                $exists =
                    $check->fetchColumn() !== false;

            } while ($exists);


            /*
            |--------------------------------------------------------------------------
            | FILE UPLOAD DIRECTORY
            |--------------------------------------------------------------------------
            */

            $uploadDirectory =
                __DIR__ .
                '/uploads/applications/' .
                date('Y/m');

            if (!is_dir($uploadDirectory)) {

                if (
                    !mkdir(
                        $uploadDirectory,
                        0755,
                        true
                    ) &&
                    !is_dir($uploadDirectory)
                ) {

                    throw new RuntimeException(
                        'Unable to create upload directory.'
                    );
                }
            }


            /*
            |--------------------------------------------------------------------------
            | FILE UPLOAD HELPER
            |--------------------------------------------------------------------------
            */

            $uploadFile = function (
                string $field,
                array $allowedMimeTypes
            ) use (
                $uploadDirectory,
                $applicationNumber
            ): ?string {

                if (
                    !isset($_FILES[$field]) ||
                    !is_array($_FILES[$field])
                ) {

                    return null;
                }

                if (
                    ($_FILES[$field]['error'] ?? UPLOAD_ERR_NO_FILE)
                    === UPLOAD_ERR_NO_FILE
                ) {

                    return null;
                }

                if (
                    ($_FILES[$field]['error'] ?? UPLOAD_ERR_OK)
                    !== UPLOAD_ERR_OK
                ) {

                    throw new RuntimeException(
                        'Unable to upload ' . $field . '.'
                    );
                }

                $tmpName =
                    $_FILES[$field]['tmp_name'];

                if (!is_uploaded_file($tmpName)) {

                    throw new RuntimeException(
                        'Invalid uploaded file for ' . $field . '.'
                    );
                }

                $fileSize =
                    (int) $_FILES[$field]['size'];

                if ($fileSize > 5 * 1024 * 1024) {

                    throw new RuntimeException(
                        ucfirst(
                            str_replace(
                                '_',
                                ' ',
                                $field
                            )
                        ) .
                        ' must not exceed 5 MB.'
                    );
                }

                $finfo =
                    new finfo(FILEINFO_MIME_TYPE);

                $mime =
                    $finfo->file($tmpName);

                if (
                    $mime === false ||
                    !in_array(
                        $mime,
                        $allowedMimeTypes,
                        true
                    )
                ) {

                    throw new RuntimeException(
                        'Invalid file type for ' .
                        str_replace(
                            '_',
                            ' ',
                            $field
                        ) .
                        '.'
                    );
                }

                $extensionMap = [

                    'image/jpeg' =>
                        'jpg',

                    'image/png' =>
                        'png',

                    'image/webp' =>
                        'webp',

                    'application/pdf' =>
                        'pdf'
                ];

                $extension =
                    $extensionMap[$mime] ??
                    'bin';

                $safeField =
                    preg_replace(
                        '/[^a-zA-Z0-9_-]/',
                        '',
                        $field
                    );

                $random =
                    bin2hex(
                        random_bytes(8)
                    );

                $filename =
                    $applicationNumber .
                    '_' .
                    $safeField .
                    '_' .
                    $random .
                    '.' .
                    $extension;

                $destination =
                    $uploadDirectory .
                    DIRECTORY_SEPARATOR .
                    $filename;

                if (
                    !move_uploaded_file(
                        $tmpName,
                        $destination
                    )
                ) {

                    throw new RuntimeException(
                        'Unable to save uploaded ' .
                        str_replace(
                            '_',
                            ' ',
                            $field
                        ) .
                        '.'
                    );
                }

                return
                    'uploads/applications/' .
                    date('Y/m') .
                    '/' .
                    $filename;
            };


            /*
            |--------------------------------------------------------------------------
            | UPLOAD DOCUMENTS
            |--------------------------------------------------------------------------
            */

            $passportPhoto = $uploadFile(
                'passport_photo',
                [
                    'image/jpeg',
                    'image/png',
                    'image/webp'
                ]
            );

            $nidPhoto = $uploadFile(
                'nid_photo',
                [
                    'image/jpeg',
                    'image/png',
                    'image/webp'
                ]
            );

            $resultSlip = $uploadFile(
                'result_slip',
                [
                    'image/jpeg',
                    'image/png',
                    'application/pdf'
                ]
            );


            /*
            |--------------------------------------------------------------------------
            | INSERT APPLICATION
            |--------------------------------------------------------------------------
            */

            $stmt = $pdo->prepare("
                INSERT INTO applications (

                    application_number,

                    university_id,

                    department_id,

                    program_id,

                    email,

                    index_number,

                    nid_passport,

                    full_name,

                    phone,

                    father_name,

                    father_phone,

                    mother_name,

                    mother_phone,

                    province,

                    district,

                    sector,

                    cell,

                    village,

                    address,

                    education_school,

                    education_combination,

                    education_year,

                    applicant_type,

                    passport_photo,

                    nid_photo,

                    result_slip,

                    status

                )
                VALUES (

                    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
                    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
                    ?, ?, ?, ?, ?, ?
                )
            ");


            $stmt->execute([

                $applicationNumber,

                $universityId,

                $departmentId,

                $programId,

                $email !== ''
                    ? $email
                    : null,

                $indexNumber,

                $nidPassport,

                $fullName,

                $phone,

                $fatherName !== ''
                    ? $fatherName
                    : null,

                $fatherPhone !== ''
                    ? $fatherPhone
                    : null,

                $motherName !== ''
                    ? $motherName
                    : null,

                $motherPhone !== ''
                    ? $motherPhone
                    : null,

                $province,

                $district,

                $sector,

                $cell,

                $village,

                $address !== ''
                    ? $address
                    : null,

                $educationSchool !== ''
                    ? $educationSchool
                    : null,

                $educationCombination !== ''
                    ? $educationCombination
                    : null,

                $educationYear !== ''
                    ? (int) $educationYear
                    : null,

                $applicantType,

                $passportPhoto,

                $nidPhoto,

                $resultSlip,

                'SUBMITTED'
            ]);


            $applicationId =
                (int) $pdo->lastInsertId();


            /*
            |--------------------------------------------------------------------------
            | COMMIT
            |--------------------------------------------------------------------------
            */

            $pdo->commit();


            /*
            |--------------------------------------------------------------------------
            | SUCCESS PAGE
            |--------------------------------------------------------------------------
            */

            header(
                'Location: success.php?application=' .
                urlencode(
                    $applicationNumber
                )
            );

            exit;


        } catch (Throwable $e) {

            if (
                $pdo->inTransaction()
            ) {

                $pdo->rollBack();
            }

            $errors[] =
                'Application submission failed.';

            $errors[] =
                $e->getMessage();
        }
    }

} elseif (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    !$applicationsOpen
) {

    $errors[] =
        'Applications are currently closed. Please try again later.';
}

?>
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>
    SmartApply — University Application
</title>

<style>

* {
    box-sizing: border-box;
}

body {

    margin: 0;

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

    background:
        linear-gradient(
            135deg,
            #f4f7fb,
            #eef3f9
        );

    color: #172033;
}

.topbar {

    background: #ffffff;

    border-bottom:
        1px solid #e5e9f0;

    padding: 18px 20px;

    position: sticky;

    top: 0;

    z-index: 50;
}

.topbar-inner {

    width:
        min(1150px, 100%);

    margin: auto;

    display: flex;

    justify-content:
        space-between;

    align-items: center;

    gap: 20px;
}

.brand {

    font-size: 23px;

    font-weight: 900;

    color: #1769aa;
}

.brand small {

    display: block;

    font-size: 12px;

    color: #718096;

    margin-top: 3px;

    font-weight: 500;
}

.container {

    width:
        min(1150px, 100%);

    margin:
        32px auto;

    padding:
        0 18px;
}

.hero {

    background:
        linear-gradient(
            135deg,
            #1769aa,
            #0f4f80
        );

    color: white;

    border-radius: 22px;

    padding: 32px;

    margin-bottom: 22px;

    box-shadow:
        0 18px 40px
        rgba(23,105,170,.18);
}

.hero h1 {

    margin:
        0 0 8px;

    font-size:
        clamp(26px, 4vw, 38px);
}

.hero p {

    margin: 0;

    line-height: 1.6;

    opacity: .92;
}

.status {

    margin-top: 20px;

    display: inline-flex;

    padding:
        10px 15px;

    border-radius: 999px;

    background:
        rgba(255,255,255,.15);

    font-weight: 800;

    font-size: 14px;
}


/*
|--------------------------------------------------------------------------
| PAYMENT SUMMARY
|--------------------------------------------------------------------------
*/

.payment-summary {

    margin-top: 20px;

    display: grid;

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

    gap: 14px;
}

.payment-summary-box {

    background:
        rgba(255,255,255,.12);

    border:
        1px solid
        rgba(255,255,255,.20);

    border-radius: 14px;

    padding: 16px;
}

.payment-summary-box small {

    display: block;

    opacity: .80;

    font-size: 12px;

    margin-bottom: 6px;

    font-weight: 700;
}

.payment-summary-box strong {

    font-size: 21px;
}


/*
|--------------------------------------------------------------------------
| CLOSED
|--------------------------------------------------------------------------
*/

.closed-card {

    background: white;

    border-radius: 22px;

    padding: 40px 28px;

    text-align: center;

    box-shadow:
        0 12px 35px
        rgba(25,40,65,.08);
}

.closed-icon {

    font-size: 55px;

    margin-bottom: 12px;
}

.closed-card h2 {

    margin:
        0 0 10px;

    color: #b42318;
}

.closed-card p {

    color: #667085;

    line-height: 1.6;
}


/*
|--------------------------------------------------------------------------
| CONTACT BOX
|--------------------------------------------------------------------------
*/

.contact-box {

    margin-top: 25px;

    display: flex;

    flex-wrap: wrap;

    justify-content: center;

    gap: 10px;
}

.contact-box a {

    text-decoration: none;

    padding:
        11px 16px;

    border-radius: 10px;

    background: #f2f6fa;

    color: #1769aa;

    font-weight: 700;
}


/*
|--------------------------------------------------------------------------
| FORM
|--------------------------------------------------------------------------
*/

.form-card {

    background: white;

    border-radius: 22px;

    padding: 30px;

    box-shadow:
        0 12px 35px
        rgba(25,40,65,.07);
}

.section {

    margin-bottom: 35px;
}

.section-title {

    display: flex;

    align-items: center;

    gap: 12px;

    margin-bottom: 20px;

    padding-bottom: 12px;

    border-bottom:
        1px solid #edf0f5;
}

.number {

    width: 35px;

    height: 35px;

    border-radius: 50%;

    display: flex;

    align-items: center;

    justify-content: center;

    background: #e8f2fb;

    color: #1769aa;

    font-weight: 900;
}

.section-title h2 {

    margin: 0;

    font-size: 20px;
}

.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;
}

label {

    font-size: 14px;

    font-weight: 750;

    color: #374151;
}

label span {

    color: #e11d48;
}

input,
select,
textarea {

    width: 100%;

    border:
        1px solid #d9e0ea;

    border-radius: 11px;

    padding:
        13px 14px;

    font-size: 15px;

    font-family: inherit;

    background: white;

    outline: none;

    transition:
        border-color .2s,
        box-shadow .2s;
}

input:focus,
select:focus,
textarea:focus {

    border-color:
        #1769aa;

    box-shadow:
        0 0 0 3px
        rgba(23,105,170,.1);
}

textarea {

    min-height: 90px;

    resize: vertical;
}

select:disabled {

    background: #f5f7fa;

    cursor: not-allowed;
}

.radio-group {

    display: flex;

    flex-wrap: wrap;

    gap: 12px;
}

.radio {

    flex: 1;

    min-width: 160px;

    border:
        1px solid #d9e0ea;

    border-radius: 11px;

    padding: 14px;

    display: flex;

    align-items: center;

    gap: 9px;

    cursor: pointer;
}

.radio input {

    width: auto;
}

.help {

    font-size: 12px;

    color: #718096;
}


/*
|--------------------------------------------------------------------------
| ALERT
|--------------------------------------------------------------------------
*/

.alert {

    border-radius: 12px;

    padding:
        15px 17px;

    margin-bottom: 22px;

    line-height: 1.5;
}

.alert.error {

    background:
        #fff1f2;

    border:
        1px solid #fecdd3;

    color: #9f1239;
}

.alert ul {

    margin:
        7px 0 0;

    padding-left: 20px;
}


/*
|--------------------------------------------------------------------------
| PAYMENT INFORMATION
|--------------------------------------------------------------------------
*/

.payment-card {

    background:
        linear-gradient(
            135deg,
            #f7fbff,
            #eef7ff
        );

    border:
        1px solid #cfe6fa;

    border-radius: 22px;

    padding: 28px;

    margin-top: 22px;

    box-shadow:
        0 12px 35px
        rgba(25,40,65,.06);
}

.payment-card .section-title {

    margin-bottom: 18px;
}

.payment-intro {

    color: #475467;

    line-height: 1.6;

    margin:
        0 0 18px;
}

.price-box {

    background: white;

    border:
        2px solid #1769aa;

    border-radius: 16px;

    padding: 20px;

    text-align: center;

    margin-bottom: 18px;
}

.price-box small {

    display: block;

    color: #667085;

    font-size: 13px;

    font-weight: 750;

    margin-bottom: 7px;
}

.price {

    color: #1769aa;

    font-size:
        clamp(28px, 5vw, 38px);

    font-weight: 950;

    letter-spacing: .5px;
}

.payment-code-box {

    background: white;

    border:
        2px dashed #1769aa;

    border-radius: 14px;

    padding: 18px;

    text-align: center;

    margin-top: 15px;
}

.payment-code-box small {

    display: block;

    color: #667085;

    font-size: 12px;

    font-weight: 750;

    margin-bottom: 8px;
}

.payment-code {

    font-size: 21px;

    font-weight: 950;

    letter-spacing: 1.5px;

    color: #1769aa;

    word-break: break-word;
}

.payment-warning {

    margin-top: 18px;

    padding:
        14px 16px;

    border-radius: 12px;

    background:
        #fff7e6;

    border:
        1px solid #f6d58b;

    color:
        #7a5200;

    line-height: 1.6;

    font-size: 14px;
}

.payment-contact {

    margin-top: 17px;

    color: #475467;

    line-height: 1.6;
}

.payment-contact a {

    color: #1769aa;

    font-weight: 850;
}


/*
|--------------------------------------------------------------------------
| NEED HELP
|--------------------------------------------------------------------------
*/

.help-card {

    background: white;

    border-radius: 22px;

    padding: 28px;

    margin-top: 22px;

    box-shadow:
        0 12px 35px
        rgba(25,40,65,.07);
}

.help-description {

    color: #667085;

    line-height: 1.6;

    margin-top: -7px;

    margin-bottom: 20px;
}

.help-grid {

    display: grid;

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

    gap: 12px;
}

.help-button {

    display: flex;

    align-items: center;

    justify-content: center;

    text-decoration: none;

    padding:
        13px 15px;

    border-radius: 11px;

    background:
        #f2f6fa;

    color:
        #1769aa;

    font-weight: 800;

    border:
        1px solid #e0e7ef;

    transition:
        .2s;
}

.help-button:hover {

    transform:
        translateY(-1px);

    background:
        #e9f2f9;
}

.help-button.whatsapp {

    background:
        #eafaf0;

    color:
        #087443;

    border-color:
        #b7ebca;
}

.help-button.instagram {

    background:
        #fff1f7;

    color:
        #c13584;

    border-color:
        #f4c2d8;
}

.help-button.group {

    background:
        #1769aa;

    color: white;

    border-color:
        #1769aa;
}


/*
|--------------------------------------------------------------------------
| SUBMIT
|--------------------------------------------------------------------------
*/

.submit-area {

    padding-top: 22px;

    border-top:
        1px solid #edf0f5;

    display: flex;

    align-items: center;

    justify-content: space-between;

    gap: 20px;
}

.submit-note {

    color: #718096;

    font-size: 13px;

    line-height: 1.6;
}

button {

    border: 0;

    border-radius: 12px;

    padding:
        14px 28px;

    background:
        #1769aa;

    color: white;

    font-size: 15px;

    font-weight: 850;

    cursor: pointer;
}

button:hover {

    background:
        #125687;
}

button:disabled {

    opacity: .6;

    cursor: not-allowed;
}

.loading {

    display: none;

    margin-top: 10px;

    color: #1769aa;

    font-size: 13px;
}


/*
|--------------------------------------------------------------------------
| FOOTER CONTACT PERSON
|--------------------------------------------------------------------------
*/

.contact-person {

    text-align: center;

    color: #667085;

    padding:
        20px 0 30px;

    font-size: 13px;
}

.contact-person strong {

    color: #172033;
}


/*
|--------------------------------------------------------------------------
| RESPONSIVE
|--------------------------------------------------------------------------
*/

@media (max-width:700px) {

    .container {

        margin-top: 20px;

        padding:
            0 12px;
    }

    .hero {

        padding: 24px;

        border-radius: 17px;
    }

    .form-card {

        padding:
            21px 16px;

        border-radius: 17px;
    }

    .payment-card,
    .help-card {

        padding:
            21px 17px;

        border-radius: 17px;
    }

    .grid {

        grid-template-columns: 1fr;
    }

    .field.full {

        grid-column: auto;
    }

    .payment-summary {

        grid-template-columns: 1fr;
    }

    .help-grid {

        grid-template-columns: 1fr;
    }

    .submit-area {

        flex-direction: column;

        align-items: stretch;
    }

    button {

        width: 100%;
    }
}

</style>

</head>

<body>

<header class="topbar">

<div class="topbar-inner">

<div class="brand">

SmartApply

<small>
University Application Service
</small>

</div>

</div>

</header>


<main class="container">


<!-- HERO -->

<div class="hero">

<h1>
University Application
</h1>

<p>
Complete the application form carefully.
Your information will be used to process your university application.
</p>


<?php if ($applicationsOpen): ?>

<div class="status">
🟢 Applications are currently open.
</div>

<?php else: ?>

<div class="status">
🔴 Applications are currently closed.
</div>

<?php endif; ?>


<!-- PRICE SUMMARY -->

<?php if ($applicationsOpen): ?>

<div class="payment-summary">

<div class="payment-summary-box">

<small>
Application Price
</small>

<strong>
<?= e($formattedApplicationPrice) ?>
<?= e($currency) ?>
</strong>

</div>


<div class="payment-summary-box">

<small>
Payment Method
</small>

<strong>
Mobile Money
</strong>

</div>

</div>

<?php endif; ?>

</div>


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


<!-- CLOSED -->

<div class="closed-card">

<div class="closed-icon">
🔴
</div>

<h2>
Applications are currently closed
</h2>

<p>
We are not accepting new applications at the moment.
Please check again later or contact us for more information.
</p>

<div class="contact-box">

<?php if ($contactPhone !== ''): ?>

<a href="tel:<?= e($contactPhone) ?>">
📞 Call Us
</a>

<?php endif; ?>


<?php if ($whatsappUrl !== ''): ?>

<a
    href="<?= e($whatsappUrl) ?>"
    target="_blank"
    rel="noopener"
>
💬 WhatsApp
</a>

<?php endif; ?>


<?php if ($contactEmail !== ''): ?>

<a href="mailto:<?= e($contactEmail) ?>">
✉️ Email
</a>

<?php endif; ?>

</div>

</div>


<?php else: ?>


<!-- FORM -->

<form
    method="POST"
    enctype="multipart/form-data"
    class="form-card"
    id="applicationForm"
>


<?php if ($errors): ?>

<div class="alert error">

<strong>
❌ Application Submission Failed
</strong>

<ul>

<?php foreach ($errors as $error): ?>

<li>
<?= e($error) ?>
</li>

<?php endforeach; ?>

</ul>

</div>

<?php endif; ?>


<!-- EDUCATION -->

<section class="section">

<div class="section-title">

<div class="number">1</div>

<h2>
Education Information
</h2>

</div>

<div class="grid">


<div class="field">

<label>
Index Number <span>*</span>
</label>

<input
    type="text"
    name="index_number"
    required
    value="<?= e($post['index_number'] ?? '') ?>"
    placeholder="Enter index number"
>

</div>


<div class="field">

<label>
NID / Passport ID <span>*</span>
</label>

<input
    type="text"
    name="nid_passport"
    required
    value="<?= e($post['nid_passport'] ?? '') ?>"
    placeholder="NID or Passport ID"
>

</div>


<div class="field full">

<label>
Full Name <span>*</span>
</label>

<input
    type="text"
    name="full_name"
    required
    value="<?= e($post['full_name'] ?? '') ?>"
    placeholder="Your full name"
>

</div>


<div class="field full">

<label>
Email
</label>

<input
    type="email"
    name="email"
    value="<?= e($post['email'] ?? '') ?>"
    placeholder="example@email.com"
>

</div>

</div>

</section>


<!-- PARENTS -->

<section class="section">

<div class="section-title">

<div class="number">2</div>

<h2>
Parents Information
</h2>

</div>

<div class="grid">


<div class="field">

<label>
Father's Name
</label>

<input
    type="text"
    name="father_name"
    value="<?= e($post['father_name'] ?? '') ?>"
>

</div>


<div class="field">

<label>
Father's Phone
</label>

<input
    type="tel"
    name="father_phone"
    value="<?= e($post['father_phone'] ?? '') ?>"
>

</div>


<div class="field">

<label>
Mother's Name
</label>

<input
    type="text"
    name="mother_name"
    value="<?= e($post['mother_name'] ?? '') ?>"
>

</div>


<div class="field">

<label>
Mother's Phone
</label>

<input
    type="tel"
    name="mother_phone"
    value="<?= e($post['mother_phone'] ?? '') ?>"
>

</div>

</div>

</section>


<!-- RWANDA ADDRESS -->

<section class="section">

<div class="section-title">

<div class="number">3</div>

<h2>
Rwanda Address
</h2>

</div>

<div class="grid">


<div class="field full">

<label>
Phone Number <span>*</span>
</label>

<input
    type="tel"
    name="phone"
    required
    value="<?= e($post['phone'] ?? '') ?>"
    placeholder="07XXXXXXXX"
>

</div>


<div class="field">

<label>
Province <span>*</span>
</label>

<select
    name="province"
    id="province"
    required
>

<option value="">
Select Province
</option>

</select>

</div>


<div class="field">

<label>
District <span>*</span>
</label>

<select
    name="district"
    id="district"
    required
    disabled
>

<option value="">
Select Province first
</option>

</select>

</div>


<div class="field">

<label>
Sector <span>*</span>
</label>

<select
    name="sector"
    id="sector"
    required
    disabled
>

<option value="">
Select District first
</option>

</select>

</div>


<div class="field">

<label>
Cell <span>*</span>
</label>

<select
    name="cell"
    id="cell"
    required
    disabled
>

<option value="">
Select Sector first
</option>

</select>

</div>


<div class="field">

<label>
Village <span>*</span>
</label>

<select
    name="village"
    id="village"
    required
    disabled
>

<option value="">
Select Cell first
</option>

</select>

</div>


<div class="field full">

<label>
Additional Address
</label>

<textarea
    name="address"
    placeholder="Additional address information"
><?= e($post['address'] ?? '') ?></textarea>

</div>

</div>

</section>


<!-- EDUCATION BACKGROUND -->

<section class="section">

<div class="section-title">

<div class="number">4</div>

<h2>
Education Background
</h2>

</div>

<div class="grid">


<div class="field full">

<label>
A-Level School
</label>

<input
    type="text"
    name="education_school"
    value="<?= e($post['education_school'] ?? '') ?>"
>

</div>


<div class="field">

<label>
A-Level Combination
</label>

<input
    type="text"
    name="education_combination"
    value="<?= e($post['education_combination'] ?? '') ?>"
    placeholder="e.g. PCM"
>

</div>


<div class="field">

<label>
Completion Year
</label>

<input
    type="number"
    name="education_year"
    min="1900"
    max="<?= date('Y') ?>"
    value="<?= e($post['education_year'] ?? '') ?>"
>

</div>

</div>

</section>


<!-- UNIVERSITY -->

<section class="section">

<div class="section-title">

<div class="number">5</div>

<h2>
University Choice
</h2>

</div>

<div class="grid">


<div class="field">

<label>
University <span>*</span>
</label>

<select
    name="university_id"
    id="university"
    required
>

<option value="">
Select University
</option>

<?php foreach ($universities as $university): ?>

<option
    value="<?= (int) $university['id'] ?>"
    <?= (
        (int)($post['university_id'] ?? 0)
        ===
        (int)$university['id']
    ) ? 'selected' : '' ?>
>

<?= e($university['name']) ?>

<?php if (!empty($university['code'])): ?>

(<?= e($university['code']) ?>)

<?php endif; ?>

</option>

<?php endforeach; ?>

</select>

</div>


<div class="field">

<label>
Department <span>*</span>
</label>

<select
    name="department_id"
    id="department"
    required
    disabled
>

<option>
Select University first
</option>

</select>

</div>


<div class="field full">

<label>
Option to Study <span>*</span>
</label>

<select
    name="program_id"
    id="program"
    required
    disabled
>

<option>
Select Department first
</option>

</select>

</div>

</div>

</section>


<!-- APPLICANT TYPE -->

<section class="section">

<div class="section-title">

<div class="number">6</div>

<h2>
Applicant Type
</h2>

</div>

<div class="radio-group">


<label class="radio">

<input
    type="radio"
    name="applicant_type"
    value="Government"
    required
    <?= (
        ($post['applicant_type'] ?? '')
        ===
        'Government'
    ) ? 'checked' : '' ?>
>

<span>
Government
</span>

</label>


<label class="radio">

<input
    type="radio"
    name="applicant_type"
    value="Private"
    <?= (
        ($post['applicant_type'] ?? '')
        ===
        'Private'
    ) ? 'checked' : '' ?>
>

<span>
Private
</span>

</label>

</div>

</section>


<!-- DOCUMENTS -->

<section class="section">

<div class="section-title">

<div class="number">7</div>

<h2>
Documents
</h2>

</div>

<div class="grid">


<div class="field">

<label>
Passport Photo
</label>

<input
    type="file"
    name="passport_photo"
    accept="image/jpeg,image/png,image/webp"
>

<div class="help">
Maximum 5 MB.
</div>

</div>


<div class="field">

<label>
National ID Photo
</label>

<input
    type="file"
    name="nid_photo"
    accept="image/jpeg,image/png,image/webp"
>

<div class="help">
Maximum 5 MB.
</div>

</div>


<div class="field full">

<label>
Result Slip
</label>

<input
    type="file"
    name="result_slip"
    accept="image/jpeg,image/png,application/pdf"
>

<div class="help">
Maximum 5 MB.
</div>

</div>

</div>

</section>


<!-- SUBMIT -->

<div class="submit-area">

<div class="submit-note">

Please check all information before submitting.

<br>

<strong>
We will contact you using the phone number provided.
</strong>

</div>

<button
    type="submit"
    id="submitButton"
>
Submit Application
</button>

</div>

<div
    class="loading"
    id="loading"
>
Submitting your application...
</div>

</form>


<!-- PAYMENT INFORMATION -->

<div class="payment-card">

<div class="section-title">

<div class="number">
💳
</div>

<h2>
Payment Information
</h2>

</div>


<p class="payment-intro">

The application price is set by the administrator.
Please make sure you pay the exact amount shown below.

</p>


<div class="price-box">

<small>
Application Price
</small>

<div class="price">

<?= e($formattedApplicationPrice) ?>
<?= e($currency) ?>

</div>

</div>


<?php if ($paymentCode !== ''): ?>

<div class="payment-code-box">

<small>
Payment Code
</small>

<div class="payment-code">

<?= e($paymentCode) ?>

</div>

</div>

<?php endif; ?>


<div class="payment-warning">

<strong>
⚠️ Important:
</strong>

<br>

Please contact us before making payment.
Do not send money to a number that has not been verified with us.

</div>


<?php if ($contactPhone !== ''): ?>

<div class="payment-contact">

<strong>
📞 Payment Assistance:
</strong>

<a
    href="tel:<?= e($contactPhone) ?>"
>
<?= e($contactPhone) ?>
</a>

</div>

<?php endif; ?>

</div>


<!-- NEED HELP -->

<div class="help-card">

<div class="section-title">

<div class="number">
📞
</div>

<h2>
Need Help?
</h2>

</div>


<p class="help-description">

If you have questions about the application,
payment or required documents, contact us using any
of the options below.

</p>


<div class="help-grid">


<?php if ($contactPhone !== ''): ?>

<a
    class="help-button"
    href="tel:<?= e($contactPhone) ?>"
>
📞 Call Us
</a>

<?php endif; ?>


<?php if ($whatsappUrl !== ''): ?>

<a
    class="help-button whatsapp"
    href="<?= e($whatsappUrl) ?>"
    target="_blank"
    rel="noopener"
>
💬 Chat on WhatsApp
</a>

<?php endif; ?>


<?php if ($contactEmail !== ''): ?>

<a
    class="help-button"
    href="mailto:<?= e($contactEmail) ?>"
>
✉️ Send Email
</a>

<?php endif; ?>


<?php if ($instagramUrl !== ''): ?>

<a
    class="help-button instagram"
    href="<?= e($instagramUrl) ?>"
    target="_blank"
    rel="noopener"
>
📸 Instagram
</a>

<?php endif; ?>


<?php if ($whatsappGroupLink !== ''): ?>

<a
    class="help-button group"
    href="<?= e($whatsappGroupLink) ?>"
    target="_blank"
    rel="noopener"
>
💬 Join WhatsApp Group
</a>

<?php endif; ?>

</div>

</div>


<!-- CONTACT PERSON -->

<?php if ($contactName !== ''): ?>

<div class="contact-person">

Need help?

<strong>
<?= e($contactName) ?>
</strong>

is available to assist you.

</div>

<?php endif; ?>


<?php endif; ?>

</main>


<script>

/*
|--------------------------------------------------------------------------
| DATA FROM PHP
|--------------------------------------------------------------------------
*/

const locations =
    <?= json_encode(
        $locations,
        JSON_UNESCAPED_UNICODE |
        JSON_UNESCAPED_SLASHES |
        JSON_HEX_TAG |
        JSON_HEX_AMP |
        JSON_HEX_APOS |
        JSON_HEX_QUOT
    ) ?>;

const departmentData =
    <?= json_encode(
        $departmentData,
        JSON_UNESCAPED_UNICODE |
        JSON_UNESCAPED_SLASHES |
        JSON_HEX_TAG |
        JSON_HEX_AMP |
        JSON_HEX_APOS |
        JSON_HEX_QUOT
    ) ?>;

const programData =
    <?= json_encode(
        $programData,
        JSON_UNESCAPED_UNICODE |
        JSON_UNESCAPED_SLASHES |
        JSON_HEX_TAG |
        JSON_HEX_AMP |
        JSON_HEX_APOS |
        JSON_HEX_QUOT
    ) ?>;


/*
|--------------------------------------------------------------------------
| LOCATION ELEMENTS
|--------------------------------------------------------------------------
*/

const province =
    document.getElementById('province');

const district =
    document.getElementById('district');

const sector =
    document.getElementById('sector');

const cell =
    document.getElementById('cell');

const village =
    document.getElementById('village');


/*
|--------------------------------------------------------------------------
| UNIVERSITY ELEMENTS
|--------------------------------------------------------------------------
*/

const university =
    document.getElementById('university');

const department =
    document.getElementById('department');

const program =
    document.getElementById('program');


/*
|--------------------------------------------------------------------------
| FORM
|--------------------------------------------------------------------------
*/

const form =
    document.getElementById('applicationForm');

const submitButton =
    document.getElementById('submitButton');

const loading =
    document.getElementById('loading');


/*
|--------------------------------------------------------------------------
| RESET SELECT
|--------------------------------------------------------------------------
*/

function resetSelect(
    select,
    text
) {

    select.innerHTML =
        '';

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

    option.value =
        '';

    option.textContent =
        text;

    select.appendChild(option);

    select.disabled =
        true;
}


/*
|--------------------------------------------------------------------------
| LOAD PROVINCES
|--------------------------------------------------------------------------
*/

function loadProvinces() {

    resetSelect(
        province,
        'Select Province'
    );

    Object.keys(locations)
        .sort()
        .forEach(function(name) {

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

            option.value =
                name;

            option.textContent =
                name;

            province.appendChild(
                option
            );
        });

    province.disabled =
        false;
}


/*
|--------------------------------------------------------------------------
| LOAD DISTRICTS
|--------------------------------------------------------------------------
*/

function loadDistricts(
    provinceName
) {

    resetSelect(
        district,
        'Select District'
    );

    resetSelect(
        sector,
        'Select District first'
    );

    resetSelect(
        cell,
        'Select Sector first'
    );

    resetSelect(
        village,
        'Select Cell first'
    );

    if (
        !provinceName ||
        !locations[provinceName]
    ) {

        return;
    }

    Object.keys(
        locations[provinceName]
    )
    .sort()
    .forEach(function(name) {

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

        option.value =
            name;

        option.textContent =
            name;

        district.appendChild(
            option
        );
    });

    district.disabled =
        false;
}


/*
|--------------------------------------------------------------------------
| LOAD SECTORS
|--------------------------------------------------------------------------
*/

function loadSectors(
    provinceName,
    districtName
) {

    resetSelect(
        sector,
        'Select Sector'
    );

    resetSelect(
        cell,
        'Select Sector first'
    );

    resetSelect(
        village,
        'Select Cell first'
    );

    if (
        !provinceName ||
        !districtName ||
        !locations[provinceName] ||
        !locations[provinceName][districtName]
    ) {

        return;
    }

    Object.keys(
        locations[
            provinceName
        ][
            districtName
        ]
    )
    .sort()
    .forEach(function(name) {

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

        option.value =
            name;

        option.textContent =
            name;

        sector.appendChild(
            option
        );
    });

    sector.disabled =
        false;
}


/*
|--------------------------------------------------------------------------
| LOAD CELLS
|--------------------------------------------------------------------------
*/

function loadCells(
    provinceName,
    districtName,
    sectorName
) {

    resetSelect(
        cell,
        'Select Cell'
    );

    resetSelect(
        village,
        'Select Cell first'
    );

    if (
        !provinceName ||
        !districtName ||
        !sectorName ||
        !locations[provinceName] ||
        !locations[provinceName][districtName] ||
        !locations[provinceName][districtName][sectorName]
    ) {

        return;
    }

    Object.keys(
        locations[
            provinceName
        ][
            districtName
        ][
            sectorName
        ]
    )
    .sort()
    .forEach(function(name) {

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

        option.value =
            name;

        option.textContent =
            name;

        cell.appendChild(
            option
        );
    });

    cell.disabled =
        false;
}


/*
|--------------------------------------------------------------------------
| LOAD VILLAGES
|--------------------------------------------------------------------------
*/

function loadVillages(
    provinceName,
    districtName,
    sectorName,
    cellName
) {

    resetSelect(
        village,
        'Select Village'
    );

    if (
        !provinceName ||
        !districtName ||
        !sectorName ||
        !cellName ||
        !locations[provinceName] ||
        !locations[provinceName][districtName] ||
        !locations[provinceName][districtName][sectorName] ||
        !locations[provinceName][districtName][sectorName][cellName]
    ) {

        return;
    }

    const villages =
        locations[
            provinceName
        ][
            districtName
        ][
            sectorName
        ][
            cellName
        ];

    villages
        .slice()
        .sort()
        .forEach(function(name) {

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

            option.value =
                name;

            option.textContent =
                name;

            village.appendChild(
                option
            );
        });

    village.disabled =
        false;
}


/*
|--------------------------------------------------------------------------
| UNIVERSITY → DEPARTMENT
|--------------------------------------------------------------------------
*/

function loadDepartments(
    universityId
) {

    resetSelect(
        department,
        'Select Department'
    );

    resetSelect(
        program,
        'Select Department first'
    );

    if (
        !universityId ||
        !departmentData[universityId]
    ) {

        return;
    }

    departmentData[
        universityId
    ]
    .slice()
    .sort(function(a,b) {

        return a.name.localeCompare(
            b.name
        );
    })
    .forEach(function(item) {

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

        option.value =
            item.id;

        option.textContent =
            item.name;

        department.appendChild(
            option
        );
    });

    department.disabled =
        false;
}


/*
|--------------------------------------------------------------------------
| DEPARTMENT → PROGRAM
|--------------------------------------------------------------------------
*/

function loadPrograms(
    universityId,
    departmentId
) {

    resetSelect(
        program,
        'Select Option'
    );

    if (
        !universityId ||
        !departmentId
    ) {

        return;
    }

    const selectedDepartment =
        departmentData[
            universityId
        ]?.find(function(item) {

            return Number(item.id) ===
                Number(departmentId);
        });

    if (!selectedDepartment) {

        return;
    }

    const departmentName =
        selectedDepartment.name;

    if (
        !programData[universityId] ||
        !programData[universityId][departmentName]
    ) {

        program.innerHTML =
            '<option value="">No options available</option>';

        return;
    }

    programData[
        universityId
    ][
        departmentName
    ]
    .slice()
    .sort(function(a,b) {

        return a.option.localeCompare(
            b.option
        );
    })
    .forEach(function(item) {

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

        option.value =
            item.id;

        option.textContent =
            item.option;

        program.appendChild(
            option
        );
    });

    program.disabled =
        false;
}


/*
|--------------------------------------------------------------------------
| EVENTS
|--------------------------------------------------------------------------
*/

province?.addEventListener(
    'change',
    function() {

        loadDistricts(
            this.value
        );
    }
);


district?.addEventListener(
    'change',
    function() {

        loadSectors(
            province.value,
            this.value
        );
    }
);


sector?.addEventListener(
    'change',
    function() {

        loadCells(
            province.value,
            district.value,
            this.value
        );
    }
);


cell?.addEventListener(
    'change',
    function() {

        loadVillages(
            province.value,
            district.value,
            sector.value,
            this.value
        );
    }
);


university?.addEventListener(
    'change',
    function() {

        loadDepartments(
            this.value
        );
    }
);


department?.addEventListener(
    'change',
    function() {

        loadPrograms(
            university.value,
            this.value
        );
    }
);


/*
|--------------------------------------------------------------------------
| RESTORE FORM VALUES
|--------------------------------------------------------------------------
*/

document.addEventListener(
    'DOMContentLoaded',
    function() {

        loadProvinces();


        <?php if (!empty($post['province'])): ?>

        const oldProvince =
            <?= json_encode(
                $post['province']
            ) ?>;

        const oldDistrict =
            <?= json_encode(
                $post['district'] ?? ''
            ) ?>;

        const oldSector =
            <?= json_encode(
                $post['sector'] ?? ''
            ) ?>;

        const oldCell =
            <?= json_encode(
                $post['cell'] ?? ''
            ) ?>;

        const oldVillage =
            <?= json_encode(
                $post['village'] ?? ''
            ) ?>;


        province.value =
            oldProvince;

        loadDistricts(
            oldProvince
        );

        district.value =
            oldDistrict;

        loadSectors(
            oldProvince,
            oldDistrict
        );

        sector.value =
            oldSector;

        loadCells(
            oldProvince,
            oldDistrict,
            oldSector
        );

        cell.value =
            oldCell;

        loadVillages(
            oldProvince,
            oldDistrict,
            oldSector,
            oldCell
        );

        village.value =
            oldVillage;

        <?php endif; ?>


        <?php if (!empty($post['university_id'])): ?>

        const oldUniversity =
            <?= (int) $post['university_id'] ?>;

        const oldDepartment =
            <?= (int) ($post['department_id'] ?? 0) ?>;

        const oldProgram =
            <?= (int) ($post['program_id'] ?? 0) ?>;


        university.value =
            String(oldUniversity);

        loadDepartments(
            oldUniversity
        );

        if (oldDepartment > 0) {

            department.value =
                String(oldDepartment);

            loadPrograms(
                oldUniversity,
                oldDepartment
            );

            if (oldProgram > 0) {

                program.value =
                    String(oldProgram);
            }
        }

        <?php endif; ?>

    }
);


/*
|--------------------------------------------------------------------------
| SUBMIT UI
|--------------------------------------------------------------------------
*/

form?.addEventListener(
    'submit',
    function() {

        submitButton.disabled =
            true;

        submitButton.textContent =
            'Submitting...';

        loading.style.display =
            'block';
    }
);

</script>

</body>

</html>