<?php

declare(strict_types=1);

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

$pdo = Database::connection();


/*
|--------------------------------------------------------------------------
| 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 NUMBER
|--------------------------------------------------------------------------
*/

$applicationNumber =
    trim(
        $_GET['application'] ?? ''
    );


/*
|--------------------------------------------------------------------------
| RESULT VARIABLES
|--------------------------------------------------------------------------
*/

$application = null;

$error = '';


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

if ($applicationNumber === '') {

    $error =
        'No application number was provided.';

} else {

    try {

        $stmt = $pdo->prepare("
            SELECT

                a.*,

                u.name AS university_name,

                u.code AS university_code,

                d.name AS department_name,

                p.option_name AS 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.application_number = ?

            LIMIT 1
        ");

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

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

        if (!$application) {

            $error =
                'Application not found. Please check your application number.';

        }

    } catch (Throwable $e) {

        $error =
            'Unable to load your application. Please try again later.';
    }
}


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

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

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

    $applicationStatus =
        'CLOSED';
}

$applicationsOpen =
    $applicationStatus === 'OPEN';


/*
|--------------------------------------------------------------------------
| CONTACT 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
| setting_key = application_price
|
*/

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

$applicationPriceNumber =
    (float) $applicationPrice;


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

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

$whatsappUrl = '';

if ($whatsappDigits !== '') {

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

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

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


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

$applicationDbStatus =
    strtoupper(
        (string) (
            $application['status']
            ?? 'SUBMITTED'
        )
    );


$statusLabels = [

    'SUBMITTED' =>
        'Application Submitted',

    'PROCESSING' =>
        'Application is being processed',

    'COMPLETED' =>
        'Application Completed',

    'NEEDS_CORRECTION' =>
        'Correction Required',

    'CANCELLED' =>
        'Application Cancelled'
];


$statusLabel =
    $statusLabels[
        $applicationDbStatus
    ] ??
    $applicationDbStatus;


$statusClass =
    match ($applicationDbStatus) {

        'COMPLETED' =>
            'success',

        'NEEDS_CORRECTION' =>
            'warning',

        'CANCELLED' =>
            'danger',

        'PROCESSING' =>
            'processing',

        default =>
            'submitted'
    };


/*
|--------------------------------------------------------------------------
| PAYMENT INSTRUCTION
|--------------------------------------------------------------------------
*/

$paymentInstruction =
    'Please contact us before making payment. ' .
    'Do not make payment to an unverified number.';

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>
SmartApply — Application Result
</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: white;

    border-bottom:
        1px solid #e5e9f0;

    padding:
        18px 20px;
}

.topbar-inner {

    width:
        min(1050px,100%);

    margin: auto;
}

.brand {

    font-size: 23px;

    font-weight: 900;

    color: #1769aa;
}

.brand small {

    display: block;

    font-size: 12px;

    color: #718096;

    font-weight: 500;

    margin-top: 3px;
}

.container {

    width:
        min(1050px,100%);

    margin:
        35px auto;

    padding:
        0 18px;
}

.card {

    background: white;

    border-radius: 22px;

    padding:
        32px;

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

    margin-bottom: 22px;
}

.result-header {

    text-align: center;

    padding-bottom:
        25px;

    border-bottom:
        1px solid #edf0f5;
}

.success-icon {

    font-size: 55px;

    margin-bottom: 10px;
}

.result-header h1 {

    margin:
        0 0 10px;

    font-size:
        clamp(25px,4vw,35px);

    color: #1769aa;
}

.result-header p {

    margin: 0;

    color: #667085;

    line-height: 1.6;
}

.number-box {

    margin-top: 20px;

    display: inline-block;

    background:
        #eef7ff;

    color:
        #1769aa;

    border:
        1px solid #cce5ff;

    padding:
        12px 18px;

    border-radius: 12px;

    font-weight: 900;

    letter-spacing: .5px;
}

.status-row {

    display: grid;

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

    gap: 15px;

    margin-top: 25px;
}

.status-card {

    border-radius: 14px;

    padding: 18px;

    background:
        #f8fafc;

    border:
        1px solid #e6eaf0;
}

.status-card small {

    display: block;

    color: #667085;

    font-size: 12px;

    margin-bottom: 7px;

    font-weight: 700;
}

.status-card strong {

    font-size: 15px;
}

.application-status {

    display: inline-flex;

    padding:
        8px 12px;

    border-radius: 999px;

    font-size: 13px;

    font-weight: 850;
}

.application-status.submitted {

    background:
        #eaf4ff;

    color:
        #1769aa;
}

.application-status.processing {

    background:
        #fff7e6;

    color:
        #9a6700;
}

.application-status.success {

    background:
        #e9f9ef;

    color:
        #087443;
}

.application-status.warning {

    background:
        #fff4e5;

    color:
        #9a6700;
}

.application-status.danger {

    background:
        #fff0f0;

    color:
        #b42318;
}

.open-status {

    margin-top: 20px;

    padding:
        14px 16px;

    border-radius: 12px;

    font-weight: 800;
}

.open-status.open {

    background:
        #e9f9ef;

    color:
        #087443;

    border:
        1px solid #b7ebca;
}

.open-status.closed {

    background:
        #fff1f2;

    color:
        #b42318;

    border:
        1px solid #fecdd3;
}

.section-title {

    margin:
        0 0 18px;

    font-size: 20px;

    color: #172033;
}

.info-grid {

    display: grid;

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

    gap: 14px;
}

.info {

    background:
        #f8fafc;

    border:
        1px solid #e7ebf0;

    border-radius: 12px;

    padding: 15px;
}

.info small {

    display: block;

    font-size: 12px;

    color: #667085;

    margin-bottom: 6px;

    font-weight: 700;
}

.info strong {

    font-size: 14px;

    word-break: break-word;
}

.payment {

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

    border:
        1px solid #cfe6fa;
}


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

.payment-amount {

    margin:
        18px 0;

    padding:
        20px;

    background:
        white;

    border:
        2px solid #1769aa;

    border-radius:
        14px;

    text-align:
        center;
}

.payment-amount small {

    display:
        block;

    color:
        #667085;

    font-size:
        13px;

    font-weight:
        800;

    margin-bottom:
        7px;

    text-transform:
        uppercase;

    letter-spacing:
        .5px;
}

.payment-amount strong {

    display:
        block;

    color:
        #1769aa;

    font-size:
        30px;

    font-weight:
        950;

    letter-spacing:
        .5px;
}

.payment-note {

    color:
        #475467;

    line-height: 1.6;

    font-size: 14px;
}

.payment-code {

    margin-top: 15px;

    background: white;

    border:
        2px dashed #1769aa;

    border-radius: 13px;

    padding: 17px;

    text-align: center;

    font-size: 22px;

    font-weight: 950;

    letter-spacing: 2px;

    color: #1769aa;
}

.contact-grid {

    display: grid;

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

    gap: 12px;
}

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

.contact-button:hover {

    transform:
        translateY(-1px);

    background:
        #e9f2f9;
}

.whatsapp {

    background:
        #eafaf0;

    color:
        #087443;

    border-color:
        #b7ebca;
}

.group {

    background:
        #1769aa;

    color: white;

    border-color:
        #1769aa;
}

.retry {

    display: inline-block;

    text-decoration: none;

    padding:
        13px 20px;

    border-radius: 11px;

    background:
        #1769aa;

    color: white;

    font-weight: 800;

    margin-top: 8px;
}

.error-card {

    text-align: center;
}

.error-icon {

    font-size: 55px;
}

.error-card h1 {

    color:
        #b42318;
}

.error-card p {

    color:
        #667085;

    line-height: 1.6;
}

@media (max-width:700px) {

    .container {

        margin-top: 20px;

        padding:
            0 12px;
    }

    .card {

        padding:
            23px 17px;

        border-radius: 17px;
    }

    .status-row,
    .info-grid,
    .contact-grid {

        grid-template-columns: 1fr;
    }

    .payment-amount strong {

        font-size:
            26px;
    }
}

</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">


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


<div class="card error-card">

<div class="error-icon">
❌
</div>

<h1>
Application Submission Failed
</h1>

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

<p>
Please try again or contact us using the contact options below.
</p>


<div class="contact-grid">

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

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

<?php endif; ?>


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

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

<?php endif; ?>


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

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

<?php endif; ?>

</div>


<a
    class="retry"
    href="index.php"
>
← Try Again
</a>

</div>


<?php else: ?>


<!-- SUCCESS HEADER -->

<div class="card">

<div class="result-header">

<div class="success-icon">
🎉
</div>

<h1>
Application Submitted Successfully
</h1>

<p>
Your application has been received successfully.
Please keep your application number for future reference.
</p>

<div class="number-box">

Application Number:
<br>

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

</div>

</div>


<div class="status-row">


<div class="status-card">

<small>
Application Status
</small>

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

<?= e($statusLabel) ?>

</span>

</div>


<div class="status-card">

<small>
Application Availability
</small>

<?php if ($applicationsOpen): ?>

<strong style="color:#087443;">
🟢 Applications are currently open.
</strong>

<?php else: ?>

<strong style="color:#b42318;">
🔴 Applications are currently closed.
</strong>

<?php endif; ?>

</div>

</div>

</div>


<!-- APPLICATION INFORMATION -->

<div class="card">

<h2 class="section-title">
📋 Your Application Information
</h2>

<div class="info-grid">


<div class="info">

<small>
Full Name
</small>

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

</div>


<div class="info">

<small>
Phone Number
</small>

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

</div>


<div class="info">

<small>
Email
</small>

<strong>
<?= e(
    $application['email'] ?: 'Not provided'
) ?>
</strong>

</div>


<div class="info">

<small>
Index Number
</small>

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

</div>


<div class="info">

<small>
University
</small>

<strong>

<?= e(
    $application['university_name']
    ?? 'N/A'
) ?>

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

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

<?php endif; ?>

</strong>

</div>


<div class="info">

<small>
Department
</small>

<strong>
<?= e(
    $application['department_name']
    ?? 'N/A'
) ?>
</strong>

</div>


<div class="info">

<small>
Option
</small>

<strong>
<?= e(
    $application['option_name']
    ?? 'N/A'
) ?>
</strong>

</div>


<div class="info">

<small>
Applicant Type
</small>

<strong>
<?= e(
    $application['applicant_type']
    ?? 'N/A'
) ?>
</strong>

</div>


<div class="info">

<small>
Province
</small>

<strong>
<?= e(
    $application['province']
    ?? 'N/A'
) ?>
</strong>

</div>


<div class="info">

<small>
District
</small>

<strong>
<?= e(
    $application['district']
    ?? 'N/A'
) ?>
</strong>

</div>


<div class="info">

<small>
Sector
</small>

<strong>
<?= e(
    $application['sector']
    ?? 'N/A'
) ?>
</strong>

</div>


<div class="info">

<small>
Cell
</small>

<strong>
<?= e(
    $application['cell']
    ?? 'N/A'
) ?>
</strong>

</div>


<div class="info">

<small>
Village
</small>

<strong>
<?= e(
    $application['village']
    ?? 'N/A'
) ?>
</strong>

</div>


<div class="info">

<small>
Submitted At
</small>

<strong>
<?= e(
    $application['created_at']
    ?? 'N/A'
) ?>
</strong>

</div>

</div>

</div>


<!-- APPLICATION OPEN/CLOSED -->

<div class="card">

<h2 class="section-title">
📢 Application Status
</h2>

<?php if ($applicationsOpen): ?>

<div class="open-status open">

🟢 Applications are currently open.

</div>

<?php else: ?>

<div class="open-status closed">

🔴 Applications are currently closed.

</div>

<?php endif; ?>

</div>


<!-- PAYMENT -->

<div class="card payment">

<h2 class="section-title">
💳 Payment Information
</h2>


<!-- APPLICATION PRICE -->

<div class="payment-amount">

<small>
Application Fee
</small>

<strong>

<?= number_format(
    $applicationPriceNumber,
    0,
    '.',
    ','
) ?>

RWF

</strong>

</div>


<p class="payment-note">

<?= e(
    $paymentInstruction
) ?>

</p>


<!-- PAYMENT CODE -->

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

<div>

<strong>
Payment Code
</strong>

<div class="payment-code">

<?= e(
    $paymentCode
) ?>

</div>

</div>

<?php else: ?>

<div class="info">

<small>
Payment Code
</small>

<strong>
Payment code is currently unavailable.
Please contact us.
</strong>

</div>

<?php endif; ?>


<!-- PHONE -->

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

<p class="payment-note">

<strong>
📞 Call:
</strong>

<a
    href="tel:<?= e($contactPhone) ?>"
    style="color:#1769aa;font-weight:800;"
>
<?= e($contactPhone) ?>
</a>

</p>

<?php endif; ?>


<p class="payment-note">

<strong>
⚠️ Important:
</strong>

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

</p>

</div>


<!-- CONTACT -->

<div class="card">

<h2 class="section-title">
📞 Need Help?
</h2>

<div class="contact-grid">


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

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

<?php endif; ?>


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

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

<?php endif; ?>


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

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

<?php endif; ?>


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

<a
    class="contact-button"
    href="https://instagram.com/<?= e(ltrim($contactInstagram, '@')) ?>"
    target="_blank"
    rel="noopener"
>
📸 Instagram
</a>

<?php endif; ?>

</div>

</div>


<!-- WHATSAPP GROUP -->

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

<div class="card">

<h2 class="section-title">
📢 Stay Updated
</h2>

<p class="payment-note">

Join our WhatsApp group to receive important information,
application updates and announcements.

</p>

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

</div>

<?php endif; ?>


<!-- CONTACT PERSON -->

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

<div
    style="
        text-align:center;
        color:#667085;
        padding:10px 0 30px;
        font-size:13px;
    "
>

Need help?

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

is available to assist you.

</div>

<?php endif; ?>


<?php endif; ?>


</main>

</body>

</html>