<?php

declare(strict_types=1);

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

session_start();

$pdo = Database::connection();

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

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

$id = (int)($_GET['id'] ?? $_POST['id'] ?? 0);

if ($id <= 0) {
    die('Invalid application ID.');
}

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

$success = '';
$error   = '';

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

    $data = [

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

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

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

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

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

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

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

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

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

        '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_school'
            => trim(
                $_POST['education_school']
                ?? ''
            ),

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

        'education_year'
            => $_POST['education_year'] !== ''
                ? (int)$_POST['education_year']
                : null,

        'applicant_type'
            => $_POST['applicant_type']
                ?: null,

        'status'
            => $_POST['status'] ?? 'SUBMITTED',

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

    $allowedStatuses = [
        'SUBMITTED',
        'PROCESSING',
        'COMPLETED',
        'NEEDS_CORRECTION',
        'CANCELLED'
    ];

    if (
        !in_array(
            $data['status'],
            $allowedStatuses,
            true
        )
    ) {

        $error =
            'Invalid status.';

    } elseif (
        $data['full_name'] === ''
    ) {

        $error =
            'Full name is required.';

    } elseif (
        $data['phone'] === ''
    ) {

        $error =
            'Phone number is required.';

    } else {

        try {

            $pdo->beginTransaction();

            /*
             * Current status
             */

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

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

            $oldStatus =
                $stmt->fetchColumn();

            if ($oldStatus === false) {

                throw new RuntimeException(
                    'Application not found.'
                );
            }

            /*
             * Update
             */

            $stmt = $pdo->prepare("

                UPDATE applications

                SET

                    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 = ?,

                    status = ?,

                    admin_note = ?

                WHERE id = ?

            ");

            $stmt->execute([

                $data['email'],

                $data['index_number'],

                $data['nid_passport'],

                $data['full_name'],

                $data['phone'],

                $data['father_name'],

                $data['father_phone'],

                $data['mother_name'],

                $data['mother_phone'],

                $data['province'],

                $data['district'],

                $data['sector'],

                $data['cell'],

                $data['village'],

                $data['address'],

                $data['education_school'],

                $data['education_combination'],

                $data['education_year'],

                $data['applicant_type'],

                $data['status'],

                $data['admin_note'],

                $id

            ]);

            /*
             * History
             */

            if (
                $oldStatus !==
                $data['status']
            ) {

                $stmt = $pdo->prepare("
                    INSERT INTO
                        application_status_history
                    (
                        application_id,
                        old_status,
                        new_status
                    )
                    VALUES
                    (?, ?, ?)
                ");

                $stmt->execute([

                    $id,

                    $oldStatus,

                    $data['status']

                ]);
            }

            $pdo->commit();

            $success =
                'Application updated successfully.';

        } catch (Throwable $e) {

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

            $error =
                'Unable to update application: '
                . $e->getMessage();
        }
    }
}

/*
|--------------------------------------------------------------------------
| LOAD APPLICATION
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("

    SELECT

        a.*,

        u.name AS university_name,

        u.code AS university_code,

        u.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

    WHERE a.id = ?

    LIMIT 1
");

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

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

if (!$application) {
    die('Application not found.');
}

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

<head>

<meta charset="UTF-8">

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

<title>
Edit Application -
<?= e($application['application_number']) ?>
</title>

<style>

* {
    box-sizing: border-box;
}

body {
    margin: 0;
    background: #f5f7fb;
    color: #172033;
    font-family:
        Inter,
        system-ui,
        sans-serif;
}

.container {
    width: min(1100px, 94%);
    margin: 35px auto;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 15px;
    margin-bottom: 25px;
}

.header h1 {
    margin: 0;
}

.header p {
    color: #6b7280;
}

.card {
    background: white;
    border: 1px solid #e5e7eb;
    border-radius: 16px;
    padding: 25px;
    margin-bottom: 20px;
}

.grid {
    display: grid;
    grid-template-columns:
        repeat(2,minmax(0,1fr));
    gap: 17px;
}

.full {
    grid-column: 1/-1;
}

.field {
    display: flex;
    flex-direction: column;
    gap: 7px;
}

label {
    font-weight: 700;
    font-size: 14px;
}

input,
select,
textarea {
    width: 100%;
    padding: 11px 13px;
    border: 1px solid #d1d5db;
    border-radius: 9px;
    font: inherit;
    background: white;
}

textarea {
    min-height: 100px;
    resize: vertical;
}

.btn {
    border: 0;
    border-radius: 9px;
    padding: 11px 17px;
    cursor: pointer;
    font-weight: 700;
}

.primary {
    background: #2563eb;
    color: white;
}

.secondary {
    background: #e5e7eb;
    color: #111827;
}

.success {
    background: #dcfce7;
    color: #166534;
    padding: 13px;
    border-radius: 9px;
    margin-bottom: 20px;
}

.error {
    background: #fee2e2;
    color: #991b1b;
    padding: 13px;
    border-radius: 9px;
    margin-bottom: 20px;
}

.info {
    background: #eff6ff;
    border: 1px solid #bfdbfe;
    border-radius: 12px;
    padding: 15px;
    margin-bottom: 20px;
}

.actions {
    display: flex;
    gap: 10px;
    margin-top: 25px;
}

@media(max-width:700px) {

    .grid {
        grid-template-columns: 1fr;
    }

    .full {
        grid-column: auto;
    }

    .header {
        flex-direction: column;
        align-items: flex-start;
    }
}

</style>

</head>

<body>

<div class="container">

<div class="header">

<div>

<h1>
Edit Application
</h1>

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

</div>

<a
    href="dashboard.php"
    class="btn secondary"
>
    ← Back
</a>

</div>


<?php if ($success): ?>

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

<?php endif; ?>


<?php if ($error): ?>

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

<?php endif; ?>


<div class="info">

<strong>
University:
</strong>

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

<br>

<strong>
Programme:
</strong>

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

<br>

<strong>
Portal:
</strong>

<?= e(
    $application['application_url']
    ?? 'Not configured'
) ?>

</div>


<form method="POST">

<input
    type="hidden"
    name="id"
    value="<?= (int)$id ?>"
>


<div class="card">

<h2>
Personal Information
</h2>

<br>

<div class="grid">


<div class="field">

<label>
Full Name
</label>

<input
    type="text"
    name="full_name"
    value="<?= e(
        $application['full_name']
    ) ?>"
    required
>

</div>


<div class="field">

<label>
Phone
</label>

<input
    type="text"
    name="phone"
    value="<?= e(
        $application['phone']
    ) ?>"
    required
>

</div>


<div class="field">

<label>
Email
</label>

<input
    type="email"
    name="email"
    value="<?= e(
        $application['email']
    ) ?>"
>

</div>


<div class="field">

<label>
Index Number
</label>

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

</div>


<div class="field">

<label>
NID / Passport
</label>

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

</div>


<div class="field">

<label>
Applicant Type
</label>

<select name="applicant_type">

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

<option
    value="Government"
    <?= $application['applicant_type']
        === 'Government'
        ? 'selected'
        : '' ?>
>
Government
</option>

<option
    value="Private"
    <?= $application['applicant_type']
        === 'Private'
        ? 'selected'
        : '' ?>
>
Private
</option>

</select>

</div>


<div class="field">

<label>
Father Name
</label>

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

</div>


<div class="field">

<label>
Father Phone
</label>

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

</div>


<div class="field">

<label>
Mother Name
</label>

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

</div>


<div class="field">

<label>
Mother Phone
</label>

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

</div>

</div>

</div>


<div class="card">

<h2>
Address
</h2>

<br>

<div class="grid">


<div class="field">

<label>
Province
</label>

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

</div>


<div class="field">

<label>
District
</label>

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

</div>


<div class="field">

<label>
Sector
</label>

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

</div>


<div class="field">

<label>
Cell
</label>

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

</div>


<div class="field">

<label>
Village
</label>

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

</div>


<div class="field full">

<label>
Address
</label>

<textarea
    name="address"
><?= e(
    $application['address']
) ?></textarea>

</div>

</div>

</div>


<div class="card">

<h2>
Academic Information
</h2>

<br>

<div class="grid">


<div class="field">

<label>
Last Secondary School
</label>

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

</div>


<div class="field">

<label>
Combination
</label>

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

</div>


<div class="field">

<label>
Education Year
</label>

<input
    type="number"
    name="education_year"
    value="<?= e(
        (string)(
            $application[
                'education_year'
            ] ?? ''
        )
    ) ?>"
>

</div>


<div class="field">

<label>
Status
</label>

<select name="status">

<?php

$statuses = [
    'SUBMITTED',
    'PROCESSING',
    'COMPLETED',
    'NEEDS_CORRECTION',
    'CANCELLED'
];

foreach ($statuses as $status):

?>

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

<?php endforeach; ?>

</select>

</div>


<div class="field full">

<label>
Admin Note
</label>

<textarea
    name="admin_note"
><?= e(
    $application['admin_note']
) ?></textarea>

</div>

</div>

</div>


<div class="actions">

<button
    type="submit"
    name="save_application"
    class="btn primary"
>
    💾 Save Changes
</button>


<a
    href="dashboard.php"
    class="btn secondary"
>
    Cancel
</a>

</div>

</form>

</div>

</body>

</html>