<?php
declare(strict_types=1);

session_start();

error_reporting(E_ALL);
ini_set('display_errors', '1'); // change to 0 in production

require_once __DIR__ . '/db.php';

require __DIR__ . '/../PHPMailer/src/Exception.php';
require __DIR__ . '/../PHPMailer/src/PHPMailer.php';
require __DIR__ . '/../PHPMailer/src/SMTP.php';

use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;

if (!isset($_SESSION['admin'])) {
    http_response_code(403);
    exit('Admin only');
}

$conn->set_charset('utf8mb4');

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

/*
|--------------------------------------------------------------------------
| Config
|--------------------------------------------------------------------------
*/
$amountColumn = 'price';

$allowedStatuses = [
    'pending',
    'in progress',
    'success',
    'failed',
];

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

function jsonResponse(array $payload, int $statusCode = 200): void
{
    http_response_code($statusCode);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($payload, JSON_UNESCAPED_UNICODE);
    exit;
}

function formatMoney(float $value): string
{
    return number_format($value, 2);
}

function statusClass(string $status): string
{
    $status = strtolower(trim($status));

    return match ($status) {
        'success'     => 'status-success',
        'failed'      => 'status-failed',
        'in progress' => 'status-progress',
        default       => 'status-pending',
    };
}

function prettyStatus(string $status): string
{
    return ucwords(strtolower(trim($status)));
}

/*
|--------------------------------------------------------------------------
| Dashboard Stats
|--------------------------------------------------------------------------
*/
$stats = [
    'today' => ['count' => 0, 'spent' => 0.00],
    'week'  => ['count' => 0, 'spent' => 0.00],
    'month' => ['count' => 0, 'spent' => 0.00],
    'total' => ['count' => 0, 'spent' => 0.00],
];

$amountExpr = "COALESCE(CAST($amountColumn AS DECIMAL(15,2)), 0)";

$statsSql = "
    SELECT
        SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) AS today_count,
        SUM(CASE WHEN DATE(created_at) = CURDATE() THEN {$amountExpr} ELSE 0 END) AS today_spent,

        SUM(CASE WHEN YEARWEEK(created_at, 1) = YEARWEEK(CURDATE(), 1) THEN 1 ELSE 0 END) AS week_count,
        SUM(CASE WHEN YEARWEEK(created_at, 1) = YEARWEEK(CURDATE(), 1) THEN {$amountExpr} ELSE 0 END) AS week_spent,

        SUM(CASE WHEN YEAR(created_at) = YEAR(CURDATE()) AND MONTH(created_at) = MONTH(CURDATE()) THEN 1 ELSE 0 END) AS month_count,
        SUM(CASE WHEN YEAR(created_at) = YEAR(CURDATE()) AND MONTH(created_at) = MONTH(CURDATE()) THEN {$amountExpr} ELSE 0 END) AS month_spent,

        COUNT(*) AS total_count,
        SUM({$amountExpr}) AS total_spent
    FROM self_delink
";

$statsResult = $conn->query($statsSql);

if ($statsResult instanceof mysqli_result) {
    $statsRow = $statsResult->fetch_assoc();

    if ($statsRow) {
        $stats['today']['count'] = (int)($statsRow['today_count'] ?? 0);
        $stats['today']['spent'] = (float)($statsRow['today_spent'] ?? 0);

        $stats['week']['count'] = (int)($statsRow['week_count'] ?? 0);
        $stats['week']['spent'] = (float)($statsRow['week_spent'] ?? 0);

        $stats['month']['count'] = (int)($statsRow['month_count'] ?? 0);
        $stats['month']['spent'] = (float)($statsRow['month_spent'] ?? 0);

        $stats['total']['count'] = (int)($statsRow['total_count'] ?? 0);
        $stats['total']['spent'] = (float)($statsRow['total_spent'] ?? 0);
    }
}

/*
|--------------------------------------------------------------------------
| AJAX Send Email
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_email'])) {
    $csrfToken = (string)($_POST['csrf_token'] ?? '');

    if (!hash_equals($_SESSION['csrf_token'], $csrfToken)) {
        jsonResponse([
            'status'  => 'error',
            'message' => 'Invalid CSRF token.',
        ], 419);
    }

    $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);

    if (!$id) {
        jsonResponse([
            'status'  => 'error',
            'message' => 'Invalid request ID.',
        ], 422);
    }

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

    if (!$stmt) {
        jsonResponse([
            'status'  => 'error',
            'message' => 'Database prepare error: ' . $conn->error,
        ], 500);
    }

    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();

    if (!$row) {
        jsonResponse([
            'status'  => 'error',
            'message' => 'Record not found.',
        ], 404);
    }

    $nin = trim((string)($row['nin'] ?? ''));
    $ninEmail = trim((string)($row['nin_email'] ?? ''));

    if ($nin === '' && $ninEmail === '') {
        jsonResponse([
            'status'  => 'error',
            'message' => 'NIN and NIN email are empty for this record.',
        ], 422);
    }

    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host       = 'smtp.gmail.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'bilyaminuumar146@gmail.com';
        $mail->Password   = 'buqp mqbh hqtt dxxs';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;

        $mail->setFrom('bilyaminuumar146@gmail.com', 'ASO VERIFY');
        $mail->addAddress('nimccustomercare@nimc.gov.ng');

        $mail->isHTML(false);
        $mail->Subject = 'SELF SERVICE DELINK REQUEST';
        $mail->Body = "Dear NIMC Customer Care,

Please help me to delink this my self service account from my old device I want to login in my new phone please this is my account

{$nin}
{$ninEmail}

Regards,
BILYAN ASO";

        $mail->send();

        $updateStmt = $conn->prepare("
            UPDATE self_delink
            SET email_status = 'Sent'
            WHERE id = ?
        ");

        if ($updateStmt) {
            $updateStmt->bind_param('i', $id);
            $updateStmt->execute();
        }

        jsonResponse([
            'status'  => 'success',
            'message' => 'Email sent successfully.',
        ]);
    } catch (Exception $e) {
        jsonResponse([
            'status'  => 'error',
            'message' => 'SMTP ERROR: ' . $mail->ErrorInfo,
        ], 500);
    }
}

/*
|--------------------------------------------------------------------------
| AJAX Update (status, reply, nin_email)
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update'])) {
    $csrfToken = (string)($_POST['csrf_token'] ?? '');

    if (!hash_equals($_SESSION['csrf_token'], $csrfToken)) {
        jsonResponse([
            'status'  => 'error',
            'message' => 'Invalid CSRF token.',
        ], 419);
    }

    $id     = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
    $status = strtolower(trim((string)($_POST['status'] ?? '')));
    $reply  = trim((string)($_POST['reply'] ?? ''));
    // nin_email is optional in the payload — if the client doesn't send it,
    // we keep the existing value untouched.
    $ninEmailRaw = $_POST['nin_email'] ?? null;

    if (!$id) {
        jsonResponse([
            'status'  => 'error',
            'message' => 'Invalid request ID.',
        ], 422);
    }

    if (!in_array($status, $allowedStatuses, true)) {
        jsonResponse([
            'status'  => 'error',
            'message' => 'Invalid status value.',
        ], 422);
    }

    // Look up the current row only to know what we're changing from.
    // $currentService is intentionally NOT consulted for gating — nin_email
    // is editable on EVERY service, including delinking_retrieve.
    $rowStmt = $conn->prepare("SELECT service_type, nin_email FROM self_delink WHERE id = ? LIMIT 1");
    if (!$rowStmt) {
        jsonResponse([
            'status'  => 'error',
            'message' => 'Failed to prepare lookup statement.',
        ], 500);
    }
    $rowStmt->bind_param('i', $id);
    $rowStmt->execute();
    $rowRes = $rowStmt->get_result();
    $current = $rowRes->fetch_assoc();
    $rowStmt->close();

    if (!$current) {
        jsonResponse([
            'status'  => 'error',
            'message' => 'Record not found.',
        ], 404);
    }

    $currentEmail = (string)($current['nin_email'] ?? '');

    // Decide the new nin_email. Service type is irrelevant — admin can edit
    // (or clear) the email on any row.
    //   - payload missing nin_email field  → keep existing
    //   - empty allowed (admin can clear it)
    //   - non-empty must pass FILTER_VALIDATE_EMAIL, then lowercased
    $newEmail = $currentEmail;     // default: keep existing
    $touched  = false;             // did the client actually send nin_email?

    if (is_string($ninEmailRaw) || is_numeric($ninEmailRaw)) {
        $touched   = true;
        $candidate = trim((string)$ninEmailRaw);

        if ($candidate !== '') {
            if (!filter_var($candidate, FILTER_VALIDATE_EMAIL)) {
                jsonResponse([
                    'status'  => 'error',
                    'message' => 'Invalid NIN email format.',
                ], 422);
            }
            $newEmail = strtolower($candidate);
        } else {
            // Empty value: explicitly clear it.
            $newEmail = '';
        }
    }

    $stmt = $conn->prepare("
        UPDATE self_delink
        SET status = ?, reply = ?, nin_email = ?
        WHERE id = ?
    ");

    if (!$stmt) {
        jsonResponse([
            'status'  => 'error',
            'message' => 'Failed to prepare update statement.',
        ], 500);
    }

    // 4 placeholders in the SQL above match the 4 type chars below:
    //   s = status, s = reply, s = nin_email, i = id
    $stmt->bind_param('sssi', $status, $reply, $newEmail, $id);

    if ($stmt->execute()) {
        $msg = 'Request updated successfully.';
        if ($touched && $newEmail !== $currentEmail) {
            $msg .= " NIN email changed from “{$currentEmail}” to “{$newEmail}”.";
        } elseif ($touched && $newEmail === $currentEmail) {
            $msg .= ' NIN email unchanged.';
        }
        jsonResponse([
            'status'    => 'success',
            'message'   => $msg,
            'nin_email' => $newEmail,
        ]);
    }

    jsonResponse([
        'status'  => 'error',
        'message' => 'Update failed.',
    ], 500);
}

/*
|--------------------------------------------------------------------------
| Search + Fetch
|--------------------------------------------------------------------------
*/
$search = trim((string)($_GET['search'] ?? ''));
$rows   = [];

if ($search !== '') {
    $like = '%' . $search . '%';

    $stmt = $conn->prepare("
        SELECT *
        FROM self_delink
        WHERE
            batch LIKE ?
            OR user_email LIKE ?
            OR nin LIKE ?
            OR nin_email LIKE ?
            OR status LIKE ?
        ORDER BY id DESC
    ");

    if ($stmt) {
        $stmt->bind_param('sssss', $like, $like, $like, $like, $like);
        $stmt->execute();
        $result = $stmt->get_result();
    } else {
        $result = false;
    }
} else {
    $result = $conn->query("
        SELECT *
        FROM self_delink
        ORDER BY id DESC
    ");
}

if ($result instanceof mysqli_result) {
    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Self Delink Admin Panel</title>
    <style>
        :root{
            --bg:#071a2f;
            --bg-2:#0b2340;
            --panel:#0d2a4d;
            --panel-2:#123b69;
            --line:rgba(255,255,255,.10);
            --text:#f4f8ff;
            --muted:#9bb1cc;
            --primary:#00c896;
            --primary-dark:#05241a;
            --white:#ffffff;
            --warning:#ffb020;
            --info:#4ba4ff;
            --success:#39d98a;
            --danger:#ff6177;
            --shadow:0 12px 34px rgba(0,0,0,.28);
            --radius:18px;
        }

        *{ box-sizing:border-box; }
        html,body{ margin:0; padding:0; }

        body{
            min-height:100vh;
            background:
                radial-gradient(circle at top right, rgba(0,200,150,.10), transparent 20%),
                radial-gradient(circle at bottom left, rgba(75,164,255,.10), transparent 18%),
                linear-gradient(180deg, var(--bg) 0%, var(--bg-2) 100%);
            color:var(--text);
            font-family:Inter, Arial, Helvetica, sans-serif;
            padding:20px;
        }

        .container{ max-width:1480px; margin:0 auto; display:grid; gap:20px; }

        .card{
            background:rgba(13,42,77,.95);
            border:1px solid var(--line);
            border-radius:var(--radius);
            padding:20px;
            box-shadow:var(--shadow);
        }

        .topbar{
            display:flex;
            align-items:flex-start;
            justify-content:space-between;
            gap:16px;
            flex-wrap:wrap;
        }

        .title{
            margin:0; font-size:29px; line-height:1.15;
            font-weight:800; letter-spacing:-.02em;
        }
        .subtitle{ margin-top:6px; color:var(--muted); font-size:14px; }

        .search-form{ display:flex; gap:10px; align-items:center; flex-wrap:wrap; }

        .stats-grid{ display:grid; grid-template-columns:repeat(4, minmax(0, 1fr)); gap:20px; }
        .stat-card{ background:linear-gradient(180deg, rgba(18,59,105,.98) 0%, rgba(13,42,77,.98) 100%); }

        .stat-label{
            color:var(--muted);
            font-size:13px;
            text-transform:uppercase;
            letter-spacing:.08em;
            font-weight:800;
            margin-bottom:14px;
        }

        .stat-row{
            display:flex;
            justify-content:space-between;
            align-items:center;
            gap:10px;
            padding:8px 0;
            border-bottom:1px solid rgba(255,255,255,.08);
        }
        .stat-row:last-child{ border-bottom:none; padding-bottom:0; }
        .stat-name{ color:#d3e2f6; font-size:14px; font-weight:600; }
        .stat-value{ color:#ffffff; font-size:19px; font-weight:800; }

        .input, .select, .textarea{
            width:100%;
            border:1px solid #d8e0ec;
            background:#f8fbff;
            color:#0b1220;
            border-radius:12px;
            padding:10px 12px;
            font:inherit;
            outline:none;
        }
        .input:focus, .select:focus, .textarea:focus{
            border-color:#4ba4ff;
            box-shadow:0 0 0 3px rgba(75,164,255,.15);
        }
        .input.is-invalid{
            border-color:#ff6177;
            box-shadow:0 0 0 3px rgba(255,97,119,.18);
        }

        .search-input{ width:min(360px, 100%); }
        .textarea{ min-height:86px; resize:vertical; }

        .btn{
            border:none; border-radius:12px; padding:10px 14px;
            font:inherit; font-weight:700; cursor:pointer;
            transition:transform .15s ease, opacity .15s ease, filter .15s ease;
        }
        .btn:hover{ transform:translateY(-1px); filter:brightness(1.02); }
        .btn:disabled{ opacity:.7; cursor:not-allowed; transform:none; }
        .btn-primary{ background:var(--primary); color:var(--primary-dark); }
        .btn-secondary{ background:#ffffff; color:#111827; }

        .flash{
            display:none;
            margin-bottom:16px;
            padding:12px 14px;
            border-radius:12px;
            font-weight:700;
        }
        .flash.show{ display:block; }
        .flash.success{ background:rgba(57,217,138,.12); color:#7bf0b2; border:1px solid rgba(57,217,138,.28); }
        .flash.error{ background:rgba(255,97,119,.12); color:#ff9baa; border:1px solid rgba(255,97,119,.28); }

        .table-wrap{ overflow-x:auto; border-radius:14px; }
        table{ width:100%; border-collapse:collapse; min-width:1400px; }
        th, td{
            padding:14px 12px;
            text-align:left;
            vertical-align:top;
            border-bottom:1px solid var(--line);
        }
        th{
            color:#d7e4f8;
            font-size:12px;
            text-transform:uppercase;
            letter-spacing:.05em;
            font-weight:800;
            white-space:nowrap;
        }
        td{ color:#eef4ff; font-size:14px; }
        .amount{ font-weight:800; color:#7bf0b2; white-space:nowrap; }

        .status-pill{
            display:inline-flex;
            align-items:center;
            justify-content:center;
            min-width:112px;
            padding:6px 10px;
            border-radius:999px;
            font-size:12px;
            font-weight:800;
            margin-bottom:10px;
            text-transform:uppercase;
        }
        .status-pending{ background:rgba(255,176,32,.14); color:var(--warning); }
        .status-progress{ background:rgba(75,164,255,.14); color:var(--info); }
        .status-success{ background:rgba(57,217,138,.14); color:var(--success); }
        .status-failed{ background:rgba(255,97,119,.14); color:#ff8f9f; }

        .actions{ display:flex; flex-wrap:wrap; gap:8px; }
        .mono{ font-family:ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size:13px; }
        .date{ color:#d6e0ef; white-space:nowrap; }
        .empty-state{ color:var(--muted); padding:24px 8px; }
        .nin-email-cell{ min-width:240px; }

        @media (max-width: 1100px){ .stats-grid{ grid-template-columns:repeat(2, minmax(0, 1fr)); } }
        @media (max-width: 900px){
            body{ padding:14px; }
            .card{ padding:16px; }
            .title{ font-size:24px; }
            .search-input{ width:100%; }
        }
        @media (max-width: 640px){ .stats-grid{ grid-template-columns:1fr; } }
    </style>
</head>
<body>
<div class="container">

    <section class="card">
        <div class="topbar">
            <div>
                <h1 class="title">Self Delink Admin Panel</h1>
                <div class="subtitle">Manage self delink requests, update statuses, save replies, edit NIN emails, and send complaint emails.</div>
            </div>

            <form method="get" class="search-form">
                <input
                    class="input search-input"
                    type="text"
                    name="search"
                    placeholder="Search batch / email / NIN / status"
                    value="<?= e($search) ?>"
                >
                <button type="submit" class="btn btn-primary">Search</button>
            </form>
        </div>
    </section>

    <section class="stats-grid">
        <div class="card stat-card">
            <div class="stat-label">Today</div>
            <div class="stat-row">
                <span class="stat-name">Today Count</span>
                <span class="stat-value"><?= $stats['today']['count'] ?></span>
            </div>
            <div class="stat-row">
                <span class="stat-name">Today Spent</span>
                <span class="stat-value">₦<?= formatMoney($stats['today']['spent']) ?></span>
            </div>
        </div>

        <div class="card stat-card">
            <div class="stat-label">Weekly</div>
            <div class="stat-row">
                <span class="stat-name">Weekly Count</span>
                <span class="stat-value"><?= $stats['week']['count'] ?></span>
            </div>
            <div class="stat-row">
                <span class="stat-name">Weekly Spent</span>
                <span class="stat-value">₦<?= formatMoney($stats['week']['spent']) ?></span>
            </div>
        </div>

        <div class="card stat-card">
            <div class="stat-label">Monthly</div>
            <div class="stat-row">
                <span class="stat-name">Monthly Count</span>
                <span class="stat-value"><?= $stats['month']['count'] ?></span>
            </div>
            <div class="stat-row">
                <span class="stat-name">Monthly Spent</span>
                <span class="stat-value">₦<?= formatMoney($stats['month']['spent']) ?></span>
            </div>
        </div>

        <div class="card stat-card">
            <div class="stat-label">Total</div>
            <div class="stat-row">
                <span class="stat-name">Total Count</span>
                <span class="stat-value"><?= $stats['total']['count'] ?></span>
            </div>
            <div class="stat-row">
                <span class="stat-name">Total Spent</span>
                <span class="stat-value">₦<?= formatMoney($stats['total']['spent']) ?></span>
            </div>
        </div>
    </section>

    <section class="card">
        <div id="flash" class="flash"></div>

        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Batch</th>
                        <th>User Email</th>
                        <th>NIN</th>
                        <th>NIN Email (editable)</th>
                        <th>Service</th>
                        <th>Current Status</th>
                        <th>Update Status</th>
                        <th>Reply</th>
                        <th>Email Status</th>
                        <th>Action</th>
                        <th>Date</th>
                    </tr>
                </thead>

                <tbody>
                <?php if (empty($rows)): ?>
                    <tr>
                        <td colspan="12" class="empty-state">No requests found.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($rows as $r): ?>
                        <?php
                            $id = (int)($r['id'] ?? 0);
                            $status = strtolower(trim((string)($r['status'] ?? 'pending')));
                            $emailStatus = trim((string)($r['email_status'] ?? 'Pending'));
                            $isEmailSent = strtolower($emailStatus) === 'sent';
                            $svcKey = strtolower(trim((string)($r['service_type'] ?? 'delinking')));
                            $svcLbl = match ($svcKey) {
                                'delinking_retrieve' => 'Delink & Retrieve',
                                default              => 'Delink',
                            };
                        ?>
                        <tr id="row-<?= $id ?>">
                            <td><?= $id ?></td>
                            <td class="mono"><?= e((string)($r['batch'] ?? '')) ?></td>
                            <td><?= e((string)($r['user_email'] ?? '')) ?></td>
                            <td class="mono"><?= e((string)($r['nin'] ?? '')) ?></td>
                            <td class="nin-email-cell">
                                <!--
                                  NOTE: No `disabled` attribute and no service-type
                                  gate here on purpose. nin_email is editable on
                                  EVERY service, including delink&retrieve.
                                -->
                                <input
                                    type="email"
                                    class="input nin-email-input"
                                    id="nin-email-<?= $id ?>"
                                    data-id="<?= $id ?>"
                                    data-service="<?= e($svcKey) ?>"
                                    value="<?= e((string)($r['nin_email'] ?? '')) ?>"
                                    placeholder="email@example.com"
                                >
                            </td>
                            <td>
                                <span class="status-pill status-pending" style="cursor:default"><?= e($svcLbl) ?></span>
                            </td>

                            <td>
                                <div class="status-pill <?= statusClass($status) ?>" id="status-pill-<?= $id ?>">
                                    <?= e(prettyStatus($status)) ?>
                                </div>
                            </td>

                            <td>
                                <select class="select" id="status-<?= $id ?>">
                                    <?php foreach ($allowedStatuses as $allowed): ?>
                                        <option
                                            value="<?= e($allowed) ?>"
                                            <?= $status === $allowed ? 'selected' : '' ?>
                                        >
                                            <?= e(prettyStatus($allowed)) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </td>

                            <td>
                                <textarea class="textarea" id="reply-<?= $id ?>"><?= e((string)($r['reply'] ?? '')) ?></textarea>
                            </td>

                            <td>
                                <div
                                    class="status-pill <?= $isEmailSent ? 'status-success' : 'status-pending' ?>"
                                    id="email-status-<?= $id ?>"
                                >
                                    <?= e($emailStatus ?: 'Pending') ?>
                                </div>
                            </td>

                            <td>
                                <div class="actions">
                                    <button
                                        type="button"
                                        class="btn btn-primary"
                                        data-save-request="<?= $id ?>"
                                    >
                                        Update
                                    </button>

                                    <button
                                        type="button"
                                        class="btn btn-secondary"
                                        data-send-email="<?= $id ?>"
                                        data-sent="<?= $isEmailSent ? '1' : '0' ?>"
                                        id="mail-btn-<?= $id ?>"
                                    >
                                        <?= $isEmailSent ? 'Resend Email' : 'Send Email' ?>
                                    </button>
                                </div>
                            </td>

                            <td class="date"><?= e((string)($r['created_at'] ?? '')) ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </section>
</div>

<script>
    const csrfToken = <?= json_encode($_SESSION['csrf_token']) ?>;
    const flash = document.getElementById('flash');

    function showFlash(message, type = 'success') {
        flash.textContent = message;
        flash.className = `flash show ${type}`;

        window.scrollTo({ top: 0, behavior: 'smooth' });

        clearTimeout(showFlash._timer);
        showFlash._timer = setTimeout(() => {
            flash.className = 'flash';
            flash.textContent = '';
        }, 3500);
    }

    function getStatusClass(status) {
        const s = String(status || '').toLowerCase().trim();
        switch (s) {
            case 'success':     return 'status-success';
            case 'failed':      return 'status-failed';
            case 'in progress': return 'status-progress';
            default:            return 'status-pending';
        }
    }

    function prettyStatus(status) {
        const s = String(status || '').toLowerCase().trim();
        return s.replace(/\b\w/g, char => char.toUpperCase());
    }

    function updateStatusPill(id, status) {
        const pill = document.getElementById(`status-pill-${id}`);
        if (!pill) return;
        pill.className = `status-pill ${getStatusClass(status)}`;
        pill.textContent = prettyStatus(status);
    }

    async function saveRequest(id, button = null) {
        const status   = document.getElementById(`status-${id}`)?.value ?? '';
        const reply    = document.getElementById(`reply-${id}`)?.value ?? '';
        const emailEl  = document.getElementById(`nin-email-${id}`);
        const ninEmail = emailEl ? emailEl.value : '';

        // Client-side validation: any non-empty nin_email must look like an
        // email address. Empty is allowed (to clear the field). No service
        // type is treated as special here.
        if (emailEl) {
            const trimmed = (ninEmail || '').trim();
            emailEl.classList.remove('is-invalid');

            if (trimmed !== '' && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmed)) {
                emailEl.classList.add('is-invalid');
                showFlash('That NIN email is not a valid address.', 'error');
                emailEl.focus();
                return false;
            }
        }

        const body = new URLSearchParams({
            update: '1',
            csrf_token: csrfToken,
            id: String(id),
            status,
            reply,
            nin_email: ninEmail
        });

        if (button) {
            button.disabled = true;
            button.dataset.originalText = button.textContent;
            button.textContent = 'Saving...';
        }

        try {
            const response = await fetch(window.location.href, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body
            });

            let data = null;
            try {
                data = await response.json();
            } catch (jsonError) {
                throw new Error('Server returned an invalid response.');
            }

            if (!response.ok || data.status !== 'success') {
                if (emailEl) emailEl.classList.add('is-invalid');
                throw new Error(data.message || 'Update failed.');
            }

            if (emailEl && typeof data.nin_email === 'string') {
                emailEl.value = data.nin_email;
                emailEl.classList.remove('is-invalid');
            }

            updateStatusPill(id, status);
            showFlash(data.message || 'Updated successfully.', 'success');
            return true;
        } catch (error) {
            showFlash(error.message || 'Something went wrong.', 'error');
            return false;
        } finally {
            if (button) {
                button.disabled = false;
                button.textContent = button.dataset.originalText || 'Update';
            }
        }
    }

    async function sendMail(id, button = null) {
        const body = new URLSearchParams({
            send_email: '1',
            csrf_token: csrfToken,
            id: String(id)
        });

        if (button) {
            const wasSent = button.dataset.sent === '1';
            button.disabled = true;
            button.dataset.originalText = button.textContent;
            button.textContent = wasSent ? 'Resending...' : 'Sending...';
        }

        try {
            const response = await fetch(window.location.href, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body
            });

            let data = null;
            try {
                data = await response.json();
            } catch (jsonError) {
                throw new Error('Server returned an invalid response.');
            }

            if (!response.ok || data.status !== 'success') {
                throw new Error(data.message || 'Email sending failed.');
            }

            const badge = document.getElementById(`email-status-${id}`);
            if (badge) {
                badge.className = 'status-pill status-success';
                badge.textContent = 'Sent';
            }

            if (button) {
                button.dataset.sent = '1';
                button.disabled = false;
                button.textContent = 'Resend Email';
            }

            showFlash(data.message || 'Email sent successfully.', 'success');
            return true;
        } catch (error) {
            if (button) {
                button.disabled = false;
                button.textContent = button.dataset.originalText || 'Send Email';
            }
            showFlash(error.message || 'Something went wrong while sending email.', 'error');
            return false;
        }
    }

    document.querySelectorAll('[data-save-request]').forEach(button => {
        button.addEventListener('click', async () => {
            const id = button.getAttribute('data-save-request');
            await saveRequest(id, button);
        });
    });

    document.querySelectorAll('[data-send-email]').forEach(button => {
        button.addEventListener('click', async () => {
            const id = button.getAttribute('data-send-email');
            await sendMail(id, button);
        });
    });

    // Clear the invalid marker as soon as the admin starts editing again.
    document.querySelectorAll('.nin-email-input').forEach(el => {
        el.addEventListener('input', () => el.classList.remove('is-invalid'));
    });
</script>
</body>
</html>
