<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| ASOVERIFY VALIDATION ADMIN
|--------------------------------------------------------------------------
| Includes:
| - Admin authentication
| - NIN verification
| - UnifyXpress / DataVerify switching
| - Validation request management
| - 4-day countdown
| - Refund system
| - Search / pagination
| - DIRECT CPANEL MAILBOX SEARCH
|
| MAILBOX:
|   noreply@asoverify.com.ng
|
| IMAP:
|   mail.asoverify.com.ng:993 SSL
|
| The View Email button searches the ACTUAL cPanel mailbox
| using the NIN on that validation request.
|--------------------------------------------------------------------------
*/


/* ============================================================
   SESSION / ERROR HANDLING
============================================================ */

session_start();

error_reporting(E_ALL);

/*
 * Do not display PHP errors in AJAX responses.
 * This prevents:
 *
 * Unexpected token '<'
 *
 * because PHP warnings are HTML.
 */
ini_set('display_errors', '0');
ini_set('display_startup_errors', '0');


if (!isset($_SESSION['admin'])) {

    header("Location: admin_login.php");
    exit();

}


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

mysqli_report(
    MYSQLI_REPORT_ERROR |
    MYSQLI_REPORT_STRICT
);


$conn = new mysqli(
    "localhost",
    "nassrrkx_Asovtu",
    "nassrrkx_Asovtu",
    "nassrrkx_Asovtu"
);


if ($conn->connect_error) {

    die("DB Error");

}


$conn->set_charset("utf8mb4");


/* ============================================================
   CPANEL MAILBOX SETTINGS
============================================================ */

/*
 * IMPORTANT:
 *
 * Enter the password of:
 *
 * noreply@asoverify.com.ng
 *
 * The password is NOT the cPanel login password unless
 * your cPanel setup uses the same password.
 */

const MAILBOX_USERNAME =
    'noreply@asoverify.com.ng';


const MAILBOX_PASSWORD = 'Sabirata@273'; // Legacy placeholder; configure ASOVERIFY_IMAP_PASSWORD in the server environment.


const MAILBOX_SERVER =
    'mail.asoverify.com.ng';


const MAILBOX_PORT =
    993;


/*
 * Mailbox folder.
 */
const MAILBOX_FOLDER =
    'INBOX';


/*
 * Maximum emails to display.
 */
const MAILBOX_MAX_RESULTS =
    100;


/* ============================================================
   HELPERS
============================================================ */

function h($v): string
{
    return htmlspecialchars(
        (string)($v ?? ''),
        ENT_QUOTES | ENT_SUBSTITUTE,
        'UTF-8'
    );
}


function naira($v): string
{
    return number_format(
        (float)($v ?? 0),
        2
    );
}


function isAjaxRequest(): bool
{
    return isset(
        $_SERVER['HTTP_X_REQUESTED_WITH']
    )
    &&
    strtolower(
        (string)$_SERVER['HTTP_X_REQUESTED_WITH']
    ) === 'xmlhttprequest';
}


function logDebug(string $msg): void
{
    $dir =
        __DIR__ .
        '/uploads/nin_photos';


    if (
        !is_dir($dir)
    ) {

        @mkdir(
            $dir,
            0775,
            true
        );

    }


    @file_put_contents(
        $dir . '/_debug.log',
        '[' .
        date('Y-m-d H:i:s') .
        '] ' .
        $msg .
        PHP_EOL,
        FILE_APPEND
    );
}




/* ============================================================
   SEND NIN VALIDATION ASSISTANCE EMAIL TO NIMC
============================================================ */

/**
 * SMTP SSL sender. Set ASOVERIFY_MAIL_PASSWORD in the hosting
 * environment. The email contains only the NIN and assistance request.
 */
function nimcSmtpReadResponse($socket): string
{
    $response = '';
    while (($line = fgets($socket, 515)) !== false) {
        $response .= $line;
        if (strlen($line) < 4 || $line[3] !== '-') {
            break;
        }
    }
    return $response;
}

function nimcSmtpExpect($socket, array $allowedCodes): string
{
    $response = nimcSmtpReadResponse($socket);
    $code = (int)substr(trim($response), 0, 3);
    if (!in_array($code, $allowedCodes, true)) {
        throw new RuntimeException('SMTP rejected a command (code ' . $code . ').');
    }
    return $response;
}

function nimcSmtpCommand($socket, string $command, array $allowedCodes): string
{
    if (fwrite($socket, $command . "\r\n") === false) {
        throw new RuntimeException('SMTP command could not be written.');
    }
    return nimcSmtpExpect($socket, $allowedCodes);
}

function sendNimcValidationAssistanceEmail(string $nin): void
{
    if (!preg_match('/^[0-9]{11}$/', $nin)) {
        throw new InvalidArgumentException('Invalid NIN.');
    }

    $host = getenv('ASOVERIFY_MAIL_HOST') ?: MAILBOX_SERVER;
    $port = (int)(getenv('ASOVERIFY_MAIL_PORT') ?: '465');
    $username = getenv('ASOVERIFY_MAIL_USERNAME') ?: MAILBOX_USERNAME;
    $password = getenv('ASOVERIFY_MAIL_PASSWORD') ?: 'Sabirata@273';
    $fromName = getenv('ASOVERIFY_MAIL_FROM_NAME') ?: 'ASOVERIFY';
    $recipient = 'nimccustomercare@nimc.gov.ng';

    if ($password === '') {
        throw new RuntimeException('SMTP password is not configured on the server.');
    }

    $socket = @stream_socket_client(
        'ssl://' . $host . ':' . $port,
        $errno,
        $errstr,
        20,
        STREAM_CLIENT_CONNECT
    );
    if (!$socket) {
        throw new RuntimeException('Could not connect to the SMTP server.');
    }

    stream_set_timeout($socket, 20);

    try {
        nimcSmtpExpect($socket, [220]);
        nimcSmtpCommand($socket, 'EHLO ' . (gethostname() ?: 'asoverify.com.ng'), [250]);
        nimcSmtpCommand($socket, 'AUTH LOGIN', [334]);
        nimcSmtpCommand($socket, base64_encode($username), [334]);
        nimcSmtpCommand($socket, base64_encode($password), [235]);
        nimcSmtpCommand($socket, 'MAIL FROM:<' . $username . '>', [250]);
        nimcSmtpCommand($socket, 'RCPT TO:<' . $recipient . '>', [250, 251]);
        nimcSmtpCommand($socket, 'DATA', [354]);

        $subject = 'Request for Assistance Validating NIN';
        $body = "Dear NIMC Customer Care,\r\n\r\n"
            . "Please help me to validate this NIN because I am unable to use it for services.\r\n\r\n"
            . "NIN: " . $nin . "\r\n\r\n"
            . "Please check the NIN and kindly assist with the validation issue.\r\n\r\n"
            . "Thank you.\r\n\r\n"
            . "ASOVERIFY";

        $message = 'Date: ' . date(DATE_RFC2822) . "\r\n"
            . 'From: =?UTF-8?B?' . base64_encode($fromName) . '?= <' . $username . ">\r\n"
            . 'To: ' . $recipient . "\r\n"
            . 'Subject: =?UTF-8?B?' . base64_encode($subject) . "?=\r\n"
            . "MIME-Version: 1.0\r\n"
            . "Content-Type: text/plain; charset=UTF-8\r\n"
            . "Content-Transfer-Encoding: 8bit\r\n\r\n"
            . $body . "\r\n";

        $message = preg_replace('/(?m)^\./', '..', $message) ?? $message;
        if (fwrite($socket, $message . "\r\n.\r\n") === false) {
            throw new RuntimeException('Could not transmit the email.');
        }
        nimcSmtpExpect($socket, [250]);
        nimcSmtpCommand($socket, 'QUIT', [221]);
    } finally {
        if (is_resource($socket)) {
            fclose($socket);
        }
    }
}


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

function sendCleanJson(
    array $data,
    int $statusCode = 200
): void {

    /*
     * Remove anything accidentally printed before JSON.
     */

    while (
        ob_get_level() > 0
    ) {

        @ob_end_clean();

    }


    http_response_code(
        $statusCode
    );


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


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


    echo json_encode(
        $data,
        JSON_UNESCAPED_UNICODE |
        JSON_UNESCAPED_SLASHES
    );


    exit;
}


/* ============================================================
   IMAP AVAILABILITY
============================================================ */

function mailboxImapAvailable(): bool
{
    return function_exists(
        'imap_open'
    );
}


/* ============================================================
   MIME HEADER DECODER
============================================================ */

function decodeMimeHeaderValue(
    string $value
): string {

    if (
        $value === ''
    ) {

        return '';

    }


    if (
        function_exists('imap_mime_header_decode')
    ) {

        $parts =
            @imap_mime_header_decode(
                $value
            );


        if (
            is_array($parts)
        ) {

            $output = '';


            foreach (
                $parts as $part
            ) {

                $text =
                    (string)(
                        $part->text
                        ?? ''
                    );


                $output .=
                    $text;
            }


            if (
                $output !== ''
            ) {

                return $output;
            }
        }
    }


    return $value;
}


/* ============================================================
   MIME BODY DECODER
============================================================ */

function decodeMimeBody(
    string $body,
    int $encoding
): string {

    switch (
        $encoding
    ) {

        /*
         * 3 = BASE64
         */
        case 3:

            $decoded =
                base64_decode(
                    $body,
                    true
                );


            return
                is_string($decoded)
                    ? $decoded
                    : $body;


        /*
         * 4 = QUOTED PRINTABLE
         */
        case 4:

            return
                quoted_printable_decode(
                    $body
                );


        default:

            return $body;
    }
}


/* ============================================================
   CLEAN EMAIL BODY
============================================================ */

function cleanEmailBody(
    string $body,
    bool $isHtml = false
): string {

    if (
        $body === ''
    ) {

        return '';

    }


    /*
     * Convert HTML email to readable text.
     *
     * We deliberately do NOT inject raw email HTML
     * into the admin page because email HTML can contain
     * scripts, tracking images, forms, etc.
     */

    if ($isHtml) {

        $body =
            preg_replace(
                '/<br\s*\/?>/i',
                "\n",
                $body
            );


        $body =
            preg_replace(
                '/<\/p>/i',
                "\n\n",
                $body
            );


        $body =
            preg_replace(
                '/<\/div>/i',
                "\n",
                $body
            );


        $body =
            strip_tags(
                $body
            );
    }


    /*
     * Decode common HTML entities.
     */

    $body =
        html_entity_decode(
            $body,
            ENT_QUOTES |
            ENT_HTML5,
            'UTF-8'
        );


    /*
     * Normalize line endings.
     */

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


    /*
     * Remove excessive blank lines.
     */

    $body =
        preg_replace(
            "/\n{4,}/",
            "\n\n\n",
            $body
        );


    return trim(
        (string)$body
    );
}


/* ============================================================
   GET MIME PART BODY
============================================================ */

function getMimePartBody(
    $imap,
    int $messageNumber,
    $structure,
    string $partNumber = ''
): array {

    $result = [

        'plain' => '',
        'html' => ''

    ];


    /*
     * Multipart email.
     */

    if (
        isset(
            $structure->parts
        )
        &&
        is_array(
            $structure->parts
        )
    ) {

        foreach (
            $structure->parts
            as $index => $part
        ) {

            $currentPart =
                $partNumber === ''
                    ? (string)($index + 1)
                    : $partNumber .
                      '.' .
                      ($index + 1);


            $child =
                getMimePartBody(
                    $imap,
                    $messageNumber,
                    $part,
                    $currentPart
                );


            if (
                $result['plain'] === '' &&
                $child['plain'] !== ''
            ) {

                $result['plain'] =
                    $child['plain'];
            }


            if (
                $result['html'] === '' &&
                $child['html'] !== ''
            ) {

                $result['html'] =
                    $child['html'];
            }
        }


        return $result;
    }


    /*
     * Single-part email.
     */

    $section =
        $partNumber === ''
            ? '1'
            : $partNumber;


    $body =
        @imap_fetchbody(
            $imap,
            $messageNumber,
            $section
        );


    if (
        !is_string($body)
    ) {

        $body = '';

    }


    $encoding =
        (int)(
            $structure->encoding
            ?? 0
        );


    $body =
        decodeMimeBody(
            $body,
            $encoding
        );


    $type =
        (int)(
            $structure->type
            ?? 0
        );


    /*
     * 0 = TEXT
     */

    if (
        $type === 0
    ) {

        $subtype =
            strtoupper(
                (string)(
                    $structure->subtype
                    ?? ''
                )
            );


        if (
            $subtype === 'HTML'
        ) {

            $result['html'] =
                $body;

        } else {

            $result['plain'] =
                $body;
        }
    }


    return $result;
}


/* ============================================================
   FETCH EMAIL BODY
============================================================ */

function fetchMailboxEmailBody(
    $imap,
    int $messageNumber
): string {

    try {

        $structure =
            @imap_fetchstructure(
                $imap,
                $messageNumber
            );


        if (
            !$structure
        ) {

            $body =
                @imap_body(
                    $imap,
                    $messageNumber
                );


            return
                is_string($body)
                    ? cleanEmailBody(
                        $body
                    )
                    : '';

        }


        $parts =
            getMimePartBody(
                $imap,
                $messageNumber,
                $structure
            );


        /*
         * Prefer plain text.
         */

        if (
            trim(
                $parts['plain']
            ) !== ''
        ) {

            return cleanEmailBody(
                $parts['plain'],
                false
            );

        }


        /*
         * Otherwise use HTML converted to text.
         */

        if (
            trim(
                $parts['html']
            ) !== ''
        ) {

            return cleanEmailBody(
                $parts['html'],
                true
            );

        }


        return '';

    } catch (Throwable $e) {

        logDebug(
            'MAIL BODY ERROR: ' .
            $e->getMessage()
        );


        return '';
    }
}


/* ============================================================
   CONNECT TO CPANEL MAILBOX
============================================================ */

function connectToMailbox()
{
    $mailboxPassword = getenv('ASOVERIFY_IMAP_PASSWORD') ?: MAILBOX_PASSWORD;

    if (
        !mailboxImapAvailable()
    ) {

        throw new RuntimeException(
            'PHP IMAP extension is not enabled.'
        );

    }


    if (
        $mailboxPassword === ''
    ) {

        throw new RuntimeException(
            'Mailbox password has not been configured.'
        );

    }


    $mailboxPath =
        '{' .
        MAILBOX_SERVER .
        ':' .
        MAILBOX_PORT .
        '/imap/ssl/novalidate-cert}' .
        MAILBOX_FOLDER;


    $imap =
        @imap_open(
            $mailboxPath,
            MAILBOX_USERNAME,
            $mailboxPassword,
            OP_READONLY,
            1
        );


    if (
        $imap === false
    ) {

        $errors =
            @imap_errors();


        $errorText =
            is_array($errors)
                ? implode(
                    ' | ',
                    $errors
                )
                : 'Unknown IMAP error';


        throw new RuntimeException(
            $errorText
        );
    }


    return $imap;
}


/* ============================================================
   GET EMAIL HEADER
============================================================ */

function getMailboxHeaderValue(
    object $header,
    string $property
): string {

    return
        isset(
            $header->{$property}
        )
            ? decodeMimeHeaderValue(
                (string)$header->{$property}
            )
            : '';
}


/* ============================================================
   SEARCH ACTUAL CPANEL MAILBOX USING NIN
============================================================ */

function getMailboxEmailsByNin(
    string $nin
): array {

    if (
        !preg_match(
            '/^[0-9]{11}$/',
            $nin
        )
    ) {

        return [

            'success' =>
                false,

            'records' =>
                [],

            'message' =>
                'Invalid NIN.'

        ];
    }


    $imap = null;


    try {

        /*
         * Connect to actual cPanel mailbox.
         */

        $imap =
            connectToMailbox();


        /*
         * Search the entire INBOX for the NIN.
         *
         * TEXT searches both message headers and body.
         */

        $searchTerm =
            '"' .
            $nin .
            '"';


        $emails =
            @imap_search(
                $imap,
                'TEXT ' .
                $searchTerm,
                SE_UID
            );


        if (
            $emails === false
        ) {

            @imap_close(
                $imap
            );


            return [

                'success' =>
                    true,

                'records' =>
                    [],

                'message' =>
                    'No records yet.'

            ];
        }


        /*
         * Newest first.
         */

        rsort(
            $emails,
            SORT_NUMERIC
        );


        /*
         * Limit results.
         */

        $emails =
            array_slice(
                $emails,
                0,
                MAILBOX_MAX_RESULTS
            );


        $records = [];


        foreach (
            $emails as $uid
        ) {

            /*
             * Convert UID to message sequence number.
             */

            $messageNumber =
                @imap_msgno(
                    $imap,
                    (int)$uid
                );


            if (
                $messageNumber <= 0
            ) {

                continue;

            }


            $header =
                @imap_headerinfo(
                    $imap,
                    $messageNumber
                );


            if (
                !$header
            ) {

                continue;

            }


            $subject =
                getMailboxHeaderValue(
                    $header,
                    'subject'
                );


            $from =
                '';


            if (
                isset(
                    $header->from
                )
                &&
                is_array(
                    $header->from
                )
            ) {

                $fromParts = [];


                foreach (
                    $header->from
                    as $fromPerson
                ) {

                    $name =
                        isset(
                            $fromPerson->personal
                        )
                            ? decodeMimeHeaderValue(
                                (string)$fromPerson->personal
                            )
                            : '';


                    $email =
                        isset(
                            $fromPerson->mailbox,
                            $fromPerson->host
                        )
                            ? $fromPerson->mailbox .
                              '@' .
                              $fromPerson->host
                            : '';


                    if (
                        $name !== '' &&
                        $email !== ''
                    ) {

                        $fromParts[] =
                            $name .
                            ' <' .
                            $email .
                            '>';

                    } elseif (
                        $email !== ''
                    ) {

                        $fromParts[] =
                            $email;

                    } elseif (
                        $name !== ''
                    ) {

                        $fromParts[] =
                            $name;
                    }
                }


                $from =
                    implode(
                        ', ',
                        $fromParts
                    );
            }


            $to =
                '';


            if (
                isset(
                    $header->to
                )
                &&
                is_array(
                    $header->to
                )
            ) {

                $toParts = [];


                foreach (
                    $header->to
                    as $toPerson
                ) {

                    $name =
                        isset(
                            $toPerson->personal
                        )
                            ? decodeMimeHeaderValue(
                                (string)$toPerson->personal
                            )
                            : '';


                    $email =
                        isset(
                            $toPerson->mailbox,
                            $toPerson->host
                        )
                            ? $toPerson->mailbox .
                              '@' .
                              $toPerson->host
                            : '';


                    if (
                        $name !== '' &&
                        $email !== ''
                    ) {

                        $toParts[] =
                            $name .
                            ' <' .
                            $email .
                            '>';

                    } elseif (
                        $email !== ''
                    ) {

                        $toParts[] =
                            $email;

                    } elseif (
                        $name !== ''
                    ) {

                        $toParts[] =
                            $name;
                    }
                }


                $to =
                    implode(
                        ', ',
                        $toParts
                    );
            }


            $date =
                isset(
                    $header->date
                )
                    ? (string)$header->date
                    : '';


            $timestamp =
                isset(
                    $header->udate
                )
                    ? (int)$header->udate
                    : 0;


            if (
                $timestamp > 0
            ) {

                $formattedDate =
                    date(
                        'd M Y, h:i A',
                        $timestamp
                    );

            } else {

                $formattedDate =
                    $date;
            }


            /*
             * Get complete email body.
             */

            $body =
                fetchMailboxEmailBody(
                    $imap,
                    $messageNumber
                );


            /*
             * Some cPanel mailboxes may return an empty MIME body.
             * Try direct body as fallback.
             */

            if (
                $body === ''
            ) {

                $fallback =
                    @imap_body(
                        $imap,
                        $messageNumber
                    );


                if (
                    is_string(
                        $fallback
                    )
                ) {

                    $body =
                        cleanEmailBody(
                            $fallback
                        );
                }
            }


            $records[] = [

                'uid' =>
                    (int)$uid,

                'message_number' =>
                    $messageNumber,

                'subject' =>
                    $subject,

                'from' =>
                    $from,

                'to' =>
                    $to,

                'date' =>
                    $formattedDate,

                'body' =>
                    $body

            ];
        }


        @imap_close(
            $imap
        );


        return [

            'success' =>
                true,

            'records' =>
                $records,

            'message' =>
                empty($records)
                    ? 'No records yet.'
                    : ''

        ];

    } catch (Throwable $e) {

        if (
            is_resource($imap)
        ) {

            @imap_close(
                $imap
            );
        }


        logDebug(
            'MAILBOX SEARCH ERROR: ' .
            $e->getMessage()
        );


        return [

            'success' =>
                false,

            'records' =>
                [],

            'message' =>
                $e->getMessage()

        ];
    }
}


/* ============================================================
   RENDER MAILBOX RESULTS
============================================================ */

function renderMailboxEmailsHtml(
    string $nin,
    array $result
): string {

    ob_start();

    ?>

    <div class="email-modal-inner">

        <div
            class="flex
                   items-center
                   justify-between
                   gap-3
                   mb-5">

            <div>

                <div
                    class="text-xl
                           font-bold
                           text-white">

                    <i
                        class="fa-solid
                               fa-envelope-open-text
                               text-blue-400">
                    </i>

                    Mailbox Emails

                </div>


                <div
                    class="text-xs
                           text-gray-400
                           mt-1">

                    Searching cPanel mailbox for NIN:

                    <span
                        class="text-blue-300
                               font-semibold">

                        <?= h($nin) ?>

                    </span>

                </div>

            </div>


            <button
                type="button"
                onclick="closeEmailModal()"
                class="w-10
                       h-10
                       rounded-full
                       bg-red-500/20
                       hover:bg-red-500/40
                       text-red-300
                       flex
                       items-center
                       justify-center">

                <i
                    class="fa-solid
                           fa-xmark">
                </i>

            </button>

        </div>


        <?php if (
            !$result['success']
        ): ?>

            <div
                class="rounded-xl
                       border
                       border-red-500/30
                       bg-red-500/10
                       p-6
                       text-center">

                <div
                    class="text-red-400
                           text-4xl
                           mb-3">

                    <i
                        class="fa-solid
                               fa-triangle-exclamation">
                    </i>

                </div>


                <div
                    class="font-semibold
                           text-white">

                    Could not connect to mailbox.

                </div>


                <div
                    class="text-gray-400
                           text-sm
                           mt-2
                           break-words">

                    <?= h(
                        $result['message']
                        ?? 'Mailbox connection failed.'
                    ) ?>

                </div>

            </div>


        <?php elseif (
            empty(
                $result['records']
            )
        ): ?>

            <div
                class="rounded-xl
                       border
                       border-yellow-500/30
                       bg-yellow-500/10
                       p-10
                       text-center">

                <div
                    class="text-yellow-300
                           text-5xl
                           mb-4">

                    <i
                        class="fa-regular
                               fa-envelope">
                    </i>

                </div>


                <div
                    class="text-xl
                           font-bold
                           text-white">

                    No records yet

                </div>


                <div
                    class="text-sm
                           text-gray-400
                           mt-2">

                    No email containing this NIN
                    was found in the cPanel mailbox.

                </div>


                <div
                    class="text-xs
                           text-gray-500
                           mt-3
                           break-all">

                    Mailbox:
                    <?= h(MAILBOX_USERNAME) ?>

                </div>

            </div>


        <?php else: ?>

            <div
                class="mb-4
                       rounded-xl
                       bg-green-500/10
                       border
                       border-green-500/20
                       p-4
                       text-sm
                       text-green-300">

                <i
                    class="fa-solid
                           fa-circle-check">
                </i>

                <?= count(
                    $result['records']
                ) ?>

                email record(s) found in mailbox.

            </div>


            <div
                class="space-y-4
                       max-h-[65vh]
                       overflow-y-auto
                       pr-1">

                <?php foreach (
                    $result['records']
                    as $index => $email
                ): ?>

                    <div
                        class="rounded-2xl
                               border
                               border-white/10
                               bg-slate-950/60
                               overflow-hidden">

                        <!-- EMAIL HEADER -->

                        <div
                            class="p-4
                                   border-b
                                   border-white/10">

                            <div
                                class="flex
                                       flex-col
                                       md:flex-row
                                       md:items-start
                                       md:justify-between
                                       gap-3">

                                <div
                                    class="min-w-0">

                                    <div
                                        class="text-[11px]
                                               text-gray-500
                                               uppercase
                                               tracking-wider
                                               mb-1">

                                        Email #<?= $index + 1 ?>

                                    </div>


                                    <div
                                        class="text-lg
                                               font-bold
                                               text-white
                                               break-words">

                                        <?= h(
                                            $email['subject']
                                            !== ''
                                                ? $email['subject']
                                                : '(No Subject)'
                                        ) ?>

                                    </div>

                                </div>


                                <?php if (
                                    $email['date'] !== ''
                                ): ?>

                                    <div
                                        class="text-xs
                                               text-gray-400
                                               whitespace-nowrap">

                                        <i
                                            class="fa-regular
                                                   fa-clock">
                                        </i>

                                        <?= h(
                                            $email['date']
                                        ) ?>

                                    </div>

                                <?php endif; ?>

                            </div>


                            <?php if (
                                $email['from'] !== ''
                            ): ?>

                                <div
                                    class="mt-4
                                           text-sm
                                           break-all">

                                    <span
                                        class="text-gray-500">

                                        From:

                                    </span>

                                    <span
                                        class="text-gray-200">

                                        <?= h(
                                            $email['from']
                                        ) ?>

                                    </span>

                                </div>

                            <?php endif; ?>


                            <?php if (
                                $email['to'] !== ''
                            ): ?>

                                <div
                                    class="mt-2
                                           text-sm
                                           break-all">

                                    <span
                                        class="text-gray-500">

                                        To:

                                    </span>

                                    <span
                                        class="text-gray-200">

                                        <?= h(
                                            $email['to']
                                        ) ?>

                                    </span>

                                </div>

                            <?php endif; ?>

                        </div>


                        <!-- EMAIL BODY -->

                        <div
                            class="p-4">

                            <div
                                class="text-xs
                                       uppercase
                                       tracking-wider
                                       text-gray-500
                                       mb-3">

                                Email Message

                            </div>


                            <div
                                class="rounded-xl
                                       bg-black/30
                                       border
                                       border-white/5
                                       p-4
                                       text-sm
                                       text-gray-200
                                       whitespace-pre-wrap
                                       break-words
                                       leading-6
                                       max-h-[450px]
                                       overflow-y-auto">

                                <?php if (
                                    trim(
                                        (string)$email['body']
                                    ) !== ''
                                ): ?>

                                    <?= h(
                                        $email['body']
                                    ) ?>

                                <?php else: ?>

                                    <span
                                        class="text-gray-500">

                                        Email body could not be
                                        extracted.

                                    </span>

                                <?php endif; ?>

                            </div>

                        </div>

                    </div>

                <?php endforeach; ?>

            </div>

        <?php endif; ?>

    </div>

    <?php

    return ob_get_clean();
}


/* ============================================================
   VIEW EMAIL AJAX
============================================================ */

/*
 * VERY IMPORTANT:
 *
 * This happens BEFORE the normal AJAX search handler.
 *
 * It connects directly to the cPanel mailbox.
 */

if (
    $_SERVER['REQUEST_METHOD'] === 'GET' &&
    isset($_GET['view_email'])
) {

    /*
     * Start buffering.
     *
     * Any accidental PHP warning is removed before JSON.
     */

    ob_start();


    try {

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


        if (
            !preg_match(
                '/^[0-9]{11}$/',
                $nin
            )
        ) {

            sendCleanJson(
                [

                    'success' =>
                        false,

                    'count' =>
                        0,

                    'message' =>
                        'Invalid NIN.',

                    'html' =>
                        '
                        <div class="p-8 text-center">

                            <div class="
                                text-red-400
                                text-4xl
                                mb-3">

                                <i class="
                                    fa-solid
                                    fa-triangle-exclamation">
                                </i>

                            </div>

                            <div class="
                                text-white
                                font-semibold">

                                Invalid NIN.

                            </div>

                        </div>
                        '

                ],
                400
            );

        }


        /*
         * Search ACTUAL cPanel mailbox.
         */

        $mailResult =
            getMailboxEmailsByNin(
                $nin
            );


        $html =
            renderMailboxEmailsHtml(
                $nin,
                $mailResult
            );


        sendCleanJson(
            [

                'success' =>
                    (bool)(
                        $mailResult['success']
                        ?? false
                    ),

                'count' =>
                    count(
                        $mailResult['records']
                        ?? []
                    ),

                'message' =>
                    (string)(
                        $mailResult['message']
                        ?? ''
                    ),

                'html' =>
                    $html

            ]
        );


    } catch (Throwable $e) {

        logDebug(
            'VIEW EMAIL ENDPOINT ERROR: ' .
            $e->getMessage()
        );


        sendCleanJson(
            [

                'success' =>
                    false,

                'count' =>
                    0,

                'message' =>
                    'Could not connect to mailbox.',

                'html' =>
                    '
                    <div class="p-8 text-center">

                        <div class="
                            text-red-400
                            text-4xl
                            mb-3">

                            <i class="
                                fa-solid
                                fa-envelope-circle-check">
                            </i>

                        </div>

                        <div class="
                            text-white
                            font-semibold">

                            Could not connect to mailbox.

                        </div>

                        <div class="
                            text-gray-400
                            text-sm
                            mt-2">

                            Please check the mailbox
                            configuration.

                        </div>

                    </div>
                    '

            ],
            500
        );
    }
}


/* ============================================================
   SCHEMA UPGRADE
============================================================ */

$requiredCols = [

    'nin_firstname' =>
        "ALTER TABLE validation_requests
         ADD COLUMN nin_firstname VARCHAR(120) NULL
         AFTER nin",

    'nin_middlename' =>
        "ALTER TABLE validation_requests
         ADD COLUMN nin_middlename VARCHAR(120) NULL
         AFTER nin_firstname",

    'nin_surname' =>
        "ALTER TABLE validation_requests
         ADD COLUMN nin_surname VARCHAR(120) NULL
         AFTER nin_middlename",

    'nin_dob' =>
        "ALTER TABLE validation_requests
         ADD COLUMN nin_dob VARCHAR(40) NULL
         AFTER nin_surname",

    'nin_photo' =>
        "ALTER TABLE validation_requests
         ADD COLUMN nin_photo MEDIUMTEXT NULL
         AFTER nin_dob",

    'nin_photo_path' =>
        "ALTER TABLE validation_requests
         ADD COLUMN nin_photo_path VARCHAR(255) NULL
         AFTER nin_photo",

    'verified_at' =>
        "ALTER TABLE validation_requests
         ADD COLUMN verified_at DATETIME NULL
         AFTER nin_photo_path",

    'verify_status' =>
        "ALTER TABLE validation_requests
         ADD COLUMN verify_status VARCHAR(40) NULL
         AFTER verified_at",

    'email_status' =>
        "ALTER TABLE validation_requests
         ADD COLUMN email_status VARCHAR(20) NOT NULL DEFAULT 'Pending'
         AFTER verify_status"

];


$existingCols = [];


try {

    $colRes =
        $conn->query(
            "SHOW COLUMNS FROM validation_requests"
        );


    while (
        $colRes instanceof mysqli_result &&
        ($cr = $colRes->fetch_assoc())
    ) {

        $field =
            (string)(
                $cr['Field']
                ?? ''
            );


        if (
            $field !== ''
        ) {

            $existingCols[$field] =
                true;
        }
    }

} catch (Throwable $e) {

    logDebug(
        'Schema check error: ' .
        $e->getMessage()
    );
}


foreach (
    $requiredCols as $col => $sql
) {

    if (
        isset(
            $existingCols[$col]
        )
    ) {

        continue;
    }


    try {

        $conn->query(
            $sql
        );

    } catch (Throwable $e) {

        logDebug(
            'Schema upgrade error ' .
            $col .
            ': ' .
            $e->getMessage()
        );
    }
}


/* ============================================================
   NIN API CONFIGURATION
============================================================ */

const UNIFYX_NIN_API_URL =
    'https://new.unifyxpress.com/api/v4/verify/nin';


const UNIFYX_NIN_API_KEY =
    'sk_live_uqSkHKwJDJjKgrQZR8knNJHHtsSOFK3dybnD';


const DATAVERIFY_NIN_API_URL =
    'https://dataverify.org/developers/nin_slips/nin_premium';


const DATAVERIFY_NIN_API_KEY =
    'dataverify9ec8d2a1130c236ebe630efa08916c36';


/* ============================================================
   ACTIVE API
============================================================ */

function getActiveNinApi(): string
{
    if (
        !isset(
            $_SESSION['active_nin_api']
        )
    ) {

        $_SESSION['active_nin_api'] =
            'unifyxpress';
    }


    $api =
        strtolower(
            trim(
                (string)(
                    $_SESSION['active_nin_api']
                )
            )
        );


    if (
        !in_array(
            $api,
            [
                'unifyxpress',
                'dataverify'
            ],
            true
        )
    ) {

        $api =
            'unifyxpress';

        $_SESSION['active_nin_api'] =
            $api;
    }


    return $api;
}


/* ============================================================
   API SWITCH
============================================================ */

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

    $requestedApi =
        strtolower(
            trim(
                (string)(
                    $_POST['switch_nin_api']
                    ?? ''
                )
            )
        );


    if (
        in_array(
            $requestedApi,
            [
                'unifyxpress',
                'dataverify'
            ],
            true
        )
    ) {

        $_SESSION['active_nin_api'] =
            $requestedApi;
    }


    $active =
        getActiveNinApi();


    if (
        isAjaxRequest()
    ) {

        sendCleanJson(
            [

                'success' =>
                    true,

                'active_api' =>
                    $active,

                'api_name' =>
                    $active === 'dataverify'
                        ? 'DataVerify'
                        : 'UnifyXpress',

                'message' =>
                    $active === 'dataverify'
                        ? 'DataVerify is now active.'
                        : 'UnifyXpress is now active.'

            ]
        );
    }


    header(
        'Location: ' .
        $_SERVER['REQUEST_URI']
    );

    exit;
}


/* ============================================================
   UNIFYXPRESS
============================================================ */

function ninApiCallUnifyXpress(
    string $nin
): array {

    $headersList = [

        [
            'Content-Type: application/json',
            'Authorization: Bearer ' .
            UNIFYX_NIN_API_KEY
        ],

        [
            'Content-Type: application/json',
            'Authorization: ' .
            UNIFYX_NIN_API_KEY
        ],

        [
            'Content-Type: application/json',
            'x-api-key: ' .
            UNIFYX_NIN_API_KEY
        ]

    ];


    $payload =
        json_encode(
            [
                'nin' =>
                    $nin
            ],
            JSON_UNESCAPED_SLASHES
        );


    $lastBody = '';

    $lastHttp = 0;

    $decoded = null;


    foreach (
        $headersList as $headers
    ) {

        $ch =
            curl_init(
                UNIFYX_NIN_API_URL
            );


        curl_setopt_array(
            $ch,
            [

                CURLOPT_RETURNTRANSFER =>
                    true,

                CURLOPT_POST =>
                    true,

                CURLOPT_POSTFIELDS =>
                    $payload,

                CURLOPT_HTTPHEADER =>
                    $headers,

                CURLOPT_TIMEOUT =>
                    25,

                CURLOPT_CONNECTTIMEOUT =>
                    10,

                CURLOPT_SSL_VERIFYPEER =>
                    true,

                CURLOPT_SSL_VERIFYHOST =>
                    2

            ]
        );


        $body =
            curl_exec(
                $ch
            );


        $http =
            (int)curl_getinfo(
                $ch,
                CURLINFO_HTTP_CODE
            );


        $curlError =
            curl_error(
                $ch
            );


        curl_close(
            $ch
        );


        $j =
            json_decode(
                (string)$body,
                true
            );


        if (
            is_array($j) &&
            $http === 200 &&
            isset(
                $j['data']['nin']
            )
        ) {

            return [

                'success' =>
                    true,

                'no_record' =>
                    false,

                'suspended' =>
                    false,

                'photo_err' =>
                    false,

                'record' =>
                    $j['data'],

                'raw' =>
                    $j,

                'http' =>
                    $http,

                'api' =>
                    'unifyxpress'

            ];
        }


        $lastBody =
            (string)$body;


        $lastHttp =
            $http;


        $decoded =
            $j;


        if (
            $curlError !== ''
        ) {

            logDebug(
                'UnifyXpress CURL error: ' .
                $curlError
            );
        }
    }


    $lower =
        strtolower(
            $lastBody
        );


    $suspended =
        strpos(
            $lower,
            'suspend'
        ) !== false
        ||
        strpos(
            $lower,
            'inactive'
        ) !== false
        ||
        strpos(
            $lower,
            'deactivat'
        ) !== false;


    return [

        'success' =>
            false,

        'no_record' =>
            !$suspended,

        'suspended' =>
            $suspended,

        'photo_err' =>
            false,

        'record' =>
            is_array($decoded)
                ? (
                    $decoded['data']
                    ?? null
                )
                : null,

        'raw' =>
            is_array($decoded)
                ? $decoded
                : [
                    'raw_body' =>
                        $lastBody,

                    'http' =>
                        $lastHttp
                ],

        'http' =>
            $lastHttp,

        'api' =>
            'unifyxpress'

    ];
}


/* ============================================================
   DATAVERIFY
============================================================ */

function ninApiCallDataVerify(
    string $nin
): array {

    $payload =
        json_encode(
            [

                'api_key' =>
                    DATAVERIFY_NIN_API_KEY,

                'nin' =>
                    $nin

            ],
            JSON_UNESCAPED_SLASHES
        );


    $ch =
        curl_init(
            DATAVERIFY_NIN_API_URL
        );


    curl_setopt_array(
        $ch,
        [

            CURLOPT_RETURNTRANSFER =>
                true,

            CURLOPT_POST =>
                true,

            CURLOPT_POSTFIELDS =>
                $payload,

            CURLOPT_HTTPHEADER =>
                [

                    'Content-Type: application/json',

                    'Content-Length: ' .
                    strlen($payload)

                ],

            CURLOPT_TIMEOUT =>
                30,

            CURLOPT_CONNECTTIMEOUT =>
                10,

            CURLOPT_SSL_VERIFYPEER =>
                true,

            CURLOPT_SSL_VERIFYHOST =>
                2

        ]
    );


    $response =
        curl_exec(
            $ch
        );


    $curlError =
        curl_error(
            $ch
        );


    $httpCode =
        (int)curl_getinfo(
            $ch,
            CURLINFO_HTTP_CODE
        );


    curl_close(
        $ch
    );


    if (
        $response === false ||
        $curlError !== ''
    ) {

        return [

            'success' =>
                false,

            'no_record' =>
                false,

            'suspended' =>
                false,

            'photo_err' =>
                false,

            'record' =>
                null,

            'raw' =>
                [
                    'curl_error' =>
                        $curlError
                ],

            'http' =>
                $httpCode,

            'api' =>
                'dataverify'

        ];
    }


    $apiResponse =
        json_decode(
            (string)$response,
            true
        );


    if (
        !is_array(
            $apiResponse
        )
    ) {

        return [

            'success' =>
                false,

            'no_record' =>
                false,

            'suspended' =>
                false,

            'photo_err' =>
                false,

            'record' =>
                null,

            'raw' =>
                [
                    'raw_body' =>
                        (string)$response,

                    'http' =>
                        $httpCode
                ],

            'http' =>
                $httpCode,

            'api' =>
                'dataverify'

        ];
    }


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


    $userData =
        $apiResponse['user_data']
        ?? null;


    if (
        $status === 'success' &&
        is_array($userData) &&
        !empty(
            $userData['nin']
        )
    ) {

        $record = [

            'nin' =>
                (string)(
                    $userData['nin']
                    ?? $nin
                ),

            'firstname' =>
                (string)(
                    $userData['firstName']
                    ?? ''
                ),

            'middlename' =>
                (string)(
                    $userData['middleName']
                    ?? ''
                ),

            'surname' =>
                (string)(
                    $userData['surname']
                    ?? ''
                ),

            'dob' =>
                (string)(
                    $userData['birthDate']
                    ?? ''
                ),

            'gender' =>
                (string)(
                    $userData['gender']
                    ?? ''
                ),

            'photo' =>
                (string)(
                    $userData['photo']
                    ?? ''
                ),

            'telephoneNo' =>
                (string)(
                    $userData['telephoneNo']
                    ?? ''
                )

        ];


        return [

            'success' =>
                true,

            'no_record' =>
                false,

            'suspended' =>
                false,

            'photo_err' =>
                false,

            'record' =>
                $record,

            'raw' =>
                $apiResponse,

            'http' =>
                $httpCode,

            'api' =>
                'dataverify'

        ];
    }


    $message =
        strtolower(
            (string)(
                $apiResponse['message']
                ?? ''
            )
        );


    $suspended =
        strpos(
            $message,
            'suspend'
        ) !== false
        ||
        strpos(
            $message,
            'inactive'
        ) !== false
        ||
        strpos(
            $message,
            'deactivat'
        ) !== false;


    return [

        'success' =>
            false,

        'no_record' =>
            !$suspended,

        'suspended' =>
            $suspended,

        'photo_err' =>
            false,

        'record' =>
            is_array($userData)
                ? $userData
                : null,

        'raw' =>
            $apiResponse,

        'http' =>
            $httpCode,

        'api' =>
            'dataverify'

    ];
}


/* ============================================================
   MAIN NIN API
============================================================ */

function ninApiCall(
    string $nin
): array {

    if (
        getActiveNinApi() ===
        'dataverify'
    ) {

        return ninApiCallDataVerify(
            $nin
        );
    }


    return ninApiCallUnifyXpress(
        $nin
    );
}


/* ============================================================
   DOB
============================================================ */

function formatDobForReply(
    string $raw
): string {

    $raw =
        trim(
            $raw
        );


    if (
        $raw === ''
    ) {

        return '';

    }


    $ts =
        strtotime(
            $raw
        );


    if (
        $ts !== false
    ) {

        return date(
            'd-m-Y',
            $ts
        );
    }


    return $raw;
}


/* ============================================================
   FOUND REPLY
============================================================ */

function buildFoundReply(
    array $r
): string {

    $fn =
        trim(
            (string)(
                $r['firstname']
                ?? ''
            )
        );


    $mn =
        trim(
            (string)(
                $r['middlename']
                ?? ''
            )
        );


    $sn =
        trim(
            (string)(
                $r['surname']
                ?? ''
            )
        );


    $name =
        trim(
            $fn .
            ' ' .
            (
                $mn !== ''
                    ? $mn . ' '
                    : ''
            ) .
            $sn
        );


    return
        $name .
        "\n" .
        formatDobForReply(
            (string)(
                $r['dob']
                ?? ''
            )
        );
}


/* ============================================================
   SAVE PHOTO
============================================================ */

function saveVerificationPhoto(
    int $rowId,
    string $photoRaw
): array {

    if (
        $photoRaw === ''
    ) {

        return [
            'path' =>
                '',

            'error' =>
                'photo field was empty'
        ];
    }


    $dir =
        __DIR__ .
        '/uploads/nin_photos';


    if (
        !is_dir($dir) &&
        !@mkdir(
            $dir,
            0775,
            true
        ) &&
        !is_dir($dir)
    ) {

        return [
            'path' =>
                '',

            'error' =>
                'could not create photo directory'
        ];
    }


    $bin = null;

    $ext = 'jpg';


    if (
        stripos(
            $photoRaw,
            'data:image/'
        ) === 0
    ) {

        if (
            preg_match(
                '#^data:image/([a-z0-9]+);base64,(.*)$#is',
                $photoRaw,
                $m
            )
        ) {

            $ext =
                strtolower(
                    $m[1]
                );


            $bin =
                base64_decode(
                    preg_replace(
                        '/\s+/',
                        '',
                        $m[2]
                    ),
                    true
                );
        }

    } elseif (
        preg_match(
            '#^https?://#i',
            $photoRaw
        )
    ) {

        $ch =
            curl_init(
                $photoRaw
            );


        curl_setopt_array(
            $ch,
            [

                CURLOPT_RETURNTRANSFER =>
                    true,

                CURLOPT_FOLLOWLOCATION =>
                    true,

                CURLOPT_TIMEOUT =>
                    15,

                CURLOPT_SSL_VERIFYPEER =>
                    true,

                CURLOPT_SSL_VERIFYHOST =>
                    2

            ]
        );


        $bin =
            curl_exec(
                $ch
            );


        $ct =
            (string)curl_getinfo(
                $ch,
                CURLINFO_CONTENT_TYPE
            );


        curl_close(
            $ch
        );


        if (
            stripos(
                $ct,
                'png'
            ) !== false
        ) {

            $ext =
                'png';

        } elseif (
            stripos(
                $ct,
                'webp'
            ) !== false
        ) {

            $ext =
                'webp';
        }

    } else {

        $bin =
            base64_decode(
                preg_replace(
                    '/\s+/',
                    '',
                    $photoRaw
                ),
                true
            );
    }


    if (
        !is_string($bin) ||
        $bin === ''
    ) {

        return [

            'path' =>
                '',

            'error' =>
                'photo could not be decoded'

        ];
    }


    $filename =
        $rowId .
        '_' .
        substr(
            bin2hex(
                random_bytes(4)
            ),
            0,
            8
        ) .
        '.' .
        $ext;


    $path =
        $dir .
        '/' .
        $filename;


    if (
        @file_put_contents(
            $path,
            $bin
        ) === false
    ) {

        return [

            'path' =>
                '',

            'error' =>
                'could not save photo'

        ];
    }


    @chmod(
        $path,
        0644
    );


    return [

        'path' =>
            'uploads/nin_photos/' .
            $filename,

        'error' =>
            ''

    ];
}


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

function getStatusBadgeHtml(
    string $status
): string {

    $s =
        strtolower(
            trim(
                $status
            )
        );


    if (
        $s === 'successful'
    ) {

        return '
        <span class="px-2 py-1 bg-green-500/20
                     text-green-400 rounded-full text-xs">
            Successful
        </span>';

    }


    if (
        $s === 'failed'
    ) {

        return '
        <span class="px-2 py-1 bg-red-500/20
                     text-red-400 rounded-full text-xs">
            Failed
        </span>';

    }


    if (
        $s === 'processing'
    ) {

        return '
        <span class="px-2 py-1 bg-blue-500/20
                     text-blue-400 rounded-full text-xs">
            Processing
        </span>';

    }


    if (
        $s === 'in progress'
    ) {

        return '
        <span class="px-2 py-1 bg-orange-500/20
                     text-orange-400 rounded-full text-xs">
            In Progress
        </span>';
    }


    return '
    <span class="px-2 py-1 bg-yellow-500/20
                 text-yellow-400 rounded-full text-xs">
        Pending
    </span>';
}


/* ============================================================
   COUNTDOWN
============================================================ */

function isCountdownStatus(
    string $status
): bool {

    return in_array(
        strtolower(
            trim(
                $status
            )
        ),
        [
            'pending',
            'in progress',
            'processing'
        ],
        true
    );
}


function getCountdownDeadline(
    $createdAt
): int {

    $createdTs =
        strtotime(
            (string)$createdAt
        );


    if (
        $createdTs === false
    ) {

        $createdTs =
            time();
    }


    return
        $createdTs +
        (
            4 *
            24 *
            60 *
            60
        );
}


function getCountdownHtml(
    array $row
): string {

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


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


    if (
        !isCountdownStatus(
            $status
        )
    ) {

        return '
        <span class="text-green-400
                     text-xs
                     font-semibold">

            <i class="fa-solid fa-circle-check"></i>
            Completed

        </span>';
    }


    $deadline =
        getCountdownDeadline(
            $row['created_at']
            ?? ''
        );


    return '
    <div class="countdown-box"
         data-countdown-id="' .
         $id .
         '"
         data-deadline="' .
         $deadline .
         '">

        <div class="text-xs text-gray-400 mb-1">

            <i class="fa-regular fa-clock"></i>
            Time Remaining

        </div>

        <div class="countdown-value
                    text-yellow-300
                    font-bold
                    text-sm">

            Calculating...

        </div>

    </div>';
}


/* ============================================================
   REFUND
============================================================ */

function getRefundHtml(
    array $row
): string {

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


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


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


    if (
        $refunded === 1
    ) {

        return '
        <span class="text-green-400 text-xs">
            Refunded 80%
        </span>';
    }


    if (
        $status === 'failed'
    ) {

        return '
        <form method="post"
              class="refund-form">

            <input type="hidden"
                   name="id"
                   value="' .
                   $id .
                   '">

            <button
                name="refund"
                type="submit"
                class="bg-red-500
                       hover:bg-red-600
                       px-3 py-1
                       rounded
                       text-xs">

                Refund 80%

            </button>

        </form>';
    }


    return '-';
}


/* ============================================================
   DASHBOARD STATS
============================================================ */

function getDashboardStats(
    mysqli $conn
): array {

    $stats = [

        'today' => [
            'count' => 0,
            'spent' => 0
        ],

        'week' => [
            'count' => 0,
            'spent' => 0
        ],

        'month' => [
            'count' => 0,
            'spent' => 0
        ],

        'total' => [
            'count' => 0,
            'spent' => 0
        ],

        'in_progress' => [
            'count' => 0
        ],

        'processing' => [
            'count' => 0
        ]

    ];


    try {

        $res =
            $conn->query("
                SELECT

                SUM(
                    CASE
                        WHEN DATE(created_at) = CURDATE()
                        THEN 1 ELSE 0
                    END
                ) AS today_count,

                SUM(
                    CASE
                        WHEN DATE(created_at) = CURDATE()
                        THEN price 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 price 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 price ELSE 0
                    END
                ) AS month_spent,

                COUNT(*) AS total_count,

                SUM(price) AS total_spent,

                SUM(
                    CASE
                        WHEN LOWER(TRIM(status))
                             = 'in progress'
                        THEN 1 ELSE 0
                    END
                ) AS in_progress_count,

                SUM(
                    CASE
                        WHEN LOWER(TRIM(status))
                             = 'processing'
                        THEN 1 ELSE 0
                    END
                ) AS processing_count

                FROM validation_requests
            ");


        if (
            $res instanceof mysqli_result &&
            ($s = $res->fetch_assoc())
        ) {

            $stats['today']['count'] =
                (int)(
                    $s['today_count']
                    ?? 0
                );


            $stats['today']['spent'] =
                (float)(
                    $s['today_spent']
                    ?? 0
                );


            $stats['week']['count'] =
                (int)(
                    $s['week_count']
                    ?? 0
                );


            $stats['week']['spent'] =
                (float)(
                    $s['week_spent']
                    ?? 0
                );


            $stats['month']['count'] =
                (int)(
                    $s['month_count']
                    ?? 0
                );


            $stats['month']['spent'] =
                (float)(
                    $s['month_spent']
                    ?? 0
                );


            $stats['total']['count'] =
                (int)(
                    $s['total_count']
                    ?? 0
                );


            $stats['total']['spent'] =
                (float)(
                    $s['total_spent']
                    ?? 0
                );


            $stats['in_progress']['count'] =
                (int)(
                    $s['in_progress_count']
                    ?? 0
                );


            $stats['processing']['count'] =
                (int)(
                    $s['processing_count']
                    ?? 0
                );
        }

    } catch (Throwable $e) {

        logDebug(
            'Stats error: ' .
            $e->getMessage()
        );
    }


    return $stats;
}


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

function renderStatsCards(
    array $stats
): string {

    ob_start();

    ?>

    <div
        class="grid
               sm:grid-cols-2
               lg:grid-cols-3
               xl:grid-cols-6
               gap-4
               mb-6"
        id="stats-container">

        <div
            class="bg-blue-600
                   p-5
                   rounded-xl
                   shadow">

            <div class="text-lg font-semibold mb-2">
                Today
            </div>

            <div class="text-sm">
                Today Count:
                <?= $stats['today']['count'] ?>
            </div>

            <div class="text-sm">
                Today Spent:
                ₦<?= naira(
                    $stats['today']['spent']
                ) ?>
            </div>

        </div>


        <div
            class="bg-green-600
                   p-5
                   rounded-xl
                   shadow">

            <div class="text-lg font-semibold mb-2">
                Weekly
            </div>

            <div class="text-sm">
                Weekly Count:
                <?= $stats['week']['count'] ?>
            </div>

            <div class="text-sm">
                Weekly Spent:
                ₦<?= naira(
                    $stats['week']['spent']
                ) ?>
            </div>

        </div>


        <div
            class="bg-purple-600
                   p-5
                   rounded-xl
                   shadow">

            <div class="text-lg font-semibold mb-2">
                Monthly
            </div>

            <div class="text-sm">
                Monthly Count:
                <?= $stats['month']['count'] ?>
            </div>

            <div class="text-sm">
                Monthly Spent:
                ₦<?= naira(
                    $stats['month']['spent']
                ) ?>
            </div>

        </div>


        <div
            class="bg-orange-600
                   p-5
                   rounded-xl
                   shadow">

            <div class="text-lg font-semibold mb-2">
                Total
            </div>

            <div class="text-sm">
                Total Count:
                <?= $stats['total']['count'] ?>
            </div>

            <div class="text-sm">
                Total Spent:
                ₦<?= naira(
                    $stats['total']['spent']
                ) ?>
            </div>

        </div>


        <div
            class="bg-amber-600
                   p-5
                   rounded-xl
                   shadow">

            <div class="text-lg font-semibold mb-2">
                In Progress
            </div>

            <div class="text-sm">
                Total In Progress:
                <?= $stats['in_progress']['count'] ?>
            </div>

        </div>


        <div
            class="bg-cyan-600
                   p-5
                   rounded-xl
                   shadow">

            <div class="text-lg font-semibold mb-2">
                Processing
            </div>

            <div class="text-sm">
                Total Processing:
                <?= $stats['processing']['count'] ?>
            </div>

        </div>

    </div>

    <?php

    return ob_get_clean();
}


/* ============================================================
   FETCH VALIDATION ROWS
============================================================ */

function fetchValidationRows(
    mysqli $conn,
    string $searchNin = '',
    string $searchStatus = '',
    int $page = 1,
    int $perPage = 10
): array {

    $page =
        max(
            1,
            $page
        );


    $perPage =
        max(
            1,
            $perPage
        );


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


    $where = [];

    $params = [];

    $types = '';


    if (
        $searchNin !== ''
    ) {

        $where[] =
            'nin LIKE ?';


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


        $types .=
            's';
    }


    if (
        $searchStatus !== ''
    ) {

        $where[] =
            'LOWER(TRIM(status)) = ?';


        $params[] =
            strtolower(
                $searchStatus
            );


        $types .=
            's';
    }


    $whereSql =
        empty($where)
            ? ''
            : 'WHERE ' .
              implode(
                  ' AND ',
                  $where
              );


    $countSql = "
        SELECT COUNT(*) AS cnt
        FROM validation_requests
        {$whereSql}
    ";


    if (
        $types !== ''
    ) {

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


        $bind =
            [$types];


        foreach (
            $params as $key => $value
        ) {

            $bind[] =
                &$params[$key];
        }


        call_user_func_array(
            [
                $stmt,
                'bind_param'
            ],
            $bind
        );


        $stmt->execute();


        $countResult =
            $stmt->get_result();


        $countRow =
            $countResult->fetch_assoc();


        $total =
            (int)(
                $countRow['cnt']
                ?? 0
            );


        $stmt->close();

    } else {

        $countResult =
            $conn->query(
                $countSql
            );


        $countRow =
            $countResult->fetch_assoc();


        $total =
            (int)(
                $countRow['cnt']
                ?? 0
            );
    }


    $listSql = "
        SELECT *
        FROM validation_requests
        {$whereSql}
        ORDER BY id DESC
        LIMIT ?
        OFFSET ?
    ";


    $listParams =
        $params;


    $listParams[] =
        $perPage;


    $listParams[] =
        $offset;


    $listTypes =
        $types .
        'ii';


    $stmt =
        $conn->prepare(
            $listSql
        );


    $bind =
        [$listTypes];


    foreach (
        $listParams as $key => $value
    ) {

        $bind[] =
            &$listParams[$key];
    }


    call_user_func_array(
        [
            $stmt,
            'bind_param'
        ],
        $bind
    );


    $stmt->execute();


    $result =
        $stmt->get_result();


    $rows = [];


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

        $rows[] =
            $row;
    }


    $stmt->close();


    return [

        'rows' =>
            $rows,

        'total' =>
            $total

    ];
}


/* ============================================================
   SEARCH INFO
============================================================ */

function renderSearchInfo(
    string $searchNin,
    string $searchStatus,
    int $total
): string {

    if (
        $searchNin === '' &&
        $searchStatus === ''
    ) {

        return '';

    }


    $parts = [];


    if (
        $searchNin !== ''
    ) {

        $parts[] =
            'NIN: <span class="text-white font-semibold">' .
            h($searchNin) .
            '</span>';
    }


    if (
        $searchStatus !== ''
    ) {

        $parts[] =
            'Status: <span class="text-white font-semibold">' .
            h($searchStatus) .
            '</span>';
    }


    return
        '<div class="mt-3 text-sm text-gray-300">' .
        'Showing ' .
        $total .
        ' result(s) for ' .
        implode(
            ' &middot; ',
            $parts
        ) .
        '</div>';
}


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

function renderPaginationHtml(
    int $page,
    int $perPage,
    int $total
): string {

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


    if (
        $totalPages <= 1
    ) {

        return '';

    }


    $page =
        max(
            1,
            min(
                $page,
                $totalPages
            )
        );


    ob_start();

    ?>

    <div
        class="flex
               flex-wrap
               items-center
               justify-between
               gap-3
               p-4
               text-sm">

        <div class="text-gray-300">

            Page <?= $page ?>
            of <?= $totalPages ?>

            (<?= $total ?> total)

        </div>


        <div class="flex flex-wrap gap-1">

            <button
                type="button"
                class="page-btn
                       px-3
                       py-1
                       rounded
                       bg-black/30"
                data-page="<?= max(
                    1,
                    $page - 1
                ) ?>"
                <?= $page <= 1
                    ? 'disabled'
                    : '' ?>>

                Prev

            </button>


            <?php

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


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


            for (
                $p = $start;
                $p <= $end;
                $p++
            ):

                $active =
                    $p === $page
                        ? 'bg-blue-600'
                        : 'bg-black/30';

            ?>

                <button
                    type="button"
                    class="page-btn
                           px-3
                           py-1
                           rounded
                           <?= $active ?>"
                    data-page="<?= $p ?>"
                    <?= $p === $page
                        ? 'disabled'
                        : '' ?>>

                    <?= $p ?>

                </button>

            <?php endfor; ?>


            <button
                type="button"
                class="page-btn
                       px-3
                       py-1
                       rounded
                       bg-black/30"
                data-page="<?= min(
                    $totalPages,
                    $page + 1
                ) ?>"
                <?= $page >= $totalPages
                    ? 'disabled'
                    : '' ?>>

                Next

            </button>

        </div>

    </div>

    <?php

    return ob_get_clean();
}


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

function renderTableRows(
    array $rows
): string {

    ob_start();


    if (
        !empty($rows)
    ):

        foreach (
            $rows as $r
        ):

            ?>

            <tr
                class="border-b
                       border-gray-700
                       hover:bg-white/5
                       transition"
                data-row-id="<?= (int)$r['id'] ?>">

                <td class="p-3">
                    <?= h(
                        $r['user']
                        ?? ''
                    ) ?>
                </td>


                <td class="p-3 font-semibold">
                    <?= h(
                        $r['nin']
                        ?? ''
                    ) ?>
                </td>


                <td class="p-3">
                    <?= h(
                        $r['type']
                        ?? ''
                    ) ?>
                </td>


                <td
                    class="p-3
                           text-green-400
                           font-semibold">

                    ₦<?= naira(
                        $r['price']
                        ?? 0
                    ) ?>

                </td>


                <td class="p-3 status-cell">

                    <?= getStatusBadgeHtml(
                        (string)(
                            $r['status']
                            ?? ''
                        )
                    ) ?>

                </td>


                <td class="p-3 countdown-cell">

                    <?= getCountdownHtml(
                        $r
                    ) ?>

                </td>


                <td class="p-3 refund-cell">

                    <?= getRefundHtml(
                        $r
                    ) ?>

                </td>


                <td class="p-3 min-w-[170px]">

                    <!-- DIRECT CPANEL MAILBOX -->

                    <button
                        type="button"
                        class="view-email-btn
                               w-full
                               mb-2
                               bg-emerald-600
                               hover:bg-emerald-700
                               text-white
                               text-xs
                               p-2.5
                               rounded-lg
                               font-semibold"
                        data-nin="<?= h(
                            $r['nin']
                            ?? ''
                        ) ?>">

                        <i
                            class="fa-solid
                                   fa-envelope-open-text">
                        </i>

                        View Email

                    </button>



                    <!-- SEND / RESEND VALIDATION ASSISTANCE EMAIL TO NIMC -->
                    <?php $emailAlreadySent = strtolower(trim((string)($r['email_status'] ?? ''))) === 'sent'; ?>
                    <button
                        type="button"
                        class="send-validation-email-btn w-full mb-2 <?= $emailAlreadySent ? 'bg-emerald-600 hover:bg-emerald-700' : 'bg-blue-600 hover:bg-blue-700' ?> text-white text-xs p-2.5 rounded-lg font-semibold"
                        data-id="<?= (int)$r['id'] ?>"
                        data-nin="<?= h($r['nin'] ?? '') ?>"
                        data-sent="<?= $emailAlreadySent ? '1' : '0' ?>"
                        title="<?= $emailAlreadySent ? 'Email previously submitted. Click to resend.' : 'Send validation assistance email to NIMC.' ?>">
                        <i class="fa-solid <?= $emailAlreadySent ? 'fa-rotate-right' : 'fa-paper-plane' ?>"></i>
                        <?= $emailAlreadySent ? 'Resend Email to NIMC' : 'Send Email to NIMC' ?>
                    </button>

                    <!-- VERIFY -->

                    <form
                        method="post"
                        class="verify-form mb-2">

                        <input
                            type="hidden"
                            name="id"
                            value="<?= (int)$r['id'] ?>">


                        <input
                            type="hidden"
                            name="nin"
                            value="<?= h(
                                $r['nin']
                                ?? ''
                            ) ?>">


                        <button
                            type="submit"
                            name="verify_request"
                            class="w-full
                                   bg-purple-600
                                   hover:bg-purple-700
                                   text-xs
                                   p-2
                                   rounded-lg
                                   font-semibold">

                            <i
                                class="fa-solid
                                       fa-bolt">
                            </i>

                            Verify

                        </button>

                    </form>


                    <!-- UPDATE -->

                    <form
                        method="post"
                        class="space-y-1
                               update-form">

                        <input
                            type="hidden"
                            name="id"
                            value="<?= (int)$r['id'] ?>">


                        <select
                            name="status"
                            class="w-full
                                   p-2
                                   rounded-lg
                                   bg-black/30
                                   text-xs">

                            <?php foreach (
                                [
                                    'Pending',
                                    'In Progress',
                                    'Processing',
                                    'Successful',
                                    'Failed'
                                ]
                                as $statusOption
                            ): ?>

                                <option
                                    value="<?= h(
                                        $statusOption
                                    ) ?>"
                                    <?= strtolower(
                                        (string)(
                                            $r['status']
                                            ?? ''
                                        )
                                    ) === strtolower(
                                        $statusOption
                                    )
                                        ? 'selected'
                                        : '' ?>>

                                    <?= h(
                                        $statusOption
                                    ) ?>

                                </option>

                            <?php endforeach; ?>

                        </select>


                        <textarea
                            name="reply"
                            placeholder="Reply..."
                            class="w-full
                                   p-2
                                   rounded-lg
                                   bg-black/30
                                   text-xs
                                   reply-cell"><?= h(
                                       $r['reply']
                                       ?? ''
                                   ) ?></textarea>


                        <button
                            type="submit"
                            name="update"
                            class="w-full
                                   bg-blue-600
                                   hover:bg-blue-700
                                   text-xs
                                   p-2
                                   rounded-lg">

                            Update

                        </button>

                    </form>

                </td>

            </tr>

        <?php

        endforeach;

    else:

        ?>

        <tr>

            <td
                colspan="8"
                class="p-6
                       text-center
                       text-gray-300">

                No validation requests found.

            </td>

        </tr>

        <?php

    endif;


    return ob_get_clean();
}




/* ============================================================
   SEND NIMC VALIDATION EMAIL AJAX
============================================================ */

if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['send_validation_email'])
) {
    if (!isAjaxRequest()) {
        sendCleanJson(['success' => false, 'message' => 'Invalid request.'], 400);
    }

    $reqId = (int)($_POST['id'] ?? 0);
    $submittedNin = trim((string)($_POST['nin'] ?? ''));

    if ($reqId <= 0 || !preg_match('/^[0-9]{11}$/', $submittedNin)) {
        sendCleanJson(['success' => false, 'message' => 'Invalid request ID or NIN.'], 422);
    }

    try {
        $stmt = $conn->prepare(
            'SELECT nin FROM validation_requests WHERE id = ? LIMIT 1'
        );
        $stmt->bind_param('i', $reqId);
        $stmt->execute();
        $requestRow = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if (!$requestRow) {
            sendCleanJson(['success' => false, 'message' => 'Validation request not found.'], 404);
        }

        $storedNin = trim((string)($requestRow['nin'] ?? ''));
        if (!preg_match('/^[0-9]{11}$/', $storedNin) || !hash_equals($storedNin, $submittedNin)) {
            sendCleanJson([
                'success' => false,
                'message' => 'The submitted NIN does not match this validation request.'
            ], 409);
        }

        sendNimcValidationAssistanceEmail($storedNin);

        // Persist the sent state so the button remains "Resend" after refresh.
        $saveEmailStatus = $conn->prepare(
            "UPDATE validation_requests SET email_status = 'Sent' WHERE id = ? LIMIT 1"
        );
        $saveEmailStatus->bind_param('i', $reqId);
        $saveEmailStatus->execute();
        $saveEmailStatus->close();

        sendCleanJson([
            'success' => true,
            'email_sent' => true,
            'message' => 'Email submitted to the SMTP server for NIMC assistance.'
        ]);
    } catch (Throwable $e) {
        logDebug('NIMC EMAIL ERROR: ' . $e->getMessage());
        sendCleanJson([
            'success' => false,
            'message' => 'Email could not be sent. Check the server mail configuration and error log.'
        ], 500);
    }
}


/* ============================================================
   VERIFY REQUEST
============================================================ */

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

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


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


    if (
        $reqId <= 0 ||
        !preg_match(
            '/^[0-9]{11}$/',
            $nin
        )
    ) {

        sendCleanJson(
            [

                'success' =>
                    false,

                'message' =>
                    'Invalid row / NIN pair.'

            ],
            400
        );
    }


    try {

        $api =
            ninApiCall(
                $nin
            );


        $newStatus =
            'Processing';


        $newReply =
            'no record is processing';


        $branch =
            'no_record';


        $photoPath =
            '';


        $photoError =
            '';


        if (
            $api['success']
        ) {

            $rec =
                is_array(
                    $api['record']
                )
                    ? $api['record']
                    : [];


            $photoRaw =
                (string)(
                    $rec['photo']
                    ?? ''
                );


            if (
                $photoRaw === ''
            ) {

                foreach (
                    [
                        'photograph',
                        'image',
                        'picture',
                        'passport',
                        'face',
                        'photo_base64',
                        'photoBase64'
                    ] as $key
                ) {

                    if (
                        !empty(
                            $rec[$key]
                        )
                    ) {

                        $photoRaw =
                            (string)(
                                $rec[$key]
                            );

                        break;
                    }
                }
            }


            if (
                $photoRaw !== ''
            ) {

                $newStatus =
                    'Successful';


                $newReply =
                    buildFoundReply(
                        $rec
                    );


                $branch =
                    'found';


                $photoResult =
                    saveVerificationPhoto(
                        $reqId,
                        $photoRaw
                    );


                $photoPath =
                    $photoResult['path'];


                $photoError =
                    $photoResult['error'];

            } else {

                $newStatus =
                    'Processing';


                $newReply =
                    'photograph error is PROCESSING';


                $branch =
                    'found_no_photo';
            }


            $stmt =
                $conn->prepare("
                    UPDATE validation_requests
                    SET
                        nin_firstname=?,
                        nin_middlename=?,
                        nin_surname=?,
                        nin_dob=?,
                        nin_photo=?,
                        nin_photo_path=?,
                        verified_at=NOW(),
                        verify_status=?,
                        status=?,
                        reply=?
                    WHERE id=?
                ");


            $firstname =
                (string)(
                    $rec['firstname']
                    ?? ''
                );


            $middlename =
                (string)(
                    $rec['middlename']
                    ?? ''
                );


            $surname =
                (string)(
                    $rec['surname']
                    ?? ''
                );


            $dob =
                formatDobForReply(
                    (string)(
                        $rec['dob']
                        ?? ''
                    )
                );


            $verifyStatus =
                $branch;


            $stmt->bind_param(
                "sssssssssi",
                $firstname,
                $middlename,
                $surname,
                $dob,
                $photoRaw,
                $photoPath,
                $verifyStatus,
                $newStatus,
                $newReply,
                $reqId
            );


            $stmt->execute();


            $stmt->close();

        } elseif (
            $api['suspended']
        ) {

            $branch =
                'suspended';


            $newStatus =
                'Processing';


            $newReply =
                'suspended is processing';


            $stmt =
                $conn->prepare("
                    UPDATE validation_requests
                    SET
                        verified_at=NOW(),
                        verify_status='suspended',
                        status=?,
                        reply=?
                    WHERE id=?
                ");


            $stmt->bind_param(
                "ssi",
                $newStatus,
                $newReply,
                $reqId
            );


            $stmt->execute();


            $stmt->close();

        } else {

            $stmt =
                $conn->prepare("
                    UPDATE validation_requests
                    SET
                        verified_at=NOW(),
                        verify_status='no_record',
                        status=?,
                        reply=?
                    WHERE id=?
                ");


            $stmt->bind_param(
                "ssi",
                $newStatus,
                $newReply,
                $reqId
            );


            $stmt->execute();


            $stmt->close();
        }


        if (
            isAjaxRequest()
        ) {

            $q =
                $conn->prepare("
                    SELECT
                        id,
                        status,
                        refunded,
                        reply,
                        created_at
                    FROM validation_requests
                    WHERE id=?
                    LIMIT 1
                ");


            $q->bind_param(
                "i",
                $reqId
            );


            $q->execute();


            $row =
                $q->get_result()
                  ->fetch_assoc();


            $q->close();


            sendCleanJson(
                [

                    'success' =>
                        true,

                    'message' =>
                        'NIN verification completed.',

                    'status' =>
                        $newStatus,

                    'reply' =>
                        $newReply,

                    'branch' =>
                        $branch,

                    'api' =>
                        $api['api']
                        ??
                        getActiveNinApi(),

                    'status_badge' =>
                        getStatusBadgeHtml(
                            $newStatus
                        ),

                    'refund_html' =>
                        $row
                            ? getRefundHtml(
                                $row
                            )
                            : '-',

                    'countdown_html' =>
                        $row
                            ? getCountdownHtml(
                                $row
                            )
                            : '-',

                    'stats_html' =>
                        renderStatsCards(
                            getDashboardStats(
                                $conn
                            )
                        ),

                    'photo_saved' =>
                        $photoPath !== '',

                    'photo_error' =>
                        $photoError

                ]
            );
        }


        header(
            'Location: ' .
            $_SERVER['REQUEST_URI']
        );

        exit;

    } catch (Throwable $e) {

        logDebug(
            'VERIFY ERROR: ' .
            $e->getMessage()
        );


        sendCleanJson(
            [

                'success' =>
                    false,

                'message' =>
                    'Verification error occurred.'

            ],
            500
        );
    }
}


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

$allowedStatuses = [

    'Pending',
    'In Progress',
    'Processing',
    'Successful',
    'Failed'

];


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

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


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


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


    if (
        !in_array(
            $status,
            $allowedStatuses,
            true
        )
    ) {

        $status =
            'Pending';
    }


    try {

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


        $stmt->bind_param(
            "ssi",
            $status,
            $reply,
            $id
        );


        $ok =
            $stmt->execute();


        $stmt->close();


        if (
            isAjaxRequest()
        ) {

            $q =
                $conn->prepare("
                    SELECT
                        id,
                        status,
                        refunded,
                        reply,
                        created_at
                    FROM validation_requests
                    WHERE id=?
                    LIMIT 1
                ");


            $q->bind_param(
                "i",
                $id
            );


            $q->execute();


            $row =
                $q->get_result()
                  ->fetch_assoc();


            $q->close();


            sendCleanJson(
                [

                    'success' =>
                        $ok,

                    'message' =>
                        $ok
                            ? 'Request updated successfully.'
                            : 'Update failed.',

                    'status' =>
                        $status,

                    'status_badge' =>
                        getStatusBadgeHtml(
                            $status
                        ),

                    'refund_html' =>
                        $row
                            ? getRefundHtml(
                                $row
                            )
                            : '-',

                    'countdown_html' =>
                        $row
                            ? getCountdownHtml(
                                $row
                            )
                            : '-',

                    'reply' =>
                        $reply,

                    'stats_html' =>
                        renderStatsCards(
                            getDashboardStats(
                                $conn
                            )
                        )

                ]
            );
        }


        header(
            'Location: ' .
            $_SERVER['REQUEST_URI']
        );

        exit;

    } catch (Throwable $e) {

        logDebug(
            'UPDATE ERROR: ' .
            $e->getMessage()
        );


        sendCleanJson(
            [

                'success' =>
                    false,

                'message' =>
                    'Update failed.'

            ],
            500
        );
    }
}


/* ============================================================
   REFUND 80%
============================================================ */

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

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


    $q =
        $conn->prepare("
            SELECT
                id,
                user,
                price,
                status,
                refunded
            FROM validation_requests
            WHERE id=?
            LIMIT 1
        ");


    $q->bind_param(
        "i",
        $id
    );


    $q->execute();


    $row =
        $q->get_result()
          ->fetch_assoc();


    $q->close();


    $success =
        false;


    $message =
        'Refund could not be processed.';


    if (
        $row &&
        strtolower(
            (string)$row['status']
        ) === 'failed' &&
        (int)$row['refunded'] === 0
    ) {

        $user =
            (string)$row['user'];


        $price =
            (float)$row['price'];


        $amt =
            round(
                $price * 0.80,
                2
            );


        $conn->begin_transaction();


        try {

            $bal =
                $conn->prepare("
                    UPDATE balance
                    SET amount=amount+?
                    WHERE user=?
                ");


            $bal->bind_param(
                "ds",
                $amt,
                $user
            );


            $bal->execute();


            $bal->close();


            $upd =
                $conn->prepare("
                    UPDATE validation_requests
                    SET refunded=1
                    WHERE id=?
                ");


            $upd->bind_param(
                "i",
                $id
            );


            $upd->execute();


            $upd->close();


            $ins =
                $conn->prepare("
                    INSERT INTO refund_transactions
                    (
                        validation_request_id,
                        user,
                        original_amount,
                        refund_percent,
                        refund_amount,
                        request_status,
                        note
                    )
                    VALUES
                    (?, ?, ?, ?, ?, ?, ?)
                ");


            $pct =
                80.00;


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


            $note =
                '80% refund for failed validation request';


            $ins->bind_param(
                "isdddss",
                $id,
                $user,
                $price,
                $pct,
                $amt,
                $status,
                $note
            );


            $ins->execute();


            $ins->close();


            $conn->commit();


            $success =
                true;


            $message =
                'Refund processed successfully.';

        } catch (Throwable $e) {

            $conn->rollback();


            logDebug(
                'Refund error: ' .
                $e->getMessage()
            );
        }
    }


    if (
        isAjaxRequest()
    ) {

        sendCleanJson(
            [

                'success' =>
                    $success,

                'message' =>
                    $message,

                'refund_html' =>
                    $success

                        ? '<span class="text-green-400 text-xs">
                             Refunded 80%
                           </span>'

                        : (
                            $row
                                ? getRefundHtml(
                                    $row
                                )
                                : '-'
                        )

            ]
        );
    }


    header(
        'Location: ' .
        $_SERVER['REQUEST_URI']
    );

    exit;
}


/* ============================================================
   PAGE VARIABLES
============================================================ */

$perPage =
    10;


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


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


$searchStatus =
    in_array(
        $searchStatusRaw,
        $allowedStatuses,
        true
    )
        ? $searchStatusRaw
        : '';


$page =
    max(
        1,
        (int)(
            $_GET['page']
            ?? 1
        )
    );


/* ============================================================
   NORMAL AJAX SEARCH
============================================================ */

if (
    $_SERVER['REQUEST_METHOD'] === 'GET' &&
    isAjaxRequest()
) {

    $result =
        fetchValidationRows(
            $conn,
            $searchNin,
            $searchStatus,
            $page,
            $perPage
        );


    sendCleanJson(
        [

            'success' =>
                true,

            'tbody_html' =>
                renderTableRows(
                    $result['rows']
                ),

            'search_info_html' =>
                renderSearchInfo(
                    $searchNin,
                    $searchStatus,
                    $result['total']
                ),

            'pagination_html' =>
                renderPaginationHtml(
                    $page,
                    $perPage,
                    $result['total']
                ),

            'page' =>
                $page

        ]
    );
}


/* ============================================================
   INITIAL DATA
============================================================ */

$result =
    fetchValidationRows(
        $conn,
        $searchNin,
        $searchStatus,
        $page,
        $perPage
    );


$rows =
    $result['rows'];


$stats =
    getDashboardStats(
        $conn
    );


$activeNinApi =
    getActiveNinApi();

?>
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>
    Validation Admin
</title>


<script src="https://cdn.tailwindcss.com"></script>


<link
    rel="stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">


<style>

body {
    overflow-x: hidden;
}

.email-modal-backdrop {
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,.80);
    backdrop-filter: blur(10px);
    z-index: 9999;
    display: none;
    align-items: center;
    justify-content: center;
    padding: 12px;
}

.email-modal-backdrop.show {
    display: flex;
}

.email-modal {
    width: 100%;
    max-width: 900px;
    max-height: 92vh;
    overflow: hidden;
    background: #0f172a;
    border: 1px solid rgba(255,255,255,.10);
    border-radius: 20px;
    box-shadow: 0 30px 100px rgba(0,0,0,.65);
}

.email-modal-inner {
    padding: 20px;
}

@media(max-width:640px) {

    .email-modal {
        max-height: 95vh;
        border-radius: 15px;
    }

    .email-modal-inner {
        padding: 14px;
    }

}

</style>

</head>


<body
    class="bg-gradient-to-br
           from-slate-900
           via-blue-900
           to-slate-800
           text-white">


<div
    class="max-w-7xl
           mx-auto
           p-4
           md:p-6">


<h1
    class="text-2xl
           md:text-3xl
           font-bold
           mb-6">

    📋 Validation Dashboard

</h1>


<!-- =========================================================
     API SWITCHER
========================================================= -->

<div
    class="bg-white/10
           backdrop-blur-xl
           rounded-2xl
           p-4
           mb-6
           border
           border-white/10">

    <div
        class="flex
               flex-col
               md:flex-row
               md:items-center
               md:justify-between
               gap-4">

        <div>

            <div
                class="text-sm
                       text-gray-400
                       mb-1">

                NIN Verification API

            </div>


            <div
                id="active-api-name"
                class="text-xl font-bold">

                <?= $activeNinApi === 'dataverify'
                    ? '🔵 DataVerify'
                    : '🟣 UnifyXpress' ?>

            </div>


            <div
                class="text-xs
                       text-gray-400
                       mt-1">

                Currently selected API for Verify buttons.

            </div>

        </div>


        <div
            class="flex
                   flex-wrap
                   gap-2">

            <button
                type="button"
                class="api-switch-btn
                       px-4
                       py-2
                       rounded-lg
                       text-sm
                       font-semibold
                       <?= $activeNinApi === 'unifyxpress'
                           ? 'bg-purple-600'
                           : 'bg-gray-700' ?>"
                data-api="unifyxpress">

                🟣 Use UnifyXpress

            </button>


            <button
                type="button"
                class="api-switch-btn
                       px-4
                       py-2
                       rounded-lg
                       text-sm
                       font-semibold
                       <?= $activeNinApi === 'dataverify'
                           ? 'bg-blue-600'
                           : 'bg-gray-700' ?>"
                data-api="dataverify">

                🔵 Use DataVerify

            </button>

        </div>

    </div>

</div>


<!-- =========================================================
     TOAST
========================================================= -->

<div
    id="toast"
    class="hidden
           fixed
           top-5
           right-5
           z-[10000]
           min-w-[220px]
           max-w-sm
           px-4
           py-3
           rounded-lg
           shadow-lg
           text-sm
           font-semibold">

</div>


<?= renderStatsCards(
    $stats
) ?>


<!-- =========================================================
     SEARCH
========================================================= -->

<div
    class="bg-white/10
           backdrop-blur-xl
           rounded-2xl
           p-4
           mb-6">

    <form
        method="get"
        id="searchForm"
        class="flex
               flex-col
               md:flex-row
               gap-3
               md:items-end">

        <div class="flex-1">

            <label
                class="block
                       text-sm
                       text-gray-300
                       mb-1">

                Search by NIN

            </label>


            <input
                type="text"
                id="search_nin"
                name="search_nin"
                value="<?= h(
                    $searchNin
                ) ?>"
                placeholder="Enter NIN..."
                class="w-full
                       p-3
                       rounded-lg
                       bg-black/30
                       text-white
                       border
                       border-gray-600
                       outline-none">

        </div>


        <div>

            <label
                class="block
                       text-sm
                       text-gray-300
                       mb-1">

                Filter by Status

            </label>


            <select
                id="search_status"
                name="search_status"
                class="p-3
                       rounded-lg
                       bg-black/30
                       text-white
                       border
                       border-gray-600
                       min-w-[170px]">

                <option value="">
                    All Statuses
                </option>


                <?php foreach (
                    $allowedStatuses
                    as $opt
                ): ?>

                    <option
                        value="<?= h(
                            $opt
                        ) ?>"
                        <?= strcasecmp(
                            $searchStatus,
                            $opt
                        ) === 0
                            ? 'selected'
                            : '' ?>>

                        <?= h(
                            $opt
                        ) ?>

                    </option>

                <?php endforeach; ?>

            </select>

        </div>


        <div
            class="flex gap-2">

            <button
                type="submit"
                id="searchBtn"
                class="bg-blue-600
                       hover:bg-blue-700
                       px-5
                       py-3
                       rounded-lg
                       text-sm
                       font-semibold">

                Search

            </button>


            <button
                type="button"
                id="clearSearchBtn"
                class="bg-gray-600
                       hover:bg-gray-700
                       px-5
                       py-3
                       rounded-lg
                       text-sm
                       font-semibold">

                Clear

            </button>

        </div>

    </form>


    <div id="search-info">

        <?= renderSearchInfo(
            $searchNin,
            $searchStatus,
            $result['total']
        ) ?>

    </div>

</div>


<!-- =========================================================
     TABLE
========================================================= -->

<div
    class="bg-white/10
           backdrop-blur-xl
           rounded-2xl
           overflow-x-auto">

<table
    class="min-w-full text-sm">

<thead
    class="border-b
           border-gray-700
           text-gray-300">

<tr>

<th class="p-3">
    User
</th>

<th class="p-3">
    NIN
</th>

<th class="p-3">
    Type
</th>

<th class="p-3">
    Price
</th>

<th class="p-3">
    Status
</th>

<th class="p-3">
    4 Days Countdown
</th>

<th class="p-3">
    Refund
</th>

<th class="p-3">
    Action
</th>

</tr>

</thead>


<tbody id="table-body">

<?= renderTableRows(
    $rows
) ?>

</tbody>

</table>


<div id="pagination-wrap">

<?= renderPaginationHtml(
    $page,
    $perPage,
    $result['total']
) ?>

</div>

</div>

</div>


<!-- =========================================================
     EMAIL MODAL
========================================================= -->

<div
    id="emailModalBackdrop"
    class="email-modal-backdrop"
    onclick="handleEmailModalBackdrop(event)">

    <div
        class="email-modal"
        onclick="event.stopPropagation()">

        <div
            id="emailModalContent">

            <div
                class="p-10
                       text-center">

                <i
                    class="fa-solid
                           fa-spinner
                           fa-spin
                           text-3xl
                           text-blue-400">
                </i>

            </div>

        </div>

    </div>

</div>


<script>


/* ============================================================
   SEND EMAIL TO NIMC BUTTON (delegated for AJAX pagination)
============================================================ */
document.addEventListener('click', async function (event) {
    const button = event.target.closest('.send-validation-email-btn');
    if (!button || button.disabled) return;

    const id = (button.dataset.id || '').trim();
    const nin = (button.dataset.nin || '').trim();

    if (!/^[0-9]{11}$/.test(nin)) {
        showToast('Invalid NIN.', 'error');
        return;
    }

    if (!confirm('Send an NIN validation assistance email to NIMC?')) {
        return;
    }

    const original = button.innerHTML;
    button.disabled = true;
    button.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Sending...';

    try {
        const formData = new FormData();
        formData.append('send_validation_email', '1');
        formData.append('id', id);
        formData.append('nin', nin);

        const response = await fetch(window.location.href, {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            },
            body: formData,
            cache: 'no-store'
        });

        const raw = await response.text();
        let data;
        try {
            data = JSON.parse(raw);
        } catch (parseError) {
            console.error('Invalid NIMC email response:', raw);
            throw new Error('Server returned an invalid response.');
        }

        showToast(
            data.message || (data.success ? 'Email sent.' : 'Email failed.'),
            data.success ? 'success' : 'error'
        );

        // Change to Resend only after the server confirms successful SMTP submission.
        if (data.success && data.email_sent) {
            button.innerHTML = '<i class="fa-solid fa-rotate-right"></i> Resend Email to NIMC';
            button.classList.remove('bg-blue-600', 'hover:bg-blue-700');
            button.classList.add('bg-emerald-600', 'hover:bg-emerald-700');
            button.dataset.sent = '1';
            button.title = 'Email submitted successfully. Click to resend if needed.';
        }
    } catch (error) {
        console.error('NIMC email error:', error);
        showToast(error.message || 'Could not send email.', 'error');
    } finally {
        button.disabled = false;
        // Keep the successful "Resend" label; restore only when sending failed.
        if (button.dataset.sent !== '1') {
            button.innerHTML = original;
        }
    }
});


/* ============================================================
   TOAST
============================================================ */

function showToast(
    message,
    type = 'success'
) {

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


    toast.textContent =
        message;


    toast.classList.remove(
        'hidden',
        'bg-green-600',
        'bg-red-600',
        'bg-orange-600'
    );


    if (
        type === 'success'
    ) {

        toast.classList.add(
            'bg-green-600'
        );

    } else if (
        type === 'error'
    ) {

        toast.classList.add(
            'bg-red-600'
        );

    } else {

        toast.classList.add(
            'bg-orange-600'
        );
    }


    clearTimeout(
        toast.hideTimer
    );


    toast.hideTimer =
        setTimeout(
            function() {

                toast.classList.add(
                    'hidden'
                );

            },
            3500
        );
}


/* ============================================================
   OPEN MAILBOX MODAL
============================================================ */

async function openEmailModal(
    nin
) {

    const backdrop =
        document.getElementById(
            'emailModalBackdrop'
        );


    const content =
        document.getElementById(
            'emailModalContent'
        );


    backdrop.classList.add(
        'show'
    );


    document.body.style.overflow =
        'hidden';


    content.innerHTML = `

        <div
            class="p-10
                   text-center">

            <i
                class="fa-solid
                       fa-spinner
                       fa-spin
                       text-4xl
                       text-blue-400">
            </i>

            <div
                class="text-sm
                       text-gray-400
                       mt-4">

                Searching cPanel mailbox for

                <span
                    class="text-blue-300
                           font-semibold">

                    ${nin}

                </span>

            </div>

            <div
                class="text-xs
                       text-gray-500
                       mt-2">

                Please wait...

            </div>

        </div>

    `;


    try {

        const params =
            new URLSearchParams();


        params.set(
            'view_email',
            '1'
        );


        params.set(
            'nin',
            nin
        );


        const response =
            await fetch(
                window.location.pathname +
                '?' +
                params.toString(),
                {

                    method:
                        'GET',

                    headers: {

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

                        'Accept':
                            'application/json'

                    },

                    cache:
                        'no-store'

                }
            );


        /*
         * IMPORTANT:
         *
         * Read TEXT first.
         *
         * This prevents:
         *
         * Unexpected token '<'
         *
         * from hiding the real problem.
         */

        const rawText =
            await response.text();


        let data;


        try {

            data =
                JSON.parse(
                    rawText
                );

        } catch (
            jsonError
        ) {

            console.error(
                'Invalid mailbox response:',
                rawText
            );


            content.innerHTML = `

                <div
                    class="p-8
                           text-center">

                    <div
                        class="text-red-400
                               text-4xl
                               mb-3">

                        <i
                            class="fa-solid
                                   fa-triangle-exclamation">
                        </i>

                    </div>

                    <div
                        class="text-white
                               font-semibold">

                        Could not connect to mailbox.

                    </div>

                    <div
                        class="text-gray-400
                               text-sm
                               mt-2">

                        The server returned an
                        invalid response.

                    </div>

                </div>

            `;

            return;
        }


        if (
            data.html
        ) {

            content.innerHTML =
                data.html;

        } else {

            content.innerHTML = `

                <div
                    class="p-8
                           text-center">

                    <div
                        class="text-yellow-400
                               text-4xl
                               mb-3">

                        <i
                            class="fa-regular
                                   fa-envelope">
                        </i>

                    </div>

                    <div
                        class="text-white
                               font-semibold">

                        No records yet

                    </div>

                </div>

            `;
        }


    } catch (
        error
    ) {

        console.error(
            'Mailbox error:',
            error
        );


        content.innerHTML = `

            <div
                class="p-8
                       text-center">

                <div
                    class="text-red-400
                           text-4xl
                           mb-3">

                    <i
                        class="fa-solid
                               fa-wifi">
                    </i>

                </div>

                <div
                    class="text-white
                           font-semibold">

                    Could not connect to mailbox.

                </div>

                <div
                    class="text-gray-400
                           text-sm
                           mt-2">

                    Please try again.

                </div>

            </div>

        `;
    }
}


/* ============================================================
   CLOSE EMAIL MODAL
============================================================ */

function closeEmailModal()
{

    const backdrop =
        document.getElementById(
            'emailModalBackdrop'
        );


    backdrop.classList.remove(
        'show'
    );


    document.body.style.overflow =
        '';
}


function handleEmailModalBackdrop(
    event
) {

    if (
        event.target.id ===
        'emailModalBackdrop'
    ) {

        closeEmailModal();
    }
}


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

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

            closeEmailModal();
        }

    }
);


/* ============================================================
   VIEW EMAIL BUTTONS
============================================================ */

function bindEmailButtons()
{

    document
        .querySelectorAll(
            '.view-email-btn'
        )
        .forEach(
            function(button) {

                if (
                    button.dataset.bound ===
                    '1'
                ) {

                    return;
                }


                button.dataset.bound =
                    '1';


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

                        const nin =
                            (
                                button.dataset.nin
                                || ''
                            ).trim();


                        if (
                            !/^[0-9]{11}$/.test(
                                nin
                            )
                        ) {

                            showToast(
                                'Invalid NIN.',
                                'error'
                            );

                            return;
                        }


                        openEmailModal(
                            nin
                        );
                    }
                );
            }
        );
}


/* ============================================================
   UPDATE STATS
============================================================ */

function updateStatsHtml(
    html
) {

    const oldStats =
        document.getElementById(
            'stats-container'
        );


    if (
        !oldStats ||
        !html
    ) {

        return;
    }


    const wrapper =
        document.createElement(
            'div'
        );


    wrapper.innerHTML =
        html.trim();


    const newStats =
        wrapper.querySelector(
            '#stats-container'
        );


    if (
        newStats
    ) {

        oldStats.replaceWith(
            newStats
        );
    }
}


/* ============================================================
   API SWITCH
============================================================ */

function bindApiSwitchButtons()
{

    document
        .querySelectorAll(
            '.api-switch-btn'
        )
        .forEach(
            function(button) {

                if (
                    button.dataset.bound ===
                    '1'
                ) {

                    return;
                }


                button.dataset.bound =
                    '1';


                button.addEventListener(
                    'click',
                    async function() {

                        const selectedApi =
                            button.dataset.api;


                        const formData =
                            new FormData();


                        formData.append(
                            'switch_nin_api',
                            selectedApi
                        );


                        button.disabled =
                            true;


                        const originalText =
                            button.innerHTML;


                        button.innerHTML =
                            '<i class="fa-solid fa-spinner fa-spin"></i> Switching...';


                        try {

                            const response =
                                await fetch(
                                    window.location.href,
                                    {

                                        method:
                                            'POST',

                                        headers: {

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

                                            'Accept':
                                                'application/json'

                                        },

                                        body:
                                            formData

                                    }
                                );


                            const raw =
                                await response.text();


                            const data =
                                JSON.parse(
                                    raw
                                );


                            if (
                                data.success
                            ) {

                                document
                                    .querySelectorAll(
                                        '.api-switch-btn'
                                    )
                                    .forEach(
                                        function(btn) {

                                            btn.classList.remove(
                                                'bg-purple-600',
                                                'bg-blue-600'
                                            );


                                            btn.classList.add(
                                                'bg-gray-700'
                                            );


                                            if (
                                                btn.dataset.api ===
                                                selectedApi
                                            ) {

                                                btn.classList.remove(
                                                    'bg-gray-700'
                                                );


                                                btn.classList.add(
                                                    selectedApi ===
                                                    'dataverify'
                                                        ? 'bg-blue-600'
                                                        : 'bg-purple-600'
                                                );
                                            }

                                        }
                                    );


                                document
                                    .getElementById(
                                        'active-api-name'
                                    )
                                    .textContent =
                                    selectedApi ===
                                    'dataverify'
                                        ? '🔵 DataVerify'
                                        : '🟣 UnifyXpress';


                                showToast(
                                    data.message,
                                    'success'
                                );

                            } else {

                                showToast(
                                    data.message ||
                                    'Could not switch API.',
                                    'error'
                                );
                            }

                        } catch (
                            error
                        ) {

                            console.error(
                                error
                            );


                            showToast(
                                'Network error.',
                                'error'
                            );

                        } finally {

                            button.disabled =
                                false;


                            button.innerHTML =
                                originalText;
                        }

                    }
                );
            }
        );
}


/* ============================================================
   COUNTDOWN
============================================================ */

const countdownTimers =
    {};


function formatCountdown(
    seconds
) {

    seconds =
        Math.max(
            0,
            Math.floor(
                seconds
            )
        );


    const days =
        Math.floor(
            seconds / 86400
        );


    seconds %=
        86400;


    const hours =
        Math.floor(
            seconds / 3600
        );


    seconds %=
        3600;


    const minutes =
        Math.floor(
            seconds / 60
        );


    const secs =
        seconds %
        60;


    return (

        String(days).padStart(
            2,
            '0'
        ) +
        'd ' +

        String(hours).padStart(
            2,
            '0'
        ) +
        'h ' +

        String(minutes).padStart(
            2,
            '0'
        ) +
        'm ' +

        String(secs).padStart(
            2,
            '0'
        ) +
        's'

    );
}


function stopCountdown(
    id
) {

    if (
        countdownTimers[id]
    ) {

        clearInterval(
            countdownTimers[id]
        );


        delete countdownTimers[id];
    }
}


function startCountdown(
    element
) {

    if (
        !element
    ) {

        return;
    }


    const id =
        element.dataset.countdownId;


    const deadline =
        parseInt(
            element.dataset.deadline,
            10
        );


    if (
        !id ||
        !deadline
    ) {

        return;
    }


    stopCountdown(
        id
    );


    const valueElement =
        element.querySelector(
            '.countdown-value'
        );


    if (
        !valueElement
    ) {

        return;
    }


    function updateCountdown()
    {

        const now =
            Math.floor(
                Date.now() / 1000
            );


        const remaining =
            deadline -
            now;


        if (
            remaining <= 0
        ) {

            valueElement.textContent =
                '00d 00h 00m 00s';


            valueElement.classList.remove(
                'text-yellow-300'
            );


            valueElement.classList.add(
                'text-red-400'
            );


            stopCountdown(
                id
            );


            return;
        }


        valueElement.textContent =
            formatCountdown(
                remaining
            );
    }


    updateCountdown();


    countdownTimers[id] =
        setInterval(
            updateCountdown,
            1000
        );
}


function initCountdowns()
{

    document
        .querySelectorAll(
            '.countdown-box'
        )
        .forEach(
            function(element) {

                startCountdown(
                    element
                );

            }
        );
}


/* ============================================================
   UPDATE FORMS
============================================================ */

function bindUpdateForms()
{

    document
        .querySelectorAll(
            '.update-form'
        )
        .forEach(
            function(form) {

                if (
                    form.dataset.bound ===
                    '1'
                ) {

                    return;
                }


                form.dataset.bound =
                    '1';


                form.addEventListener(
                    'submit',
                    async function(e) {

                        e.preventDefault();


                        const row =
                            form.closest(
                                'tr'
                            );


                        const submitBtn =
                            form.querySelector(
                                'button[name="update"]'
                            );


                        const formData =
                            new FormData(
                                form
                            );


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


                        submitBtn.disabled =
                            true;


                        submitBtn.textContent =
                            'Updating...';


                        try {

                            const response =
                                await fetch(
                                    window.location.href,
                                    {

                                        method:
                                            'POST',

                                        headers: {

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

                                            'Accept':
                                                'application/json'

                                        },

                                        body:
                                            formData

                                    }
                                );


                            const raw =
                                await response.text();


                            const data =
                                JSON.parse(
                                    raw
                                );


                            if (
                                data.success
                            ) {

                                row.querySelector(
                                    '.status-cell'
                                ).innerHTML =
                                    data.status_badge;


                                row.querySelector(
                                    '.refund-cell'
                                ).innerHTML =
                                    data.refund_html;


                                row.querySelector(
                                    '.countdown-cell'
                                ).innerHTML =
                                    data.countdown_html;


                                const reply =
                                    row.querySelector(
                                        '.reply-cell'
                                    );


                                if (
                                    reply
                                ) {

                                    reply.value =
                                        data.reply;
                                }


                                updateStatsHtml(
                                    data.stats_html
                                );


                                bindRefundForms();

                                bindVerifyForms();

                                bindEmailButtons();

                                initCountdowns();


                                showToast(
                                    data.message,
                                    'success'
                                );

                            } else {

                                showToast(
                                    data.message,
                                    'error'
                                );
                            }

                        } catch (
                            error
                        ) {

                            console.error(
                                error
                            );


                            showToast(
                                'Network error occurred.',
                                'error'
                            );

                        } finally {

                            submitBtn.disabled =
                                false;


                            submitBtn.textContent =
                                'Update';
                        }

                    }
                );
            }
        );
}


/* ============================================================
   REFUND FORMS
============================================================ */

function bindRefundForms()
{

    document
        .querySelectorAll(
            '.refund-form'
        )
        .forEach(
            function(form) {

                if (
                    form.dataset.bound ===
                    '1'
                ) {

                    return;
                }


                form.dataset.bound =
                    '1';


                form.addEventListener(
                    'submit',
                    async function(e) {

                        e.preventDefault();


                        if (
                            !confirm(
                                'Refund 80% for this failed request?'
                            )
                        ) {

                            return;
                        }


                        const row =
                            form.closest(
                                'tr'
                            );


                        const cell =
                            row.querySelector(
                                '.refund-cell'
                            );


                        const button =
                            form.querySelector(
                                'button'
                            );


                        const formData =
                            new FormData(
                                form
                            );


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


                        button.disabled =
                            true;


                        button.textContent =
                            'Processing...';


                        try {

                            const response =
                                await fetch(
                                    window.location.href,
                                    {

                                        method:
                                            'POST',

                                        headers: {

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

                                            'Accept':
                                                'application/json'

                                        },

                                        body:
                                            formData

                                    }
                                );


                            const raw =
                                await response.text();


                            const data =
                                JSON.parse(
                                    raw
                                );


                            if (
                                data.success
                            ) {

                                cell.innerHTML =
                                    data.refund_html;


                                showToast(
                                    data.message,
                                    'success'
                                );

                            } else {

                                button.disabled =
                                    false;


                                button.textContent =
                                    'Refund 80%';


                                showToast(
                                    data.message,
                                    'error'
                                );
                            }

                        } catch (
                            error
                        ) {

                            console.error(
                                error
                            );


                            button.disabled =
                                false;


                            button.textContent =
                                'Refund 80%';


                            showToast(
                                'Network error occurred.',
                                'error'
                            );
                        }

                    }
                );
            }
        );
}


/* ============================================================
   VERIFY FORMS
============================================================ */

function bindVerifyForms()
{

    document
        .querySelectorAll(
            '.verify-form'
        )
        .forEach(
            function(form) {

                if (
                    form.dataset.bound ===
                    '1'
                ) {

                    return;
                }


                form.dataset.bound =
                    '1';


                form.addEventListener(
                    'submit',
                    async function(e) {

                        e.preventDefault();


                        const row =
                            form.closest(
                                'tr'
                            );


                        const btn =
                            form.querySelector(
                                'button[name="verify_request"]'
                            );


                        const original =
                            btn.innerHTML;


                        const formData =
                            new FormData(
                                form
                            );


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


                        btn.disabled =
                            true;


                        btn.innerHTML =
                            '<i class="fa-solid fa-spinner fa-spin"></i> Verifying...';


                        try {

                            const response =
                                await fetch(
                                    window.location.href,
                                    {

                                        method:
                                            'POST',

                                        headers: {

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

                                            'Accept':
                                                'application/json'

                                        },

                                        body:
                                            formData

                                    }
                                );


                            const raw =
                                await response.text();


                            const data =
                                JSON.parse(
                                    raw
                                );


                            if (
                                data.success
                            ) {

                                row.querySelector(
                                    '.status-cell'
                                ).innerHTML =
                                    data.status_badge;


                                row.querySelector(
                                    '.refund-cell'
                                ).innerHTML =
                                    data.refund_html;


                                row.querySelector(
                                    '.countdown-cell'
                                ).innerHTML =
                                    data.countdown_html;


                                const reply =
                                    row.querySelector(
                                        '.reply-cell'
                                    );


                                if (
                                    reply
                                ) {

                                    reply.value =
                                        data.reply;
                                }


                                updateStatsHtml(
                                    data.stats_html
                                );


                                bindRefundForms();

                                bindVerifyForms();

                                bindEmailButtons();

                                initCountdowns();


                                let msg =
                                    data.message;


                                if (
                                    data.branch ===
                                    'no_record'
                                ) {

                                    msg =
                                        'No record — marked as Processing.';

                                } else if (
                                    data.branch ===
                                    'suspended'
                                ) {

                                    msg =
                                        'Suspended — marked as Processing.';

                                } else if (
                                    data.branch ===
                                    'found_no_photo'
                                ) {

                                    msg =
                                        'Record found, photograph missing.';

                                } else if (
                                    data.branch ===
                                    'found'
                                ) {

                                    msg =
                                        data.photo_saved
                                            ? 'Record found — photo saved.'
                                            : 'Record found, but photo could not be saved.';
                                }


                                showToast(
                                    msg,
                                    data.branch ===
                                    'found'
                                        ? 'success'
                                        : 'orange'
                                );

                            } else {

                                showToast(
                                    data.message ||
                                    'Verify failed.',
                                    'error'
                                );
                            }

                        } catch (
                            error
                        ) {

                            console.error(
                                error
                            );


                            showToast(
                                'Network error during verify.',
                                'error'
                            );

                        } finally {

                            btn.disabled =
                                false;


                            btn.innerHTML =
                                original;
                        }

                    }
                );
            }
        );
}


/* ============================================================
   SEARCH
============================================================ */

let currentSearch =
    <?= json_encode(
        $searchNin
    ) ?>;


let currentStatus =
    <?= json_encode(
        $searchStatus
    ) ?>;


let currentPage =
    <?= (int)$page ?>;


function bindSearchForm()
{

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


    const input =
        document.getElementById(
            'search_nin'
        );


    const statusSelect =
        document.getElementById(
            'search_status'
        );


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


    const clearBtn =
        document.getElementById(
            'clearSearchBtn'
        );


    const tableBody =
        document.getElementById(
            'table-body'
        );


    const searchInfo =
        document.getElementById(
            'search-info'
        );


    const paginationWrap =
        document.getElementById(
            'pagination-wrap'
        );


    let debounceTimer =
        null;


    async function runSearch(
        value = '',
        status = '',
        page = 1
    ) {

        currentSearch =
            value.trim();


        currentStatus =
            status.trim();


        currentPage =
            page;


        const params =
            new URLSearchParams();


        if (
            currentSearch !== ''
        ) {

            params.set(
                'search_nin',
                currentSearch
            );
        }


        if (
            currentStatus !== ''
        ) {

            params.set(
                'search_status',
                currentStatus
            );
        }


        if (
            page > 1
        ) {

            params.set(
                'page',
                page
            );
        }


        const url =
            window.location.pathname +
            (
                params.toString()
                    ? '?' +
                      params.toString()
                    : ''
            );


        searchBtn.disabled =
            true;


        searchBtn.textContent =
            'Searching...';


        try {

            const response =
                await fetch(
                    url,
                    {

                        headers: {

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

                            'Accept':
                                'application/json'

                        },

                        cache:
                            'no-store'

                    }
                );


            const raw =
                await response.text();


            const data =
                JSON.parse(
                    raw
                );


            if (
                data.success
            ) {

                tableBody.innerHTML =
                    data.tbody_html;


                searchInfo.innerHTML =
                    data.search_info_html ||
                    '';


                paginationWrap.innerHTML =
                    data.pagination_html ||
                    '';


                history.replaceState(
                    null,
                    '',
                    url
                );


                bindUpdateForms();

                bindRefundForms();

                bindVerifyForms();

                bindEmailButtons();

                initCountdowns();

            } else {

                showToast(
                    'Search failed.',
                    'error'
                );
            }

        } catch (
            error
        ) {

            console.error(
                error
            );


            showToast(
                'Network error occurred.',
                'error'
            );

        } finally {

            searchBtn.disabled =
                false;


            searchBtn.textContent =
                'Search';
        }
    }


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

            e.preventDefault();


            runSearch(
                input.value,
                statusSelect.value,
                1
            );

        }
    );


    input.addEventListener(
        'input',
        function() {

            clearTimeout(
                debounceTimer
            );


            debounceTimer =
                setTimeout(
                    function() {

                        runSearch(
                            input.value,
                            statusSelect.value,
                            1
                        );

                    },
                    400
                );
        }
    );


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

            runSearch(
                input.value,
                statusSelect.value,
                1
            );

        }
    );


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

            input.value =
                '';


            statusSelect.value =
                '';


            runSearch(
                '',
                '',
                1
            );

        }
    );


    paginationWrap.addEventListener(
        'click',
        function(e) {

            const button =
                e.target.closest(
                    '.page-btn'
                );


            if (
                !button ||
                button.disabled
            ) {

                return;
            }


            const nextPage =
                parseInt(
                    button.dataset.page,
                    10
                );


            if (
                !nextPage ||
                nextPage ===
                currentPage
            ) {

                return;
            }


            runSearch(
                currentSearch,
                currentStatus,
                nextPage
            );

        }
    );
}


/* ============================================================
   INITIALIZE
============================================================ */

bindApiSwitchButtons();

bindUpdateForms();

bindRefundForms();

bindVerifyForms();

bindEmailButtons();

bindSearchForm();

initCountdowns();

</script>


</body>

</html>