<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| ASOVERIFY - NIN CUSTOMER SUPPORT
|--------------------------------------------------------------------------
| AJAX SEND / RESEND + SERVER-SIDE SEARCH + PAGINATION
|--------------------------------------------------------------------------
|
| FEATURES:
| - 20 requests per page
| - Previous / Next pagination
| - Page number pagination
| - Search by NIN
| - Search by Email
| - Filter by Request Status
| - Filter by Email Status
| - Server-side filtering
| - AJAX send
| - AJAX resend
| - SMTP
| - IMAP Sent copy
| - email_status update
|--------------------------------------------------------------------------
*/

error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('display_startup_errors', '0');


/* =========================================================
   SESSION
========================================================= */

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}


/* =========================================================
   DATABASE
========================================================= */

require_once __DIR__ . '/db.php';


/* =========================================================
   MAIL CONFIGURATION
========================================================= */

$mailHost = 'mail.asoverify.com.ng';

$mailUsername = 'noreply@asoverify.com.ng';

$mailPassword = 'Sabirata@273';

$smtpHost = $mailHost;
$smtpPort = 465;
$smtpUsername = $mailUsername;
$smtpPassword = $mailPassword;

$imapServer = $mailHost;
$imapPort = 993;
$mailboxEmail = $mailUsername;
$mailboxPassword = $mailPassword;

$fromEmail = $mailUsername;
$fromName = 'ASOVERIFY';

$nimcEmail = 'nimccustomercare@nimc.gov.ng';


/* =========================================================
   DATABASE CONNECTION
========================================================= */

$dbConnection = null;

if (
    isset($conn) &&
    $conn instanceof mysqli
) {
    $dbConnection = $conn;

} elseif (
    isset($pdo) &&
    $pdo instanceof PDO
) {
    $dbConnection = $pdo;
}


/* =========================================================
   JSON RESPONSE
========================================================= */

function jsonResponse(
    bool $success,
    string $message,
    array $extra = [],
    int $httpCode = 200
): never {

    while (ob_get_level() > 0) {
        ob_end_clean();
    }

    http_response_code($httpCode);

    header(
        'Content-Type: application/json; charset=UTF-8'
    );

    header(
        'Cache-Control: no-store, no-cache, must-revalidate'
    );

    echo json_encode(
        array_merge(
            [
                'success' => $success,
                'message' => $message
            ],
            $extra
        ),
        JSON_UNESCAPED_SLASHES |
        JSON_UNESCAPED_UNICODE
    );

    exit;
}


/* =========================================================
   OUTPUT BUFFER
========================================================= */

ob_start();


/* =========================================================
   DATABASE CHECK FOR AJAX
========================================================= */

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

    if (!$dbConnection) {

        jsonResponse(
            false,
            'Database connection was not found.',
            [],
            500
        );
    }
}


/* =========================================================
   HTML ESCAPE
========================================================= */

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


/* =========================================================
   SMTP READ
========================================================= */

function smtpRead($socket): string
{
    $response = '';

    while (!feof($socket)) {

        $line = fgets(
            $socket,
            515
        );

        if ($line === false) {
            break;
        }

        $response .= $line;

        if (
            strlen($line) >= 4 &&
            $line[3] === ' '
        ) {
            break;
        }
    }

    return trim($response);
}


/* =========================================================
   SMTP COMMAND
========================================================= */

function smtpCommand(
    $socket,
    string $command,
    array $expectedCodes = [250]
): string {

    $written =
        @fwrite(
            $socket,
            $command . "\r\n"
        );

    if ($written === false) {

        throw new Exception(
            'Unable to write SMTP command.'
        );
    }

    $response =
        smtpRead($socket);

    if ($response === '') {

        throw new Exception(
            'SMTP server returned an empty response.'
        );
    }

    $code =
        (int)substr(
            $response,
            0,
            3
        );

    if (
        !in_array(
            $code,
            $expectedCodes,
            true
        )
    ) {

        throw new Exception(
            'SMTP error: ' .
            $response
        );
    }

    return $response;
}


/* =========================================================
   BUILD RAW EMAIL
========================================================= */

function buildRawEmail(
    string $fromEmail,
    string $fromName,
    string $toEmail,
    string $subject,
    string $body
): string {

    $encodedFromName =
        '=?UTF-8?B?' .
        base64_encode($fromName) .
        '?=';

    $encodedSubject =
        '=?UTF-8?B?' .
        base64_encode($subject) .
        '?=';

    $body =
        str_replace(
            ["\r\n", "\r"],
            "\n",
            $body
        );

    $body =
        str_replace(
            "\n",
            "\r\n",
            $body
        );

    $body =
        str_replace(
            "\r\n.",
            "\r\n..",
            $body
        );

    $messageId =
        '<' .
        bin2hex(
            random_bytes(16)
        ) .
        '@asoverify.com.ng>';

    $headers = '';

    $headers .=
        'Date: ' .
        date('r') .
        "\r\n";

    $headers .=
        'From: ' .
        $encodedFromName .
        ' <' .
        $fromEmail .
        ">\r\n";

    $headers .=
        'To: <' .
        $toEmail .
        ">\r\n";

    $headers .=
        'Subject: ' .
        $encodedSubject .
        "\r\n";

    $headers .=
        'Message-ID: ' .
        $messageId .
        "\r\n";

    $headers .=
        "MIME-Version: 1.0\r\n";

    $headers .=
        "Content-Type: text/plain; charset=UTF-8\r\n";

    $headers .=
        "Content-Transfer-Encoding: 8bit\r\n";

    $headers .=
        "X-Mailer: ASOVERIFY NIN Customer Support\r\n";

    return
        $headers .
        "\r\n" .
        $body .
        "\r\n";
}


/* =========================================================
   SMTP SEND
========================================================= */

function sendSMTPEmail(
    string $host,
    int $port,
    string $username,
    string $password,
    string $fromEmail,
    string $fromName,
    string $toEmail,
    string $subject,
    string $body
): array {

    $errorNumber = 0;
    $errorString = '';

    $socket =
        @fsockopen(
            'ssl://' . $host,
            $port,
            $errorNumber,
            $errorString,
            30
        );

    if (!$socket) {

        return [
            'success' => false,
            'error' =>
                'SMTP connection failed: ' .
                (
                    $errorString !== ''
                    ? $errorString
                    : 'Unable to connect to SMTP server.'
                )
        ];
    }

    stream_set_timeout(
        $socket,
        30
    );

    try {

        $response =
            smtpRead($socket);

        $code =
            (int)substr(
                $response,
                0,
                3
            );

        if ($code !== 220) {

            throw new Exception(
                'SMTP greeting failed: ' .
                $response
            );
        }

        smtpCommand(
            $socket,
            'EHLO asoverify.com.ng',
            [250]
        );

        smtpCommand(
            $socket,
            'AUTH LOGIN',
            [334]
        );

        smtpCommand(
            $socket,
            base64_encode($username),
            [334]
        );

        smtpCommand(
            $socket,
            base64_encode($password),
            [235]
        );

        smtpCommand(
            $socket,
            'MAIL FROM:<' .
            $fromEmail .
            '>',
            [250]
        );

        smtpCommand(
            $socket,
            'RCPT TO:<' .
            $toEmail .
            '>',
            [250, 251]
        );

        smtpCommand(
            $socket,
            'DATA',
            [354]
        );

        $rawEmail =
            buildRawEmail(
                $fromEmail,
                $fromName,
                $toEmail,
                $subject,
                $body
            );

        $written =
            @fwrite(
                $socket,
                $rawEmail
            );

        if ($written === false) {

            throw new Exception(
                'Could not write email data to SMTP server.'
            );
        }

        @fwrite(
            $socket,
            ".\r\n"
        );

        $response =
            smtpRead($socket);

        $code =
            (int)substr(
                $response,
                0,
                3
            );

        if ($code !== 250) {

            throw new Exception(
                'SMTP rejected the email: ' .
                $response
            );
        }

        @fwrite(
            $socket,
            "QUIT\r\n"
        );

        @fclose($socket);

        return [
            'success' => true,
            'error' => ''
        ];

    } catch (Throwable $e) {

        @fclose($socket);

        return [
            'success' => false,
            'error' =>
                $e->getMessage()
        ];
    }
}


/* =========================================================
   FIND SENT FOLDER
========================================================= */

function findSentFolder(
    $imap,
    string $server,
    int $port
): ?string {

    $prefix =
        '{' .
        $server .
        ':' .
        $port .
        '/imap/ssl/novalidate-cert}';

    $mailboxes =
        @imap_getmailboxes(
            $imap,
            $prefix,
            '*'
        );

    if ($mailboxes === false) {
        return null;
    }

    foreach ($mailboxes as $box) {

        $fullName =
            (string)$box->name;

        $decoded =
            @imap_utf7_decode(
                $fullName
            );

        if ($decoded === false) {
            $decoded = $fullName;
        }

        $folderName =
            $decoded;

        if (
            str_starts_with(
                $folderName,
                '{'
            )
        ) {

            $closeBrace =
                strpos(
                    $folderName,
                    '}'
                );

            if (
                $closeBrace !== false
            ) {

                $folderName =
                    substr(
                        $folderName,
                        $closeBrace + 1
                    );
            }
        }

        $folderLower =
            strtolower(
                trim($folderName)
            );

        $knownSentFolders = [

            'sent',
            'inbox.sent',
            'sent items',
            'inbox.sent items',
            'sent mail',
            'inbox.sent mail',
            'sent messages',
            'inbox.sent messages',
            'mail/sent',
            'mail/sent items'
        ];

        if (
            in_array(
                $folderLower,
                $knownSentFolders,
                true
            )
        ) {

            return $fullName;
        }

        if (
            str_ends_with(
                $folderLower,
                '.sent'
            ) ||
            str_ends_with(
                $folderLower,
                '.sent items'
            ) ||
            str_ends_with(
                $folderLower,
                '.sent mail'
            )
        ) {

            return $fullName;
        }
    }

    return null;
}


/* =========================================================
   SAVE TO SENT
========================================================= */

function saveEmailToSentFolder(
    string $server,
    int $port,
    string $email,
    string $password,
    string $fromEmail,
    string $fromName,
    string $toEmail,
    string $subject,
    string $body
): array {

    if (
        !function_exists('imap_open')
    ) {

        return [
            'success' => false,
            'error' =>
                'PHP IMAP extension is not enabled on this server.'
        ];
    }

    $mailbox =
        '{' .
        $server .
        ':' .
        $port .
        '/imap/ssl/novalidate-cert}INBOX';

    $imap =
        @imap_open(
            $mailbox,
            $email,
            $password
        );

    if (!$imap) {

        return [
            'success' => false,
            'error' =>
                'IMAP connection failed: ' .
                (
                    imap_last_error()
                    ?: 'Unable to login to mailbox.'
                )
        ];
    }

    $sentFolder =
        findSentFolder(
            $imap,
            $server,
            $port
        );

    if ($sentFolder === null) {

        @imap_close($imap);

        return [
            'success' => false,
            'error' =>
                'Sent folder could not be found on the mail server.'
        ];
    }

    $rawEmail =
        buildRawEmail(
            $fromEmail,
            $fromName,
            $toEmail,
            $subject,
            $body
        );

    $saved =
        @imap_append(
            $imap,
            $sentFolder,
            $rawEmail,
            "\\Seen"
        );

    $imapError =
        imap_last_error();

    @imap_close($imap);

    if (!$saved) {

        return [
            'success' => false,
            'error' =>
                'Email was sent, but saving the copy to Sent failed: ' .
                (
                    $imapError
                    ?: 'Unknown IMAP error.'
                )
        ];
    }

    return [
        'success' => true,
        'error' => '',
        'folder' => $sentFolder
    ];
}


/* =========================================================
   GET VALIDATION REQUEST
========================================================= */

function getValidationRequest(
    $db,
    int $requestId
): ?array {

    $sql = "
        SELECT
            id,
            api_request_id,
            reference,
            user_email,
            tracking_id,
            user,
            nin,
            nin_firstname,
            nin_middlename,
            nin_surname,
            nin_dob,
            type,
            status,
            reply,
            price,
            created_at,
            email_status
        FROM validation_requests
        WHERE id = ?
        LIMIT 1
    ";

    if ($db instanceof mysqli) {

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

        if (!$stmt) {

            throw new Exception(
                'Database prepare failed: ' .
                $db->error
            );
        }

        $stmt->bind_param(
            'i',
            $requestId
        );

        if (!$stmt->execute()) {

            throw new Exception(
                'Database query failed: ' .
                $stmt->error
            );
        }

        $result =
            $stmt->get_result();

        $row =
            $result->fetch_assoc();

        $stmt->close();

        return $row ?: null;
    }

    if ($db instanceof PDO) {

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

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

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

        return $row ?: null;
    }

    throw new Exception(
        'Unsupported database connection.'
    );
}


/* =========================================================
   UPDATE EMAIL STATUS
========================================================= */

function updateEmailStatus(
    $db,
    int $requestId,
    string $status
): bool {

    $sql = "
        UPDATE validation_requests
        SET email_status = ?
        WHERE id = ?
        LIMIT 1
    ";

    if ($db instanceof mysqli) {

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

        if (!$stmt) {

            throw new Exception(
                'Database prepare failed: ' .
                $db->error
            );
        }

        $stmt->bind_param(
            'si',
            $status,
            $requestId
        );

        $success =
            $stmt->execute();

        $stmt->close();

        return $success;
    }

    if ($db instanceof PDO) {

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

        return $stmt->execute([
            $status,
            $requestId
        ]);
    }

    return false;
}


/* =========================================================
   AJAX SEND / RESEND
========================================================= */

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

    if (
        session_status() !== PHP_SESSION_ACTIVE
    ) {

        jsonResponse(
            false,
            'Admin session is not available.',
            [],
            403
        );
    }

    if (empty($_SESSION)) {

        jsonResponse(
            false,
            'Admin session expired. Please login again.',
            [],
            403
        );
    }

    $action =
        trim(
            (string)(
                $_POST['action']
                ?? ''
            )
        );

    $requestId =
        (int)(
            $_POST['request_id']
            ?? 0
        );

    if (
        $action !== 'send_email' &&
        $action !== 'resend_email'
    ) {

        jsonResponse(
            false,
            'Invalid email action.',
            [],
            400
        );
    }

    if ($requestId <= 0) {

        jsonResponse(
            false,
            'Invalid request ID.',
            [],
            400
        );
    }

    try {

        $request =
            getValidationRequest(
                $dbConnection,
                $requestId
            );

    } catch (Throwable $e) {

        jsonResponse(
            false,
            'Database error: ' .
            $e->getMessage(),
            [],
            500
        );
    }

    if (!$request) {

        jsonResponse(
            false,
            'Validation request #' .
            $requestId .
            ' was not found.',
            [],
            404
        );
    }

    $nin =
        trim(
            (string)(
                $request['nin']
                ?? ''
            )
        );

    if ($nin === '') {

        jsonResponse(
            false,
            'Request #' .
            $requestId .
            ' does not contain a NIN.',
            [],
            400
        );
    }

    $firstName =
        trim(
            (string)(
                $request['nin_firstname']
                ?? ''
            )
        );

    $middleName =
        trim(
            (string)(
                $request['nin_middlename']
                ?? ''
            )
        );

    $surname =
        trim(
            (string)(
                $request['nin_surname']
                ?? ''
            )
        );

    $customerName =
        trim(
            $firstName .
            ' ' .
            $middleName .
            ' ' .
            $surname
        );

    if ($customerName === '') {
        $customerName = 'Customer';
    }

    $reference =
        trim(
            (string)(
                $request['reference']
                ?? ''
            )
        );

    if ($reference === '') {
        $reference = 'N/A';
    }

    $subject =
        'Request for Assistance Validating NIN';

    $emailBody =
"Dear NIMC Customer Care,

Please help me to validate this NIN because I am unable to use it for any service.

NIN: {$nin}

Customer Name: {$customerName}

Reference: {$reference}

Request ID: {$requestId}

Please check the NIN and kindly assist with the issue.

Thank you.

ASOVERIFY";

    $smtpResult =
        sendSMTPEmail(
            $smtpHost,
            $smtpPort,
            $smtpUsername,
            $smtpPassword,
            $fromEmail,
            $fromName,
            $nimcEmail,
            $subject,
            $emailBody
        );

    if (
        $smtpResult['success']
    ) {

        $sentResult =
            saveEmailToSentFolder(
                $imapServer,
                $imapPort,
                $mailboxEmail,
                $mailboxPassword,
                $fromEmail,
                $fromName,
                $nimcEmail,
                $subject,
                $emailBody
            );

        try {

            $statusUpdated =
                updateEmailStatus(
                    $dbConnection,
                    $requestId,
                    'Sent'
                );

        } catch (Throwable $e) {

            $statusUpdated = false;
        }

        if (
            $sentResult['success']
        ) {

            $message =
                '✓ Email sent successfully to ' .
                $nimcEmail .
                ' for NIN ' .
                $nin .
                '. A copy was saved to Sent.';

        } else {

            $message =
                '✓ Email sent successfully to ' .
                $nimcEmail .
                ' for NIN ' .
                $nin .
                '. However, the Sent copy could not be saved: ' .
                $sentResult['error'];
        }

        if (!$statusUpdated) {

            $message .=
                ' Warning: email_status could not be updated.';
        }

        jsonResponse(
            true,
            $message,
            [
                'request_id' =>
                    $requestId,

                'nin' =>
                    $nin,

                'email_status' =>
                    'Sent',

                'sent_saved' =>
                    (bool)$sentResult['success'],

                'sent_folder' =>
                    $sentResult['folder']
                    ?? null
            ]
        );
    }

    try {

        updateEmailStatus(
            $dbConnection,
            $requestId,
            'Failed'
        );

    } catch (Throwable $e) {
        // Keep original SMTP error.
    }

    jsonResponse(
        false,
        '✗ Email was not sent for NIN ' .
        $nin .
        ': ' .
        $smtpResult['error'],
        [
            'request_id' =>
                $requestId,

            'nin' =>
                $nin,

            'email_status' =>
                'Failed'
        ],
        500
    );
}


/* =========================================================
   PAGINATION SETTINGS
========================================================= */

$perPage = 20;


/* =========================================================
   CURRENT PAGE
========================================================= */

$page =
    isset($_GET['page'])
    ? (int)$_GET['page']
    : 1;

if ($page < 1) {
    $page = 1;
}


/* =========================================================
   SEARCH / FILTER VALUES
========================================================= */

$searchNin =
    trim(
        (string)(
            $_GET['nin']
            ?? ''
        )
    );

$searchEmail =
    trim(
        (string)(
            $_GET['email']
            ?? ''
        )
    );

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

$filterEmailStatus =
    trim(
        (string)(
            $_GET['email_status']
            ?? ''
        )
    );


/* =========================================================
   STATUS LISTS
========================================================= */

$requestStatuses = [];
$emailStatuses = [];


try {

    /*
     * Request statuses.
     */

    $statusSql = "
        SELECT DISTINCT status
        FROM validation_requests
        WHERE status IS NOT NULL
          AND TRIM(status) <> ''
        ORDER BY status ASC
    ";

    if ($dbConnection instanceof mysqli) {

        $result =
            $dbConnection->query(
                $statusSql
            );

        if ($result) {

            while (
                $row =
                $result->fetch_assoc()
            ) {

                $status =
                    trim(
                        (string)(
                            $row['status']
                            ?? ''
                        )
                    );

                if ($status !== '') {
                    $requestStatuses[$status] = true;
                }
            }
        }

    } elseif (
        $dbConnection instanceof PDO
    ) {

        $stmt =
            $dbConnection->query(
                $statusSql
            );

        if ($stmt) {

            while (
                $row =
                $stmt->fetch(
                    PDO::FETCH_ASSOC
                )
            ) {

                $status =
                    trim(
                        (string)(
                            $row['status']
                            ?? ''
                        )
                    );

                if ($status !== '') {
                    $requestStatuses[$status] = true;
                }
            }
        }
    }


    /*
     * Email statuses.
     */

    $emailStatusSql = "
        SELECT DISTINCT email_status
        FROM validation_requests
        WHERE email_status IS NOT NULL
          AND TRIM(email_status) <> ''
        ORDER BY email_status ASC
    ";

    if ($dbConnection instanceof mysqli) {

        $result =
            $dbConnection->query(
                $emailStatusSql
            );

        if ($result) {

            while (
                $row =
                $result->fetch_assoc()
            ) {

                $status =
                    trim(
                        (string)(
                            $row['email_status']
                            ?? ''
                        )
                    );

                if ($status !== '') {
                    $emailStatuses[$status] = true;
                }
            }
        }

    } elseif (
        $dbConnection instanceof PDO
    ) {

        $stmt =
            $dbConnection->query(
                $emailStatusSql
            );

        if ($stmt) {

            while (
                $row =
                $stmt->fetch(
                    PDO::FETCH_ASSOC
                )
            ) {

                $status =
                    trim(
                        (string)(
                            $row['email_status']
                            ?? ''
                        )
                    );

                if ($status !== '') {
                    $emailStatuses[$status] = true;
                }
            }
        }
    }

} catch (Throwable $e) {

    $requestStatuses = [];
    $emailStatuses = [];
}


/* =========================================================
   SORT STATUS LISTS
========================================================= */

uksort(
    $requestStatuses,
    'strnatcasecmp'
);

uksort(
    $emailStatuses,
    'strnatcasecmp'
);


/* =========================================================
   BUILD SERVER-SIDE FILTER QUERY
========================================================= */

$where = [];

$params = [];

$types = '';


/*
 * NIN search.
 */

if ($searchNin !== '') {

    $where[] =
        "nin LIKE ?";

    $params[] =
        '%' .
        $searchNin .
        '%';

    $types .= 's';
}


/*
 * Email search.
 */

if ($searchEmail !== '') {

    $where[] =
        "user_email LIKE ?";

    $params[] =
        '%' .
        $searchEmail .
        '%';

    $types .= 's';
}


/*
 * Request status.
 */

if ($filterStatus !== '') {

    $where[] =
        "status = ?";

    $params[] =
        $filterStatus;

    $types .= 's';
}


/*
 * Email status.
 */

if ($filterEmailStatus !== '') {

    $where[] =
        "email_status = ?";

    $params[] =
        $filterEmailStatus;

    $types .= 's';
}


$whereSql = '';

if (!empty($where)) {

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


/* =========================================================
   TOTAL FILTERED REQUESTS
========================================================= */

$totalRequests = 0;


try {

    $countSql =
        "
        SELECT COUNT(*) AS total
        FROM validation_requests
        " .
        $whereSql;

    if (
        $dbConnection instanceof mysqli
    ) {

        $stmt =
            $dbConnection->prepare(
                $countSql
            );

        if ($stmt) {

            if ($types !== '') {

                $stmt->bind_param(
                    $types,
                    ...$params
                );
            }

            $stmt->execute();

            $result =
                $stmt->get_result();

            $row =
                $result->fetch_assoc();

            $totalRequests =
                (int)(
                    $row['total']
                    ?? 0
                );

            $stmt->close();
        }

    } elseif (
        $dbConnection instanceof PDO
    ) {

        $stmt =
            $dbConnection->prepare(
                $countSql
            );

        $stmt->execute(
            $params
        );

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

        $totalRequests =
            (int)(
                $row['total']
                ?? 0
            );
    }

} catch (Throwable $e) {

    $totalRequests = 0;
}


/* =========================================================
   CALCULATE PAGINATION
========================================================= */

$totalPages =
    max(
        1,
        (int)ceil(
            $totalRequests /
            $perPage
        )
    );


if ($page > $totalPages) {
    $page = $totalPages;
}


$offset =
    ($page - 1) *
    $perPage;


/* =========================================================
   LOAD CURRENT PAGE REQUESTS
========================================================= */

$requests = [];


try {

    $sql = "
        SELECT
            id,
            api_request_id,
            reference,
            user_email,
            tracking_id,
            user,
            nin,
            nin_firstname,
            nin_middlename,
            nin_surname,
            nin_dob,
            type,
            status,
            reply,
            price,
            created_at,
            email_status
        FROM validation_requests
        " .
        $whereSql .
        "
        ORDER BY id DESC
        LIMIT ? OFFSET ?
    ";


    if (
        $dbConnection instanceof mysqli
    ) {

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

        if (!$stmt) {

            throw new Exception(
                'Database prepare failed: ' .
                $dbConnection->error
            );
        }


        /*
         * LIMIT + OFFSET are integers.
         */

        $bindTypes =
            $types . 'ii';

        $bindParams =
            $params;

        $bindParams[] =
            $perPage;

        $bindParams[] =
            $offset;


        $stmt->bind_param(
            $bindTypes,
            ...$bindParams
        );

        $stmt->execute();

        $result =
            $stmt->get_result();

        while (
            $row =
            $result->fetch_assoc()
        ) {

            $requests[] =
                $row;
        }

        $stmt->close();

    } elseif (
        $dbConnection instanceof PDO
    ) {

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


        $pdoParams =
            $params;

        $pdoParams[] =
            $perPage;

        $pdoParams[] =
            $offset;


        $stmt->execute(
            $pdoParams
        );


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

} catch (Throwable $e) {

    $requests = [];
}


/* =========================================================
   PAGINATION URL BUILDER
========================================================= */

function paginationUrl(
    int $page
): string {

    $params = $_GET;

    $params['page'] =
        $page;

    return '?' .
        http_build_query(
            $params
        );
}


/* =========================================================
   FILTER URL
========================================================= */

function currentFilterUrl(
    int $page = 1
): string {

    $params = [];

    $nin =
        trim(
            (string)(
                $_GET['nin']
                ?? ''
            )
        );

    $email =
        trim(
            (string)(
                $_GET['email']
                ?? ''
            )
        );

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

    $emailStatus =
        trim(
            (string)(
                $_GET['email_status']
                ?? ''
            )
        );


    if ($nin !== '') {
        $params['nin'] = $nin;
    }

    if ($email !== '') {
        $params['email'] = $email;
    }

    if ($status !== '') {
        $params['status'] = $status;
    }

    if ($emailStatus !== '') {
        $params['email_status'] =
            $emailStatus;
    }

    if ($page > 1) {
        $params['page'] =
            $page;
    }

    if (empty($params)) {
        return '?';
    }

    return '?' .
        http_build_query(
            $params
        );
}


/* =========================================================
   DISPLAY RANGE
========================================================= */

if ($totalRequests > 0) {

    $displayFrom =
        $offset + 1;

    $displayTo =
        min(
            $offset + $perPage,
            $totalRequests
        );

} else {

    $displayFrom = 0;
    $displayTo = 0;
}


/* =========================================================
   PAGE BUTTON RANGE
========================================================= */

$pageStart =
    max(
        1,
        $page - 2
    );

$pageEnd =
    min(
        $totalPages,
        $page + 2
    );


/* =========================================================
   HTML
========================================================= */

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>NIN Customer Support - ASOVERIFY</title>


<style>

/* =========================================================
   GLOBAL
========================================================= */

* {
    box-sizing: border-box;
}


body {

    margin: 0;

    font-family:
        Arial,
        Helvetica,
        sans-serif;

    background: #f1f5f9;

    color: #172033;
}


/* =========================================================
   HEADER
========================================================= */

.header {

    background:
        linear-gradient(
            135deg,
            #063b8c,
            #0875d1
        );

    color: white;

    padding: 20px;
}


.header h1 {

    margin: 0;

    font-size: 23px;
}


.header p {

    margin: 7px 0 0;

    font-size: 13px;

    opacity: .9;
}


/* =========================================================
   CONTAINER
========================================================= */

.container {

    max-width: 1400px;

    margin: 20px auto;

    padding: 0 15px;
}


/* =========================================================
   ALERT
========================================================= */

.alert {

    display: none;

    padding: 15px 18px;

    border-radius: 10px;

    margin-bottom: 18px;

    font-size: 14px;

    font-weight: bold;

    line-height: 1.5;

    word-break: break-word;
}


.alert.success {

    display: block;

    background: #dcfce7;

    color: #166534;

    border:
        1px solid #86efac;
}


.alert.error {

    display: block;

    background: #fee2e2;

    color: #991b1b;

    border:
        1px solid #fca5a5;
}


/* =========================================================
   CARD
========================================================= */

.card {

    background: white;

    border-radius: 12px;

    overflow: hidden;

    box-shadow:
        0 3px 15px
        rgba(0,0,0,.08);
}


.card-header {

    padding: 18px;

    border-bottom:
        1px solid #e5e7eb;
}


.card-header h2 {

    margin: 0;

    font-size: 19px;
}


/* =========================================================
   FILTER PANEL
========================================================= */

.filter-panel {

    padding: 16px;

    background: #f8fafc;

    border-bottom:
        1px solid #e5e7eb;
}


.filter-title {

    display: flex;

    align-items: center;

    justify-content: space-between;

    gap: 10px;

    margin-bottom: 12px;
}


.filter-title strong {

    color: #1e293b;

    font-size: 14px;
}


.result-count {

    color: #0875d1;

    font-size: 12px;

    font-weight: bold;
}


.filter-grid {

    display: grid;

    grid-template-columns:
        minmax(180px, 1.5fr)
        minmax(180px, 1.5fr)
        minmax(150px, 1fr)
        minmax(150px, 1fr)
        auto;

    gap: 10px;

    align-items: center;
}


.filter-box input,
.filter-box select {

    width: 100%;

    height: 44px;

    border:
        1px solid #cbd5e1;

    border-radius: 8px;

    background: white;

    color: #172033;

    outline: none;

    padding: 0 12px;

    font-size: 13px;

    transition: .2s;
}


.filter-box input:focus,
.filter-box select:focus {

    border-color: #0875d1;

    box-shadow:
        0 0 0 3px
        rgba(8,117,209,.10);
}


.filter-box input::placeholder {

    color: #94a3b8;
}


.clear-filters {

    height: 44px;

    border: 0;

    border-radius: 8px;

    padding: 0 16px;

    background: #334155;

    color: white;

    font-size: 12px;

    font-weight: bold;

    cursor: pointer;

    transition: .2s;

    white-space: nowrap;
}


.clear-filters:hover {

    background: #1e293b;
}


/* =========================================================
   TABLE
========================================================= */

.table-wrapper {

    width: 100%;

    overflow-x: auto;
}


table {

    width: 100%;

    min-width: 1250px;

    border-collapse: collapse;
}


th {

    background: #f8fafc;

    color: #334155;

    text-align: left;

    padding: 13px;

    font-size: 12px;

    white-space: nowrap;

    border-bottom:
        1px solid #e5e7eb;
}


td {

    padding: 13px;

    font-size: 13px;

    vertical-align: middle;

    border-bottom:
        1px solid #eef0f3;
}


tr:hover td {

    background: #f8fbff;
}


/* =========================================================
   NIN
========================================================= */

.nin {

    font-family: monospace;

    font-size: 15px;

    font-weight: bold;

    color: #0759a5;

    letter-spacing: 1px;

    white-space: nowrap;
}


/* =========================================================
   STATUS
========================================================= */

.status {

    display: inline-block;

    padding: 5px 9px;

    border-radius: 20px;

    font-size: 11px;

    font-weight: bold;

    white-space: nowrap;
}


.status.pending {

    background: #fef3c7;

    color: #92400e;
}


.status.success,
.status.completed {

    background: #dcfce7;

    color: #166534;
}


.status.failed {

    background: #fee2e2;

    color: #991b1b;
}


.status.processing,
.status.in_progress {

    background: #dbeafe;

    color: #1e40af;
}


/* =========================================================
   EMAIL STATUS
========================================================= */

.email-status {

    display: inline-block;

    padding: 6px 10px;

    border-radius: 20px;

    font-size: 11px;

    font-weight: bold;

    white-space: nowrap;
}


.email-status.sent {

    background: #dcfce7;

    color: #166534;
}


.email-status.pending {

    background: #fef3c7;

    color: #92400e;
}


.email-status.failed {

    background: #fee2e2;

    color: #991b1b;
}


/* =========================================================
   BUTTON
========================================================= */

.send-btn {

    border: 0;

    color: white;

    padding: 9px 13px;

    border-radius: 7px;

    cursor: pointer;

    font-size: 12px;

    font-weight: bold;

    white-space: nowrap;

    transition: .2s;
}


.send-btn:disabled {

    opacity: .65;

    cursor: not-allowed;
}


.send-btn.send {

    background: #0875d1;
}


.send-btn.send:hover {

    background: #075aa5;
}


.send-btn.resend {

    background: #7c3aed;
}


.send-btn.resend:hover {

    background: #6d28d9;
}


.send-btn.failed {

    background: #dc2626;
}


.send-btn.failed:hover {

    background: #b91c1c;
}


/* =========================================================
   EMPTY
========================================================= */

.empty {

    padding: 55px 20px;

    text-align: center;

    color: #64748b;
}


.empty h3 {

    margin-bottom: 8px;

    color: #334155;
}


.empty p {

    font-size: 13px;
}


/* =========================================================
   PAGINATION
========================================================= */

.pagination-wrapper {

    display: flex;

    align-items: center;

    justify-content: space-between;

    gap: 15px;

    padding: 16px;

    border-top:
        1px solid #e5e7eb;

    background: #fff;

    flex-wrap: wrap;
}


.pagination-info {

    color: #64748b;

    font-size: 13px;

    font-weight: 600;
}


.pagination-info strong {

    color: #0875d1;
}


.pagination {

    display: flex;

    align-items: center;

    justify-content: center;

    gap: 5px;

    flex-wrap: wrap;
}


.page-btn {

    min-width: 36px;

    height: 36px;

    display: inline-flex;

    align-items: center;

    justify-content: center;

    padding: 0 10px;

    border:
        1px solid #dbe3ec;

    border-radius: 7px;

    background: #fff;

    color: #334155;

    text-decoration: none;

    font-size: 12px;

    font-weight: bold;

    transition: .2s;
}


.page-btn:hover {

    background: #eff6ff;

    border-color: #0875d1;

    color: #075aa5;
}


.page-btn.active {

    background:
        linear-gradient(
            135deg,
            #063b8c,
            #0875d1
        );

    border-color: #0875d1;

    color: white;

    box-shadow:
        0 3px 8px
        rgba(8,117,209,.25);
}


.page-btn.disabled {

    opacity: .45;

    pointer-events: none;

    cursor: default;
}


.page-arrow {

    padding: 0 13px;
}


.page-dots {

    color: #94a3b8;

    font-weight: bold;

    padding: 0 3px;
}


/* =========================================================
   LOADING SPINNER
========================================================= */

.loading-spinner {

    display: inline-block;

    width: 12px;

    height: 12px;

    border:
        2px solid
        rgba(255,255,255,.5);

    border-top-color:
        white;

    border-radius: 50%;

    animation:
        spin .7s linear infinite;

    vertical-align: middle;

    margin-right: 5px;
}


@keyframes spin {

    to {
        transform: rotate(360deg);
    }
}


/* =========================================================
   MOBILE
========================================================= */

@media(max-width:900px) {

    .filter-grid {

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


    .clear-filters {

        width: 100%;
    }


    .pagination-wrapper {

        align-items: flex-start;

        flex-direction: column;
    }


    .pagination {

        width: 100%;

        justify-content: flex-start;
    }
}


@media(max-width:600px) {

    .header {

        padding: 17px;
    }


    .header h1 {

        font-size: 19px;
    }


    .container {

        padding: 0 10px;
    }


    .card-header h2 {

        font-size: 17px;
    }


    .filter-grid {

        grid-template-columns: 1fr;
    }


    .filter-title {

        align-items: flex-start;

        flex-direction: column;

        gap: 4px;
    }


    .filter-panel {

        padding: 12px;
    }


    .pagination {

        gap: 4px;
    }


    .page-btn {

        min-width: 33px;

        height: 33px;

        padding: 0 8px;

        font-size: 11px;
    }


    .page-arrow {

        padding: 0 9px;
    }

}

</style>

</head>


<body>


<div class="header">

    <h1>
        📧 NIN Customer Support
    </h1>

    <p>
        Send NIN validation assistance requests
        to NIMC Customer Care
    </p>

</div>


<div class="container">


<!-- =====================================================
     AJAX ALERT
====================================================== -->

<div
    id="ajaxAlert"
    class="alert"
></div>


<!-- =====================================================
     REQUEST CARD
====================================================== -->

<div class="card">


<div class="card-header">

    <h2>

        Validation Requests
        (<span id="totalRequestCount">
            <?php echo $totalRequests; ?>
        </span>)

    </h2>

</div>


<!-- =====================================================
     SEARCH / FILTER
====================================================== -->

<div class="filter-panel">

    <div class="filter-title">

        <strong>
            🔎 Search & Filter Requests
        </strong>

        <span
            class="result-count"
            id="filterResultCount"
        >
            Showing
            <?php echo $displayFrom; ?>
            -
            <?php echo $displayTo; ?>
            of
            <?php echo $totalRequests; ?>
        </span>

    </div>


    <form
        method="GET"
        action=""
        id="filterForm"
    >

        <div class="filter-grid">


            <!-- NIN -->

            <div class="filter-box">

                <input
                    type="text"
                    name="nin"
                    id="searchNin"
                    value="<?php echo e($searchNin); ?>"
                    placeholder="Search by NIN..."
                    autocomplete="off"
                >

            </div>


            <!-- EMAIL -->

            <div class="filter-box">

                <input
                    type="text"
                    name="email"
                    id="searchEmail"
                    value="<?php echo e($searchEmail); ?>"
                    placeholder="Search by email..."
                    autocomplete="off"
                >

            </div>


            <!-- REQUEST STATUS -->

            <div class="filter-box">

                <select
                    name="status"
                    id="filterStatus"
                >

                    <option value="">
                        All Request Status
                    </option>

                    <?php foreach (
                        $requestStatuses
                        as $status => $_
                    ): ?>

                        <option
                            value="<?php echo e($status); ?>"
                            <?php
                            echo (
                                strcasecmp(
                                    $status,
                                    $filterStatus
                                ) === 0
                            )
                            ? 'selected'
                            : '';
                            ?>
                        >
                            <?php echo e($status); ?>
                        </option>

                    <?php endforeach; ?>

                </select>

            </div>


            <!-- EMAIL STATUS -->

            <div class="filter-box">

                <select
                    name="email_status"
                    id="filterEmailStatus"
                >

                    <option value="">
                        All Email Status
                    </option>

                    <?php foreach (
                        $emailStatuses
                        as $emailStatus => $_
                    ): ?>

                        <option
                            value="<?php
                                echo e($emailStatus);
                            ?>"
                            <?php
                            echo (
                                strcasecmp(
                                    $emailStatus,
                                    $filterEmailStatus
                                ) === 0
                            )
                            ? 'selected'
                            : '';
                            ?>
                        >
                            <?php
                            echo e(
                                $emailStatus
                            );
                            ?>
                        </option>

                    <?php endforeach; ?>

                </select>

            </div>


            <!-- CLEAR -->

            <button
                type="button"
                id="clearFilters"
                class="clear-filters"
            >
                ✕ Clear Filters
            </button>


        </div>

    </form>

</div>


<?php if (
    empty($requests) &&
    $totalRequests === 0
): ?>


<div class="empty">

    <h3>
        📭 No Requests Found
    </h3>

    <p>

        <?php if (
            $searchNin !== '' ||
            $searchEmail !== '' ||
            $filterStatus !== '' ||
            $filterEmailStatus !== ''
        ): ?>

            No validation requests match
            your current search/filter.

        <?php else: ?>

            There are currently no records
            in validation_requests.

        <?php endif; ?>

    </p>

</div>


<?php else: ?>


<div class="table-wrapper">


<table id="requestsTable">


<thead>

<tr>

    <th>ID</th>

    <th>NIN</th>

    <th>Customer</th>

    <th>Email</th>

    <th>Reference</th>

    <th>Type</th>

    <th>Request Status</th>

    <th>Email Status</th>

    <th>Date</th>

    <th>Action</th>

</tr>

</thead>


<tbody>


<?php foreach (
    $requests
    as $row
): ?>


<?php

$firstName =
    trim(
        (string)(
            $row['nin_firstname']
            ?? ''
        )
    );

$middleName =
    trim(
        (string)(
            $row['nin_middlename']
            ?? ''
        )
    );

$surname =
    trim(
        (string)(
            $row['nin_surname']
            ?? ''
        )
    );

$customerName =
    trim(
        $firstName .
        ' ' .
        $middleName .
        ' ' .
        $surname
    );

if ($customerName === '') {
    $customerName = 'Customer';
}


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


$email =
    trim(
        (string)(
            $row['user_email']
            ?? ''
        )
    );


$requestStatus =
    trim(
        (string)(
            $row['status']
            ?? 'Pending'
        )
    );

if ($requestStatus === '') {
    $requestStatus = 'Pending';
}


$requestStatusClass =
    strtolower(
        str_replace(
            ' ',
            '_',
            $requestStatus
        )
    );


$emailStatus =
    trim(
        (string)(
            $row['email_status']
            ?? 'Pending'
        )
    );

if ($emailStatus === '') {
    $emailStatus = 'Pending';
}


$emailStatusClass =
    strtolower(
        str_replace(
            ' ',
            '_',
            $emailStatus
        )
    );

?>


<tr
    class="request-row"
    id="request-row-<?php
        echo (int)$row['id'];
    ?>"
>


<td>

<strong>
#<?php echo (int)$row['id']; ?>
</strong>

</td>


<td>

<span class="nin">
<?php echo e($nin); ?>
</span>

</td>


<td>
<?php echo e($customerName); ?>
</td>


<td>
<?php echo e($email); ?>
</td>


<td>
<?php echo e(
    (string)(
        $row['reference']
        ?? ''
    )
); ?>
</td>


<td>
<?php echo e(
    (string)(
        $row['type']
        ?? ''
    )
); ?>
</td>


<td>

<span class="status <?php
    echo e($requestStatusClass);
?>">

<?php echo e(
    ucfirst(
        str_replace(
            '_',
            ' ',
            $requestStatus
        )
    )
); ?>

</span>

</td>


<td>

<span
    class="email-status <?php
        echo e($emailStatusClass);
    ?>"
    data-email-status="<?php
        echo (int)$row['id'];
    ?>"
>

<?php echo e(
    ucfirst($emailStatus)
); ?>

</span>

</td>


<td>

<?php echo e(
    (string)(
        $row['created_at']
        ?? ''
    )
); ?>

</td>


<td>


<?php if ($nin === ''): ?>


<span style="
    color:#94a3b8;
    font-size:12px;
">

No NIN

</span>


<?php elseif (
    strtolower($emailStatus)
    === 'sent'
): ?>


<button
    type="button"
    class="send-btn resend ajax-email-btn"
    data-action="resend_email"
    data-request-id="<?php
        echo (int)$row['id'];
    ?>"
>

🔄 Resend Email

</button>


<?php elseif (
    strtolower($emailStatus)
    === 'failed'
): ?>


<button
    type="button"
    class="send-btn failed ajax-email-btn"
    data-action="send_email"
    data-request-id="<?php
        echo (int)$row['id'];
    ?>"
>

↻ Try Again

</button>


<?php else: ?>


<button
    type="button"
    class="send-btn send ajax-email-btn"
    data-action="send_email"
    data-request-id="<?php
        echo (int)$row['id'];
    ?>"
>

📧 Send Email

</button>


<?php endif; ?>


</td>


</tr>


<?php endforeach; ?>


</tbody>

</table>

</div>


<!-- =====================================================
     PAGINATION
====================================================== -->

<div class="pagination-wrapper">


<div class="pagination-info">

    Showing

    <strong>
        <?php echo $displayFrom; ?>
    </strong>

    -

    <strong>
        <?php echo $displayTo; ?>
    </strong>

    of

    <strong>
        <?php echo $totalRequests; ?>
    </strong>

    requests

</div>


<?php if (
    $totalPages > 1
): ?>


<div class="pagination">


<!-- FIRST -->

<a
    href="<?php
        echo e(
            currentFilterUrl(1)
        );
    ?>"
    class="page-btn page-arrow <?php
        echo $page <= 1
            ? 'disabled'
            : '';
    ?>"
>
    « First
</a>


<!-- PREVIOUS -->

<a
    href="<?php
        echo e(
            currentFilterUrl(
                max(
                    1,
                    $page - 1
                )
            )
        );
    ?>"
    class="page-btn page-arrow <?php
        echo $page <= 1
            ? 'disabled'
            : '';
    ?>"
>
    ‹ Prev
</a>


<?php if (
    $pageStart > 1
): ?>


<a
    href="<?php
        echo e(
            currentFilterUrl(1)
        );
    ?>"
    class="page-btn"
>
    1
</a>


<?php if (
    $pageStart > 2
): ?>

<span class="page-dots">
    ...
</span>

<?php endif; ?>


<?php endif; ?>


<?php for (
    $p = $pageStart;
    $p <= $pageEnd;
    $p++
): ?>


<a
    href="<?php
        echo e(
            currentFilterUrl($p)
        );
    ?>"
    class="page-btn <?php
        echo $p === $page
            ? 'active'
            : '';
    ?>"
>
    <?php echo $p; ?>
</a>


<?php endfor; ?>


<?php if (
    $pageEnd < $totalPages
): ?>


<?php if (
    $pageEnd < $totalPages - 1
): ?>

<span class="page-dots">
    ...
</span>

<?php endif; ?>


<a
    href="<?php
        echo e(
            currentFilterUrl(
                $totalPages
            )
        );
    ?>"
    class="page-btn"
>
    <?php echo $totalPages; ?>
</a>


<?php endif; ?>


<!-- NEXT -->

<a
    href="<?php
        echo e(
            currentFilterUrl(
                min(
                    $totalPages,
                    $page + 1
                )
            )
        );
    ?>"
    class="page-btn page-arrow <?php
        echo $page >= $totalPages
            ? 'disabled'
            : '';
    ?>"
>
    Next ›
</a>


<!-- LAST -->

<a
    href="<?php
        echo e(
            currentFilterUrl(
                $totalPages
            )
        );
    ?>"
    class="page-btn page-arrow <?php
        echo $page >= $totalPages
            ? 'disabled'
            : '';
    ?>"
>
    Last »
</a>


</div>


<?php endif; ?>


</div>


<?php endif; ?>


</div>


</div>


<script>

/* =========================================================
   FILTER SYSTEM
   SERVER-SIDE
========================================================= */

(function () {

    'use strict';


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


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


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


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


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


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


    /*
     * Automatically search after typing.
     *
     * Small delay prevents a request
     * on every single keystroke.
     */

    let searchTimer = null;


    function submitFilters() {

        if (!form) {
            return;
        }

        /*
         * Always return to page 1
         * when a new filter is applied.
         */

        const pageInput =
            form.querySelector(
                'input[name="page"]'
            );

        if (pageInput) {

            pageInput.remove();
        }


        form.submit();
    }


    function delayedSubmit() {

        clearTimeout(
            searchTimer
        );

        searchTimer =
            setTimeout(
                function () {

                    submitFilters();

                },
                500
            );
    }


    /*
     * Live NIN search.
     */

    if (searchNin) {

        searchNin.addEventListener(
            'input',
            delayedSubmit
        );


        searchNin.addEventListener(
            'keydown',
            function (event) {

                if (
                    event.key ===
                    'Enter'
                ) {

                    event.preventDefault();

                    clearTimeout(
                        searchTimer
                    );

                    submitFilters();
                }
            }
        );
    }


    /*
     * Live email search.
     */

    if (searchEmail) {

        searchEmail.addEventListener(
            'input',
            delayedSubmit
        );


        searchEmail.addEventListener(
            'keydown',
            function (event) {

                if (
                    event.key ===
                    'Enter'
                ) {

                    event.preventDefault();

                    clearTimeout(
                        searchTimer
                    );

                    submitFilters();
                }
            }
        );
    }


    /*
     * Request status.
     */

    if (filterStatus) {

        filterStatus.addEventListener(
            'change',
            function () {

                submitFilters();

            }
        );
    }


    /*
     * Email status.
     */

    if (filterEmailStatus) {

        filterEmailStatus.addEventListener(
            'change',
            function () {

                submitFilters();

            }
        );
    }


    /*
     * Clear filters.
     */

    if (clearFilters) {

        clearFilters.addEventListener(
            'click',
            function () {

                window.location.href =
                    window.location.pathname;

            }
        );
    }


})();


/* =========================================================
   AJAX SEND / RESEND
========================================================= */

(function () {

    'use strict';


    /*
     * SHOW MESSAGE
     */

    function showAlert(
        message,
        type
    ) {

        const alertBox =
            document.getElementById(
                'ajaxAlert'
            );


        if (!alertBox) {
            return;
        }


        alertBox.className =
            'alert ' +
            (
                type === 'success'
                ? 'success'
                : 'error'
            );


        alertBox.textContent =
            message;


        alertBox.style.display =
            'block';


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


    /*
     * MARK SENT
     */

    function markAsSent(
        requestId
    ) {

        const status =
            document.querySelector(
                '[data-email-status="' +
                requestId +
                '"]'
            );


        if (status) {

            status.textContent =
                'Sent';

            status.className =
                'email-status sent';
        }


        const button =
            document.querySelector(
                '.ajax-email-btn[data-request-id="' +
                requestId +
                '"]'
            );


        if (button) {

            button.disabled =
                false;

            button.dataset.action =
                'resend_email';

            button.className =
                'send-btn resend ajax-email-btn';

            button.textContent =
                '🔄 Resend Email';
        }
    }


    /*
     * MARK FAILED
     */

    function markAsFailed(
        requestId
    ) {

        const status =
            document.querySelector(
                '[data-email-status="' +
                requestId +
                '"]'
            );


        if (status) {

            status.textContent =
                'Failed';

            status.className =
                'email-status failed';
        }


        const button =
            document.querySelector(
                '.ajax-email-btn[data-request-id="' +
                requestId +
                '"]'
            );


        if (button) {

            button.disabled =
                false;

            button.dataset.action =
                'send_email';

            button.className =
                'send-btn failed ajax-email-btn';

            button.textContent =
                '↻ Try Again';
        }
    }


    /*
     * SEND EMAIL
     */

    async function sendEmail(
        button
    ) {

        const requestId =
            button.dataset.requestId;


        const action =
            button.dataset.action;


        if (
            !requestId ||
            !action
        ) {

            showAlert(
                'Invalid request information.',
                'error'
            );

            return;
        }


        /*
         * Resend confirmation.
         */

        if (
            action ===
            'resend_email'
        ) {

            const confirmed =
                window.confirm(
                    'This request has already been sent to NIMC. Do you want to resend it?'
                );


            if (!confirmed) {
                return;
            }
        }


        /*
         * Prevent double click.
         */

        if (button.disabled) {
            return;
        }


        button.disabled =
            true;


        const oldText =
            button.innerHTML;


        button.innerHTML =
            '<span class="loading-spinner"></span>' +
            (
                action ===
                'resend_email'
                ? 'Resending...'
                : 'Sending...'
            );


        /*
         * POST.
         */

        const formData =
            new FormData();


        formData.append(
            'ajax',
            '1'
        );


        formData.append(
            'action',
            action
        );


        formData.append(
            'request_id',
            requestId
        );


        try {

            const response =
                await fetch(
                    window.location.pathname,
                    {
                        method: 'POST',

                        body: formData,

                        credentials:
                            'same-origin',

                        cache: 'no-store',

                        headers: {

                            'X-Requested-With':
                                'XMLHttpRequest',

                            'Accept':
                                'application/json'
                        }
                    }
                );


            const responseText =
                await response.text();


            let data;


            try {

                data =
                    JSON.parse(
                        responseText
                    );

            } catch (jsonError) {

                button.disabled =
                    false;


                button.innerHTML =
                    oldText;


                let serverMessage =
                    responseText.trim();


                if (
                    serverMessage.length >
                    1000
                ) {

                    serverMessage =
                        serverMessage.substring(
                            0,
                            1000
                        ) +
                        '...';
                }


                if (
                    serverMessage === ''
                ) {

                    serverMessage =
                        'The server returned an empty response.';
                }


                showAlert(
                    'Server did not return valid JSON. HTTP ' +
                    response.status +
                    ': ' +
                    serverMessage,
                    'error'
                );


                console.error(
                    'Invalid AJAX JSON:',
                    responseText
                );


                return;
            }


            /*
             * SUCCESS
             */

            if (
                data.success === true
            ) {

                markAsSent(
                    requestId
                );


                showAlert(
                    data.message ||
                    'Email sent successfully.',
                    'success'
                );


                return;
            }


            /*
             * FAILED
             */

            markAsFailed(
                requestId
            );


            showAlert(
                data.message ||
                'Email sending failed.',
                'error'
            );


        } catch (error) {

            button.disabled =
                false;


            button.innerHTML =
                oldText;


            showAlert(
                'AJAX connection error: ' +
                (
                    error.message ||
                    'Unable to communicate with the server.'
                ),
                'error'
            );


            console.error(
                'AJAX error:',
                error
            );
        }

    }


    /*
     * CLICK HANDLER
     */

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

            const button =
                event.target.closest(
                    '.ajax-email-btn'
                );


            if (!button) {
                return;
            }


            event.preventDefault();


            sendEmail(
                button
            );
        }
    );


})();

</script>


</body>

</html>