<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| ASOVERIFY MODERN MAIL VIEWER
|--------------------------------------------------------------------------
| INBOX + SENT
|
| FEATURES
|   - 50 emails per page
|   - Inbox pagination
|   - Sent pagination
|   - Search Inbox by NIN
|   - Search NIN inside subject/body
|   - READ = GREEN
|   - UNREAD = BLUE
|   - Real IMAP \Seen flag
|   - Permanent read status
|   - Mobile friendly
|--------------------------------------------------------------------------
*/

error_reporting(E_ALL);
ini_set('display_errors', '1');


/* =========================================================
   MAIL SETTINGS
========================================================= */

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

/*
|--------------------------------------------------------------------------
| PUT YOUR CPANEL MAILBOX PASSWORD HERE
|--------------------------------------------------------------------------
*/

$mailboxPassword = 'Sabirata@273';

$imapServer = 'mail.asoverify.com.ng';
$imapPort   = 993;


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

$perPage = 50;


/* =========================================================
   CHECK IMAP
========================================================= */

if (!function_exists('imap_open')) {

    die('
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta
                name="viewport"
                content="width=device-width, initial-scale=1.0"
            >
            <title>IMAP Error</title>

            <style>
                * {
                    box-sizing: border-box;
                }

                body {
                    margin: 0;
                    padding: 20px;
                    background: #f4f7fb;
                    font-family: Arial, Helvetica, sans-serif;
                }

                .error-box {
                    width: 100%;
                    max-width: 600px;
                    margin: 50px auto;
                    background: #fff;
                    border-radius: 20px;
                    padding: 28px;
                    box-shadow: 0 15px 45px rgba(15,23,42,.10);
                    border-top: 5px solid #dc2626;
                }

                .error-icon {
                    width: 60px;
                    height: 60px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    background: #fee2e2;
                    border-radius: 16px;
                    font-size: 28px;
                    margin-bottom: 18px;
                }

                h2 {
                    margin: 0 0 10px;
                    color: #991b1b;
                }

                p {
                    color: #64748b;
                    line-height: 1.6;
                }
            </style>
        </head>

        <body>

            <div class="error-box">

                <div class="error-icon">
                    ⚠️
                </div>

                <h2>
                    PHP IMAP Extension Missing
                </h2>

                <p>
                    Please enable the PHP IMAP extension from cPanel.
                </p>

            </div>

        </body>
        </html>
    ');
}


/* =========================================================
   HELPER
========================================================= */

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


/* =========================================================
   IMAP PREFIX
========================================================= */

function imapPrefix(
    string $server,
    int $port
): string {

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


/* =========================================================
   CONNECT FOLDER
========================================================= */

function connectFolder(
    string $server,
    int $port,
    string $email,
    string $password,
    string $folder
) {

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

        $mailbox = $folder;

    } else {

        $mailbox =
            imapPrefix(
                $server,
                $port
            ) .
            $folder;
    }

    return @imap_open(
        $mailbox,
        $email,
        $password
    );
}


/* =========================================================
   CONNECT INBOX
========================================================= */

$inboxFolder =
    imapPrefix(
        $imapServer,
        $imapPort
    ) .
    'INBOX';


$inbox = @imap_open(
    $inboxFolder,
    $mailboxEmail,
    $mailboxPassword
);


if (!$inbox) {

    $imapError =
        imap_last_error()
        ?: 'Unknown IMAP connection error';

    die('
        <!DOCTYPE html>
        <html lang="en">
        <head>

            <meta charset="UTF-8">

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

            <title>Mail Connection Error</title>

            <style>

                * {
                    box-sizing: border-box;
                }

                body {
                    margin: 0;
                    padding: 20px;
                    background: #f4f7fb;
                    font-family: Arial, Helvetica, sans-serif;
                }

                .error-box {
                    width: 100%;
                    max-width: 650px;
                    margin: 50px auto;
                    background: #fff;
                    border-radius: 20px;
                    padding: 28px;
                    box-shadow: 0 15px 45px rgba(15,23,42,.10);
                    border-top: 5px solid #dc2626;
                }

                .error-icon {
                    width: 60px;
                    height: 60px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    background: #fee2e2;
                    border-radius: 16px;
                    font-size: 28px;
                    margin-bottom: 18px;
                }

                h2 {
                    margin: 0 0 10px;
                    color: #991b1b;
                    font-size: 22px;
                }

                p {
                    margin: 8px 0;
                    color: #64748b;
                    line-height: 1.6;
                }

                .error-message {
                    margin-top: 18px;
                    padding: 14px;
                    background: #fff1f2;
                    color: #be123c;
                    border-radius: 12px;
                    font-size: 13px;
                    word-break: break-word;
                }

            </style>

        </head>

        <body>

            <div class="error-box">

                <div class="error-icon">
                    ⚠️
                </div>

                <h2>
                    Unable to Connect to Inbox
                </h2>

                <p>
                    The mail server connection could not be established.
                </p>

                <div class="error-message">
                    ' .
                    e($imapError) .
                    '
                </div>

            </div>

        </body>
        </html>
    ');
}


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

$sentFolder = null;
$sentDisplayName = '';

$serverPrefix =
    imapPrefix(
        $imapServer,
        $imapPort
    );


$mailboxes =
    @imap_getmailboxes(
        $inbox,
        $serverPrefix,
        '*'
    );


if ($mailboxes !== false) {

    foreach (
        $mailboxes as $box
    ) {

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


        $displayName =
            @imap_utf7_decode(
                $fullMailboxName
            );


        if ($displayName === false) {

            $displayName =
                $fullMailboxName;
        }


        $folderOnly =
            $displayName;


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

            $closingBrace =
                strpos(
                    $folderOnly,
                    '}'
                );


            if (
                $closingBrace !== false
            ) {

                $folderOnly =
                    substr(
                        $folderOnly,
                        $closingBrace + 1
                    );
            }
        }


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


        $isSent =
            (
                $folderLower === 'sent' ||
                $folderLower === 'inbox.sent' ||
                $folderLower === 'sent items' ||
                $folderLower === 'inbox.sent items' ||
                $folderLower === 'sent mail' ||
                $folderLower === 'inbox.sent mail' ||
                str_ends_with(
                    $folderLower,
                    '.sent'
                ) ||
                str_ends_with(
                    $folderLower,
                    '.sent items'
                ) ||
                str_ends_with(
                    $folderLower,
                    '.sent mail'
                )
            );


        if ($isSent) {

            $sentFolder =
                $fullMailboxName;

            $sentDisplayName =
                $folderOnly;

            break;
        }
    }
}


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

function decodeMimeHeader(
    string $text
): string {

    if ($text === '') {
        return '';
    }


    $decoded =
        @imap_mime_header_decode(
            $text
        );


    if (!$decoded) {
        return $text;
    }


    $result = '';


    foreach (
        $decoded as $part
    ) {

        $charset =
            strtoupper(
                $part->charset ?? 'DEFAULT'
            );


        $value =
            $part->text ?? '';


        if (
            $charset !== 'DEFAULT' &&
            $charset !== 'UTF-8'
        ) {

            $converted =
                @iconv(
                    $charset,
                    'UTF-8//IGNORE',
                    $value
                );


            if (
                $converted !== false
            ) {

                $value =
                    $converted;
            }
        }


        $result .= $value;
    }


    return $result;
}


/* =========================================================
   ADDRESSES
========================================================= */

function getAddresses(
    $header,
    string $field
): string {

    if (
        !isset($header->$field) ||
        empty($header->$field)
    ) {

        return '';
    }


    $addresses = [];


    foreach (
        $header->$field as $address
    ) {

        $name =
            decodeMimeHeader(
                $address->personal ?? ''
            );


        $mailbox =
            $address->mailbox ?? '';


        $host =
            $address->host ?? '';


        $email = '';


        if (
            $mailbox !== '' &&
            $host !== ''
        ) {

            $email =
                $mailbox .
                '@' .
                $host;
        }


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

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

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

            $addresses[] =
                $email;

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

            $addresses[] =
                $name;
        }
    }


    return implode(
        ', ',
        $addresses
    );
}


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

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

    if ($encoding === 3) {

        $decoded =
            base64_decode(
                $body
            );


        if ($decoded !== false) {

            $body =
                $decoded;
        }

    } elseif (
        $encoding === 4
    ) {

        $body =
            quoted_printable_decode(
                $body
            );
    }


    return $body;
}


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

function getEmailBody(
    $imap,
    int $emailNumber
): string {

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


    if (!$structure) {
        return '';
    }


    $plain = '';
    $html  = '';


    if (
        empty(
            $structure->parts
        )
    ) {

        $body =
            @imap_body(
                $imap,
                $emailNumber,
                FT_PEEK
            );


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


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


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

            $html =
                $body;

        } else {

            $plain =
                $body;
        }

    } else {

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

            $section =
                (string)(
                    $partNumber + 1
                );


            $body =
                @imap_fetchbody(
                    $imap,
                    $emailNumber,
                    $section,
                    FT_PEEK
                );


            $body =
                decodeBodyPart(
                    $body,
                    (int)(
                        $part->encoding ?? 0
                    )
                );


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


            $subtype =
                strtoupper(
                    $part->subtype ?? ''
                );


            if (
                $type === 0
            ) {

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

                    $html .=
                        $body;

                } else {

                    $plain .=
                        $body;
                }
            }
        }
    }


    if ($html !== '') {

        $html =
            preg_replace(
                '/<script\b[^>]*>.*?<\/script>/is',
                '',
                $html
            );


        $html =
            preg_replace(
                '/<iframe\b[^>]*>.*?<\/iframe>/is',
                '',
                $html
            );


        $html =
            preg_replace(
                '/<object\b[^>]*>.*?<\/object>/is',
                '',
                $html
            );


        $html =
            preg_replace(
                '/<embed\b[^>]*>/is',
                '',
                $html
            );


        $html =
            preg_replace(
                '/\son\w+\s*=\s*("[^"]*"|\'[^\']*\'|[^\s>]+)/i',
                '',
                $html
            );


        $html =
            preg_replace(
                '/(<img\b[^>]*)(>)/i',
                '$1 style="max-width:100%;height:auto;"$2',
                $html
            );


        return $html;
    }


    return nl2br(
        htmlspecialchars(
            trim($plain),
            ENT_QUOTES,
            'UTF-8'
        )
    );
}


/* =========================================================
   BUILD MAIL ENTRY
========================================================= */

function buildMailEntry(
    $imap,
    $header,
    int $number,
    string $folder,
    string $type,
    int $displayNumber = 0
): array {

    $seen = false;


    $overview =
        @imap_fetch_overview(
            $imap,
            (string)$number,
            0
        );


    if (
        is_array($overview) &&
        isset($overview[0])
    ) {

        $seen =
            !empty(
                $overview[0]->seen
            );
    }


    return [

        'number' =>
            $number,

        'display_number' =>
            $displayNumber > 0
                ? $displayNumber
                : $number,

        'folder' =>
            $folder,

        'type' =>
            $type,

        'subject' =>
            decodeMimeHeader(
                $header->subject
                ?? '(No Subject)'
            ),

        'from' =>
            getAddresses(
                $header,
                'from'
            ),

        'to' =>
            getAddresses(
                $header,
                'to'
            ),

        'date' =>
            $header->date
            ?? '',

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

        'seen' =>
            $seen
    ];
}


/* =========================================================
   CURRENT VIEW
========================================================= */

$view =
    strtolower(
        trim(
            (string)(
                $_GET['view']
                ?? 'inbox'
            )
        )
    );


if (
    $view !== 'sent'
) {

    $view = 'inbox';
}


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

$page =
    filter_input(
        INPUT_GET,
        'page',
        FILTER_VALIDATE_INT
    );


if (
    !$page ||
    $page < 1
) {

    $page = 1;
}


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

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


/*
|--------------------------------------------------------------------------
| Only Inbox uses NIN search.
|--------------------------------------------------------------------------
*/

if (
    $view === 'sent'
) {

    $ninSearch = '';
}


/* =========================================================
   SELECTED EMAIL
========================================================= */

$selectedEmail =
    isset($_GET['email'])
        ? (int)$_GET['email']
        : 0;


/* =========================================================
   TOTAL INBOX EMAILS
========================================================= */

$totalInboxEmails =
    (int)imap_num_msg(
        $inbox
    );


/* =========================================================
   UNREAD COUNT
========================================================= */

$unreadInboxEmails = 0;


$unreadMessages =
    @imap_search(
        $inbox,
        'UNSEEN'
    );


if (
    $unreadMessages !== false &&
    is_array($unreadMessages)
) {

    $unreadInboxEmails =
        count(
            $unreadMessages
        );
}


/* =========================================================
   INBOX MESSAGE NUMBERS
========================================================= */

$inboxMessageNumbers = [];


/*
|--------------------------------------------------------------------------
| SEARCH INBOX BY NIN
|--------------------------------------------------------------------------
|
| IMAP TEXT searches the message subject and body.
|
*/

if (
    $ninSearch !== ''
) {

    /*
     * Keep search safe for IMAP SEARCH syntax.
     */
    $safeNin =
        preg_replace(
            '/[^0-9A-Za-z@._+\- ]/',
            '',
            $ninSearch
        );


    $safeNin =
        trim(
            (string)$safeNin
        );


    if (
        $safeNin !== ''
    ) {

        /*
         * Search entire message.
         */
        $searchQuery =
            'TEXT "' .
            addcslashes(
                $safeNin,
                '\\"'
            ) .
            '"';


        $searchResult =
            @imap_search(
                $inbox,
                $searchQuery,
                SE_UID
            );


        /*
         * IMPORTANT:
         *
         * SE_UID returns UIDs, while our display/open
         * functions use message numbers.
         *
         * Convert UID to message numbers.
         */
        if (
            $searchResult !== false &&
            is_array($searchResult)
        ) {

            foreach (
                $searchResult as $uid
            ) {

                $msgNo =
                    @imap_msgno(
                        $inbox,
                        (int)$uid
                    );


                if (
                    $msgNo > 0
                ) {

                    $inboxMessageNumbers[] =
                        $msgNo;
                }
            }
        }
    }

} else {

    /*
     * Normal Inbox.
     *
     * Newest email is message number $totalInboxEmails.
     */
    for (
        $i = $totalInboxEmails;
        $i >= 1;
        $i--
    ) {

        $inboxMessageNumbers[] =
            $i;
    }
}


/* =========================================================
   REMOVE DUPLICATES
========================================================= */

$inboxMessageNumbers =
    array_values(
        array_unique(
            $inboxMessageNumbers
        )
    );


/* =========================================================
   SORT NEWEST FIRST
========================================================= */

rsort(
    $inboxMessageNumbers,
    SORT_NUMERIC
);


/* =========================================================
   SEARCH RESULT COUNT
========================================================= */

$inboxResultCount =
    count(
        $inboxMessageNumbers
    );


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

$inboxTotalPages =
    max(
        1,
        (int)ceil(
            $inboxResultCount /
            $perPage
        )
    );


if (
    $page > $inboxTotalPages
) {

    $page =
        $inboxTotalPages;
}


/* =========================================================
   INBOX OFFSET
========================================================= */

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


/* =========================================================
   CURRENT INBOX MESSAGE NUMBERS
========================================================= */

$currentInboxNumbers =
    array_slice(
        $inboxMessageNumbers,
        $inboxOffset,
        $perPage
    );


/* =========================================================
   INBOX LIST
========================================================= */

$inboxEmails = [];


foreach (
    $currentInboxNumbers as $number
) {

    $header =
        @imap_headerinfo(
            $inbox,
            $number
        );


    if (!$header) {
        continue;
    }


    /*
     * Original position:
     *
     * newest = 1
     * second newest = 2
     * etc.
     */
    $displayNumber =
        $totalInboxEmails -
        $number +
        1;


    $inboxEmails[] =
        buildMailEntry(
            $inbox,
            $header,
            $number,
            'INBOX',
            'incoming',
            $displayNumber
        );
}


/* =========================================================
   SENT CONNECTION
========================================================= */

$sent = null;

$sentEmails = [];

$totalSentEmails = 0;

$sentTotalPages = 1;

$currentSentNumbers = [];


if (
    $sentFolder !== null
) {

    $sent =
        connectFolder(
            $imapServer,
            $imapPort,
            $mailboxEmail,
            $mailboxPassword,
            $sentFolder
        );


    if ($sent) {

        $totalSentEmails =
            (int)imap_num_msg(
                $sent
            );


        $sentTotalPages =
            max(
                1,
                (int)ceil(
                    $totalSentEmails /
                    $perPage
                )
            );


        /*
         * If viewing Sent, make sure page is valid.
         */
        if (
            $view === 'sent' &&
            $page > $sentTotalPages
        ) {

            $page =
                $sentTotalPages;
        }


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


        /*
         * Newest first.
         */
        for (
            $i = $totalSentEmails;
            $i >= 1 &&
            count($currentSentNumbers) < $perPage;
            $i--
        ) {

            /*
             * Skip until page offset.
             */
            static $sentCounter = 0;

            /*
             * This static approach is not suitable for
             * resetting after each loop, so actual pagination
             * is handled below.
             */
        }


        $allSentNumbers = [];


        for (
            $i = $totalSentEmails;
            $i >= 1;
            $i--
        ) {

            $allSentNumbers[] =
                $i;
        }


        $currentSentNumbers =
            array_slice(
                $allSentNumbers,
                (
                    $page - 1
                ) * $perPage,
                $perPage
            );


        foreach (
            $currentSentNumbers as $number
        ) {

            $header =
                @imap_headerinfo(
                    $sent,
                    $number
                );


            if (!$header) {
                continue;
            }


            /*
             * Newest sent email = 1.
             */
            $displayNumber =
                $totalSentEmails -
                $number +
                1;


            $sentEmails[] =
                buildMailEntry(
                    $sent,
                    $header,
                    $number,
                    $sentFolder,
                    'sent',
                    $displayNumber
                );
        }
    }
}


/* =========================================================
   OPEN INBOX EMAIL
========================================================= */

$openedEmail = null;


if (
    $selectedEmail > 0 &&
    $view === 'inbox' &&
    $selectedEmail <= $totalInboxEmails
) {

    /*
     * Mark permanently as READ.
     */
    @imap_setflag_full(
        $inbox,
        (string)$selectedEmail,
        "\\Seen"
    );


    /*
     * Refresh/check overview.
     */
    @imap_expunge(
        $inbox
    );


    $header =
        @imap_headerinfo(
            $inbox,
            $selectedEmail
        );


    if ($header) {

        $openedEmail = [

            'type' =>
                'incoming',

            'number' =>
                $selectedEmail,

            'display_number' =>
                $totalInboxEmails -
                $selectedEmail +
                1,

            'subject' =>
                decodeMimeHeader(
                    $header->subject
                    ?? '(No Subject)'
                ),

            'from' =>
                getAddresses(
                    $header,
                    'from'
                ),

            'to' =>
                getAddresses(
                    $header,
                    'to'
                ),

            'date' =>
                $header->date
                ?? '',

            'body' =>
                getEmailBody(
                    $inbox,
                    $selectedEmail
                )
        ];
    }
}


/* =========================================================
   OPEN SENT EMAIL
========================================================= */

if (
    $selectedEmail > 0 &&
    $view === 'sent' &&
    $sent !== false &&
    $sent !== null &&
    $selectedEmail <= $totalSentEmails
) {

    $header =
        @imap_headerinfo(
            $sent,
            $selectedEmail
        );


    if ($header) {

        $openedEmail = [

            'type' =>
                'sent',

            'number' =>
                $selectedEmail,

            'display_number' =>
                $totalSentEmails -
                $selectedEmail +
                1,

            'subject' =>
                decodeMimeHeader(
                    $header->subject
                    ?? '(No Subject)'
                ),

            'from' =>
                getAddresses(
                    $header,
                    'from'
                ),

            'to' =>
                getAddresses(
                    $header,
                    'to'
                ),

            'date' =>
                $header->date
                ?? '',

            'body' =>
                getEmailBody(
                    $sent,
                    $selectedEmail
                )
        ];
    }
}


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

function pageUrl(
    string $view,
    int $page,
    string $nin = ''
): string {

    $params = [

        'view' =>
            $view,

        'page' =>
            $page
    ];


    if (
        $view === 'inbox' &&
        $nin !== ''
    ) {

        $params['nin'] =
            $nin;
    }


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


/* =========================================================
   CLOSE SENT
========================================================= */

if ($sent) {

    @imap_close(
        $sent
    );
}

?>
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<meta
    name="theme-color"
    content="#0757c9"
>

<title>
ASOVERIFY Mail
</title>


<style>

/* =========================================================
   RESET
========================================================= */

* {
    box-sizing: border-box;
}


html {
    -webkit-text-size-adjust: 100%;
}


body {

    margin: 0;

    padding: 0;

    min-height: 100vh;

    background:
        #f4f7fb;

    color:
        #172033;

    font-family:
        Inter,
        -apple-system,
        BlinkMacSystemFont,
        "Segoe UI",
        Roboto,
        Arial,
        Helvetica,
        sans-serif;
}


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

.header {

    position: relative;

    overflow: hidden;

    color: white;

    padding: 21px 20px;

    background:
        linear-gradient(
            135deg,
            #063b91 0%,
            #0757c9 50%,
            #087ee8 100%
        );
}


.header::after {

    content: "";

    position: absolute;

    width: 190px;

    height: 190px;

    right: -80px;

    top: -100px;

    border-radius: 50%;

    background:
        rgba(255,255,255,.10);
}


.header-content {

    max-width: 1150px;

    margin: 0 auto;

    position: relative;

    z-index: 2;
}


.header-top {

    display: flex;

    align-items: center;

    justify-content: space-between;

    gap: 15px;
}


.brand {

    display: flex;

    align-items: center;

    gap: 13px;

    min-width: 0;
}


.brand-icon {

    width: 48px;

    height: 48px;

    min-width: 48px;

    display: flex;

    align-items: center;

    justify-content: center;

    border-radius: 14px;

    background:
        rgba(255,255,255,.16);

    font-size: 23px;
}


.header h1 {

    margin: 0;

    font-size: 22px;

    font-weight: 800;
}


.header p {

    margin: 4px 0 0;

    opacity: .82;

    font-size: 12px;

    white-space: nowrap;

    overflow: hidden;

    text-overflow: ellipsis;

    max-width: 400px;
}


.mail-status {

    display: flex;

    align-items: center;

    gap: 7px;

    padding: 8px 12px;

    border: 1px solid
        rgba(255,255,255,.16);

    border-radius: 999px;

    background:
        rgba(255,255,255,.13);

    font-size: 10px;

    font-weight: 700;

    white-space: nowrap;
}


.status-dot {

    width: 8px;

    height: 8px;

    border-radius: 50%;

    background: #4ade80;

    box-shadow:
        0 0 0 4px
        rgba(74,222,128,.15);
}


/* =========================================================
   NAVIGATION
========================================================= */

.mail-nav {

    position: sticky;

    top: 0;

    z-index: 50;

    background:
        rgba(255,255,255,.97);

    border-bottom:
        1px solid #e6eaf0;

    box-shadow:
        0 2px 12px
        rgba(15,23,42,.04);
}


.nav-inner {

    max-width: 1150px;

    margin: 0 auto;

    padding: 10px 15px;

    display: flex;

    gap: 8px;
}


.nav-button {

    min-height: 42px;

    padding: 8px 15px;

    display: flex;

    align-items: center;

    justify-content: center;

    gap: 7px;

    text-decoration: none;

    border: 1px solid transparent;

    border-radius: 11px;

    font-size: 13px;

    font-weight: 750;
}


.nav-inbox {

    background: #eff6ff;

    color: #0757c9;
}


.nav-sent {

    background: #f5f3ff;

    color: #6d28d9;
}


.nav-button.active {

    box-shadow:
        0 0 0 2px
        rgba(7,87,201,.12);
}


.nav-count {

    min-width: 23px;

    height: 23px;

    padding: 0 6px;

    display: inline-flex;

    align-items: center;

    justify-content: center;

    border-radius: 999px;

    background: #0757c9;

    color: white;

    font-size: 10px;
}


.sent-count {

    background: #7c3aed;
}


/* =========================================================
   MAIN
========================================================= */

.container {

    width: 100%;

    max-width: 1150px;

    margin: 24px auto;

    padding: 0 15px 40px;
}


/* =========================================================
   PAGE HEADING
========================================================= */

.page-heading {

    display: flex;

    align-items: flex-end;

    justify-content: space-between;

    gap: 15px;

    margin-bottom: 14px;
}


.page-heading h2 {

    margin: 0;

    font-size: 20px;
}


.page-heading p {

    margin: 5px 0 0;

    color: #718096;

    font-size: 12px;
}


.mail-summary {

    color: #64748b;

    font-size: 12px;
}


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

.search-box {

    margin-bottom: 14px;

    padding: 14px;

    background: #fff;

    border:
        1px solid #e7ebf0;

    border-radius: 16px;

    box-shadow:
        0 6px 24px
        rgba(15,23,42,.05);
}


.search-title {

    margin-bottom: 9px;

    color: #334155;

    font-size: 12px;

    font-weight: 800;
}


.search-form {

    display: flex;

    gap: 8px;

    width: 100%;
}


.search-input {

    flex: 1;

    min-width: 0;

    height: 43px;

    padding: 10px 13px;

    border:
        1px solid #d9e1ea;

    border-radius: 11px;

    background: #f8fafc;

    color: #172033;

    font-size: 13px;

    outline: none;
}


.search-input:focus {

    border-color: #087ee8;

    background: #fff;

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


.search-btn {

    height: 43px;

    padding: 0 17px;

    border: none;

    border-radius: 11px;

    background: #0757c9;

    color: #fff;

    font-weight: 800;

    cursor: pointer;
}


.clear-btn {

    height: 43px;

    padding: 0 14px;

    border:
        1px solid #d5dde7;

    border-radius: 11px;

    background: #fff;

    color: #475569;

    text-decoration: none;

    display: inline-flex;

    align-items: center;

    justify-content: center;

    font-size: 12px;

    font-weight: 750;
}


.search-result {

    margin-top: 10px;

    padding: 9px 11px;

    border-radius: 10px;

    background: #eff6ff;

    color: #0757c9;

    font-size: 11px;

    font-weight: 700;
}


/* =========================================================
   UNREAD
========================================================= */

.unread-count {

    display: inline-flex;

    align-items: center;

    gap: 5px;

    padding: 6px 10px;

    border-radius: 999px;

    background: #eff6ff;

    color: #0757c9;

    font-weight: 750;
}


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

.card {

    background: #fff;

    border:
        1px solid #e7ebf0;

    border-radius: 18px;

    overflow: hidden;

    box-shadow:
        0 8px 30px
        rgba(15,23,42,.07);
}


/* =========================================================
   MAIL ITEM
========================================================= */

.mail-item {

    position: relative;

    display: block;

    padding: 15px 17px;

    color: inherit;

    text-decoration: none;

    background: #fff;

    border-bottom:
        1px solid #edf0f4;
}


.mail-item:last-child {

    border-bottom: 0;
}


.mail-item:hover {

    background: #f8fafc;
}


/* =========================================================
   NUMBER
========================================================= */

.mail-number {

    width: 35px;

    height: 35px;

    min-width: 35px;

    display: flex;

    align-items: center;

    justify-content: center;

    border-radius: 10px;

    font-size: 11px;

    font-weight: 800;
}


/* READ */

.mail-item.read {

    padding-left: 13px;

    border-left:
        4px solid #16a34a;

    background: #fff;
}


.mail-item.read .mail-number {

    background: #ecfdf3;

    color: #15803d;

    border:
        1px solid #d1fae5;
}


.mail-item.read .mail-icon {

    background: #ecfdf3;

    color: #16a34a;
}


.mail-item.read .mail-subject {

    color: #166534;
}


/* UNREAD */

.mail-item.unread {

    padding-left: 13px;

    border-left:
        4px solid #087ee8;

    background: #eff7ff;
}


.mail-item.unread .mail-number {

    background: #dbeafe;

    color: #0757c9;

    border:
        1px solid #bfdbfe;
}


.mail-item.unread .mail-icon {

    background: #dbeafe;

    color: #0757c9;
}


.mail-item.unread .mail-subject {

    color: #0757c9;

    font-weight: 800;
}


/* =========================================================
   MAIL ROW
========================================================= */

.mail-row {

    display: flex;

    align-items: flex-start;

    gap: 10px;

    min-width: 0;
}


.mail-icon {

    width: 40px;

    height: 40px;

    min-width: 40px;

    display: flex;

    align-items: center;

    justify-content: center;

    border-radius: 11px;

    font-size: 17px;
}


.mail-content {

    flex: 1;

    min-width: 0;
}


.mail-top {

    display: flex;

    align-items: flex-start;

    justify-content: space-between;

    gap: 10px;

    min-width: 0;
}


.mail-subject {

    min-width: 0;

    margin-bottom: 5px;

    font-size: 13px;

    font-weight: 700;

    line-height: 1.4;

    overflow: hidden;

    text-overflow: ellipsis;

    white-space: nowrap;
}


.mail-date {

    flex-shrink: 0;

    color: #7b8794;

    font-size: 9px;

    white-space: nowrap;
}


.mail-from {

    color: #526174;

    font-size: 11px;

    line-height: 1.5;

    overflow: hidden;

    text-overflow: ellipsis;

    white-space: nowrap;
}


.mail-preview {

    margin-top: 4px;

    color: #8a96a5;

    font-size: 10px;

    overflow: hidden;

    text-overflow: ellipsis;

    white-space: nowrap;
}


/* =========================================================
   BADGES
========================================================= */

.badge {

    display: inline-flex;

    align-items: center;

    justify-content: center;

    padding: 3px 7px;

    margin-left: 4px;

    vertical-align: middle;

    border-radius: 999px;

    font-size: 8px;

    font-weight: 800;
}


.badge-new {

    color: #fff;

    background: #087ee8;
}


.badge-read {

    color: #15803d;

    background: #dcfce7;
}


.badge-sent {

    color: #6d28d9;

    background: #ede9fe;
}


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

.pagination {

    display: flex;

    align-items: center;

    justify-content: center;

    flex-wrap: wrap;

    gap: 6px;

    padding: 17px 12px;

    background: #fff;

    border-top:
        1px solid #edf0f4;
}


.page-link {

    min-width: 35px;

    height: 35px;

    padding: 0 9px;

    display: inline-flex;

    align-items: center;

    justify-content: center;

    border:
        1px solid #dbe2ea;

    border-radius: 9px;

    background: #fff;

    color: #475569;

    text-decoration: none;

    font-size: 11px;

    font-weight: 750;
}


.page-link:hover {

    background: #eff6ff;

    color: #0757c9;

    border-color: #bfdbfe;
}


.page-link.active {

    background: #0757c9;

    color: #fff;

    border-color: #0757c9;
}


.page-info {

    width: 100%;

    text-align: center;

    margin-bottom: 6px;

    color: #64748b;

    font-size: 10px;

    font-weight: 700;
}


/* =========================================================
   OPENED EMAIL
========================================================= */

.opened {

    padding: 24px;
}


.back {

    display: inline-flex;

    align-items: center;

    gap: 7px;

    margin-bottom: 20px;

    padding: 8px 11px;

    border-radius: 9px;

    color: #0757c9;

    background: #eff6ff;

    text-decoration: none;

    font-size: 13px;

    font-weight: 750;
}


.email-type {

    display: inline-flex;

    align-items: center;

    gap: 6px;

    padding: 6px 10px;

    margin-bottom: 12px;

    border-radius: 999px;

    font-size: 9px;

    font-weight: 800;
}


.email-type.incoming {

    color: #15803d;

    background: #dcfce7;
}


.email-type.sent {

    color: #6d28d9;

    background: #ede9fe;
}


.opened h2 {

    margin: 0;

    color: #172033;

    font-size: 24px;

    line-height: 1.35;

    overflow-wrap: anywhere;
}


/* =========================================================
   EMAIL META
========================================================= */

.meta {

    margin-top: 20px;

    margin-bottom: 22px;

    padding: 15px 16px;

    background: #f8fafc;

    border:
        1px solid #e8edf3;

    border-radius: 13px;
}


.meta-row {

    display: flex;

    gap: 10px;

    padding: 6px 0;

    font-size: 13px;

    line-height: 1.5;
}


.meta-label {

    width: 55px;

    flex-shrink: 0;

    color: #64748b;

    font-weight: 700;
}


.meta-value {

    color: #334155;

    overflow-wrap: anywhere;
}


/* =========================================================
   BODY
========================================================= */

.body {

    padding: 5px 2px;

    color: #263244;

    font-size: 14px;

    line-height: 1.75;

    overflow-x: auto;

    word-wrap: break-word;

    overflow-wrap: anywhere;
}


.body img {

    max-width: 100% !important;

    height: auto !important;
}


.body table {

    max-width: 100% !important;
}


.body pre {

    max-width: 100%;

    overflow-x: auto;

    white-space: pre-wrap;

    word-break: break-word;
}


.body iframe,
.body object,
.body embed {

    display: none !important;
}


.body a {

    overflow-wrap: anywhere;
}


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

.empty {

    padding: 65px 20px;

    text-align: center;

    color: #64748b;
}


.empty-icon {

    width: 70px;

    height: 70px;

    display: flex;

    align-items: center;

    justify-content: center;

    margin: 0 auto 15px;

    border-radius: 20px;

    background: #f1f5f9;

    font-size: 30px;
}


.empty h3 {

    margin: 0 0 8px;

    color: #334155;

    font-size: 17px;
}


.empty p {

    margin: 0;

    font-size: 13px;

    line-height: 1.6;
}


/* =========================================================
   WARNING
========================================================= */

.warning {

    margin-top: 15px;

    padding: 14px 16px;

    border:
        1px solid #fed7aa;

    border-radius: 12px;

    background: #fff7ed;

    color: #9a3412;

    font-size: 12px;

    line-height: 1.6;
}


/* =========================================================
   REFRESH
========================================================= */

.refresh-wrapper {

    display: flex;

    justify-content: flex-end;

    margin-top: 15px;
}


.refresh {

    min-height: 40px;

    display: inline-flex;

    align-items: center;

    justify-content: center;

    gap: 7px;

    padding: 10px 14px;

    border:
        1px solid #cbd5e1;

    border-radius: 10px;

    background: #fff;

    color: #0757c9;

    text-decoration: none;

    font-size: 12px;

    font-weight: 700;
}


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

@media (max-width: 700px) {

    .header {

        padding: 16px 13px;
    }


    .header-top {

        align-items: flex-start;
    }


    .brand-icon {

        width: 43px;

        height: 43px;

        min-width: 43px;

        border-radius: 12px;

        font-size: 20px;
    }


    .header h1 {

        font-size: 18px;
    }


    .header p {

        max-width: 220px;

        font-size: 10px;
    }


    .mail-status {

        padding: 7px 9px;

        font-size: 9px;
    }


    .nav-inner {

        padding: 8px 10px;
    }


    .nav-button {

        flex: 1;

        min-height: 42px;

        padding: 8px 10px;

        font-size: 12px;
    }


    .container {

        margin: 14px auto;

        padding: 0 9px 30px;
    }


    .page-heading {

        align-items: flex-start;

        flex-direction: column;

        gap: 8px;

        margin-bottom: 10px;
    }


    .page-heading h2 {

        font-size: 18px;
    }


    .search-form {

        flex-wrap: wrap;
    }


    .search-input {

        flex-basis: 100%;

        width: 100%;
    }


    .search-btn,
    .clear-btn {

        flex: 1;
    }


    .card {

        border-radius: 14px;
    }


    .mail-item {

        padding: 13px 9px;
    }


    .mail-item.read,
    .mail-item.unread {

        padding-left: 6px;
    }


    .mail-row {

        gap: 7px;
    }


    .mail-number {

        width: 32px;

        height: 32px;

        min-width: 32px;

        font-size: 10px;
    }


    .mail-icon {

        width: 35px;

        height: 35px;

        min-width: 35px;

        border-radius: 9px;

        font-size: 15px;
    }


    .mail-top {

        display: block;
    }


    .mail-subject {

        white-space: normal;

        display: -webkit-box;

        -webkit-line-clamp: 2;

        -webkit-box-orient: vertical;

        font-size: 12px;
    }


    .mail-date {

        display: block;

        margin-top: 4px;

        font-size: 8px;
    }


    .mail-from {

        font-size: 10px;
    }


    .mail-preview {

        font-size: 9px;
    }


    .badge {

        font-size: 7px;

        padding: 3px 6px;
    }


    .opened {

        padding: 17px 14px;
    }


    .opened h2 {

        font-size: 19px;
    }


    .meta {

        padding: 11px 12px;

        margin-bottom: 17px;
    }


    .meta-row {

        display: block;

        padding: 5px 0;

        font-size: 12px;
    }


    .meta-label {

        display: block;

        width: auto;

        margin-bottom: 2px;

        font-size: 10px;

        text-transform: uppercase;

        letter-spacing: .3px;
    }


    .body {

        font-size: 13px;

        line-height: 1.65;
    }


    .refresh-wrapper {

        justify-content: stretch;
    }


    .refresh {

        width: 100%;
    }


    .warning {

        font-size: 11px;
    }

}


/* =========================================================
   VERY SMALL PHONES
========================================================= */

@media (max-width: 380px) {

    .mail-status span {

        display: none;
    }


    .header h1 {

        font-size: 17px;
    }


    .nav-button {

        font-size: 11px;

        gap: 5px;
    }


    .mail-number {

        width: 29px;

        height: 29px;

        min-width: 29px;
    }


    .mail-icon {

        width: 32px;

        height: 32px;

        min-width: 32px;
    }

}

</style>

</head>


<body>


<!-- =====================================================
     HEADER
====================================================== -->

<header class="header">

    <div class="header-content">

        <div class="header-top">

            <div class="brand">

                <div class="brand-icon">
                    ✉️
                </div>

                <div>

                    <h1>
                        ASOVERIFY Mail
                    </h1>

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

                </div>

            </div>


            <div class="mail-status">

                <span class="status-dot"></span>

                <span>
                    Mail Connected
                </span>

            </div>

        </div>

    </div>

</header>


<!-- =====================================================
     NAVIGATION
====================================================== -->

<nav class="mail-nav">

    <div class="nav-inner">

        <a
            href="inbox_val.php?view=inbox"
            class="nav-button nav-inbox
            <?= $view === 'inbox' ? 'active' : '' ?>"
        >

            <span>
                📥
            </span>

            <span>
                Inbox
            </span>

            <?php if (
                $totalInboxEmails > 0
            ): ?>

                <span class="nav-count">

                    <?= $totalInboxEmails ?>

                </span>

            <?php endif; ?>

        </a>


        <a
            href="inbox_val.php?view=sent"
            class="nav-button nav-sent
            <?= $view === 'sent' ? 'active' : '' ?>"
        >

            <span>
                📤
            </span>

            <span>
                Sent
            </span>

            <?php if (
                $totalSentEmails > 0
            ): ?>

                <span class="nav-count sent-count">

                    <?= $totalSentEmails ?>

                </span>

            <?php endif; ?>

        </a>

    </div>

</nav>


<!-- =====================================================
     MAIN
====================================================== -->

<main class="container">


<?php if (
    $openedEmail
): ?>


    <!-- =================================================
         OPENED EMAIL
    ================================================== -->

    <div class="card">

        <div class="opened">


            <a
                href="<?= e(
                    pageUrl(
                        $view,
                        $page,
                        $ninSearch
                    )
                ) ?>"
                class="back"
            >

                ←

                <span>

                    Back to

                    <?= $view === 'sent'
                        ? 'Sent'
                        : 'Inbox'
                    ?>

                </span>

            </a>


            <div class="opened-header">


                <?php if (
                    $openedEmail['type'] === 'sent'
                ): ?>

                    <div class="email-type sent">

                        📤

                        <span>
                            SENT EMAIL
                        </span>

                    </div>

                <?php else: ?>

                    <div class="email-type incoming">

                        🟢

                        <span>
                            READ EMAIL
                        </span>

                    </div>

                <?php endif; ?>


                <h2>

                    <?= e(
                        $openedEmail['subject']
                    ) ?>

                </h2>


            </div>


            <div class="meta">


                <div class="meta-row">

                    <div class="meta-label">
                        Number
                    </div>

                    <div class="meta-value">

                        #<?= (int)$openedEmail[
                            'display_number'
                        ] ?>

                    </div>

                </div>


                <div class="meta-row">

                    <div class="meta-label">
                        From
                    </div>

                    <div class="meta-value">

                        <?= e(
                            $openedEmail['from']
                        ) ?>

                    </div>

                </div>


                <div class="meta-row">

                    <div class="meta-label">
                        To
                    </div>

                    <div class="meta-value">

                        <?= e(
                            $openedEmail['to']
                        ) ?>

                    </div>

                </div>


                <div class="meta-row">

                    <div class="meta-label">
                        Date
                    </div>

                    <div class="meta-value">

                        <?= e(
                            $openedEmail['date']
                        ) ?>

                    </div>

                </div>


            </div>


            <div class="body">

                <?= $openedEmail['body'] ?>

            </div>


        </div>

    </div>


<?php else: ?>


    <!-- =================================================
         PAGE HEADING
    ================================================== -->

    <div class="page-heading">

        <div>

            <h2>

                <?= $view === 'sent'
                    ? 'Sent Mail'
                    : 'Inbox'
                ?>

            </h2>


            <p>

                <?php if (
                    $view === 'sent'
                ): ?>

                    Emails sent from this mailbox

                <?php elseif (
                    $ninSearch !== ''
                ): ?>

                    Search results for NIN

                <?php else: ?>

                    Incoming emails received by this mailbox

                <?php endif; ?>

            </p>

        </div>


        <?php if (
            $view === 'inbox'
        ): ?>

            <div class="mail-summary">

                <?php if (
                    $unreadInboxEmails > 0
                ): ?>

                    <span class="unread-count">

                        🔵

                        <?= $unreadInboxEmails ?>

                        unread

                    </span>

                <?php else: ?>

                    <span>
                        All emails read
                    </span>

                <?php endif; ?>

            </div>

        <?php endif; ?>


    </div>


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

    <?php if (
        $view === 'inbox'
    ): ?>

        <div class="search-box">

            <div class="search-title">

                🔎 Search Inbox by NIN

            </div>


            <form
                method="get"
                action="inbox_val.php"
                class="search-form"
            >

                <input
                    type="hidden"
                    name="view"
                    value="inbox"
                >


                <input
                    type="hidden"
                    name="page"
                    value="1"
                >


                <input
                    type="text"
                    name="nin"
                    class="search-input"
                    inputmode="numeric"
                    autocomplete="off"
                    placeholder="Enter NIN to search email subject and body"
                    value="<?= e($ninSearch) ?>"
                >


                <button
                    type="submit"
                    class="search-btn"
                >

                    🔎 Search

                </button>


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

                    <a
                        href="inbox_val.php?view=inbox"
                        class="clear-btn"
                    >

                        ✕ Clear

                    </a>

                <?php endif; ?>

            </form>


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

                <div class="search-result">

                    Found
                    <?= $inboxResultCount ?>
                    email(s) containing:

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

                </div>

            <?php endif; ?>

        </div>

    <?php endif; ?>


    <!-- =================================================
         MAIL CARD
    ================================================== -->

    <div class="card">


    <?php if (
        $view === 'sent'
    ): ?>


        <!-- =============================================
             SENT
        ============================================== -->

        <?php if (
            empty($sentEmails)
        ): ?>

            <div class="empty">

                <div class="empty-icon">
                    📤
                </div>

                <h3>
                    No Sent Emails
                </h3>

                <?php if (
                    $sentFolder === null
                ): ?>

                    <p>
                        The mail server did not expose
                        a recognizable Sent folder.
                    </p>

                <?php elseif (
                    $sent === false
                ): ?>

                    <p>
                        The Sent folder was found,
                        but the server did not allow
                        it to be opened.
                    </p>

                <?php else: ?>

                    <p>
                        There are no messages in the
                        Sent folder.
                    </p>

                <?php endif; ?>

            </div>


        <?php else: ?>


            <div class="mail-list">


            <?php foreach (
                $sentEmails as $mail
            ): ?>


                <?php

                $url =
                    'inbox_val.php?' .
                    http_build_query([
                        'view' =>
                            'sent',

                        'page' =>
                            $page,

                        'email' =>
                            (int)$mail['number']
                    ]);

                ?>


                <a
                    href="<?= e($url) ?>"
                    class="mail-item read"
                >

                    <div class="mail-row">


                        <div class="mail-number">

                            <?= (int)$mail[
                                'display_number'
                            ] ?>

                        </div>


                        <div class="mail-icon">

                            📤

                        </div>


                        <div class="mail-content">


                            <div class="mail-top">


                                <div class="mail-subject">

                                    <?= e(
                                        $mail['subject']
                                    ) ?>


                                    <span class="badge badge-sent">
                                        SENT
                                    </span>

                                </div>


                                <div class="mail-date">

                                    <?= e(
                                        $mail['date']
                                    ) ?>

                                </div>


                            </div>


                            <div class="mail-from">

                                <strong>
                                    To:
                                </strong>

                                <?= e(
                                    $mail['to']
                                ) ?>

                            </div>


                            <div class="mail-preview">

                                Sent message

                            </div>


                        </div>


                    </div>

                </a>


            <?php endforeach; ?>


            </div>


            <!-- SENT PAGINATION -->

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

                <div class="pagination">

                    <div class="page-info">

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

                        —
                        <?= $totalSentEmails ?>
                        sent emails

                    </div>


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

                        <a
                            href="<?= e(
                                pageUrl(
                                    'sent',
                                    $page - 1
                                )
                            ) ?>"
                            class="page-link"
                        >
                            ←
                        </a>

                    <?php endif; ?>


                    <?php

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


                    $endPage =
                        min(
                            $sentTotalPages,
                            $page + 2
                        );

                    ?>


                    <?php for (
                        $p = $startPage;
                        $p <= $endPage;
                        $p++
                    ): ?>

                        <a
                            href="<?= e(
                                pageUrl(
                                    'sent',
                                    $p
                                )
                            ) ?>"
                            class="page-link
                            <?= $p === $page
                                ? 'active'
                                : ''
                            ?>"
                        >

                            <?= $p ?>

                        </a>

                    <?php endfor; ?>


                    <?php if (
                        $page < $sentTotalPages
                    ): ?>

                        <a
                            href="<?= e(
                                pageUrl(
                                    'sent',
                                    $page + 1
                                )
                            ) ?>"
                            class="page-link"
                        >
                            →
                        </a>

                    <?php endif; ?>


                </div>

            <?php endif; ?>


        <?php endif; ?>


    <?php else: ?>


        <!-- =============================================
             INBOX
        ============================================== -->

        <?php if (
            empty($inboxEmails)
        ): ?>


            <div class="empty">

                <div class="empty-icon">
                    <?= $ninSearch !== ''
                        ? '🔎'
                        : '📭'
                    ?>
                </div>


                <h3>

                    <?= $ninSearch !== ''
                        ? 'No Matching Emails'
                        : 'No Incoming Emails'
                    ?>

                </h3>


                <p>

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

                        No inbox email was found
                        containing the searched NIN.

                    <?php else: ?>

                        Your inbox is currently empty.

                    <?php endif; ?>

                </p>

            </div>


        <?php else: ?>


            <div class="mail-list">


            <?php foreach (
                $inboxEmails as $mail
            ): ?>


                <?php

                $urlParams = [

                    'view' =>
                        'inbox',

                    'page' =>
                        $page,

                    'email' =>
                        (int)$mail['number']
                ];


                if (
                    $ninSearch !== ''
                ) {

                    $urlParams['nin'] =
                        $ninSearch;
                }


                $url =
                    'inbox_val.php?' .
                    http_build_query(
                        $urlParams
                    );

                ?>


                <a
                    href="<?= e($url) ?>"
                    class="mail-item
                    <?= $mail['seen']
                        ? 'read'
                        : 'unread'
                    ?>"
                >


                    <div class="mail-row">


                        <!-- EMAIL NUMBER -->

                        <div class="mail-number">

                            <?= (int)$mail[
                                'display_number'
                            ] ?>

                        </div>


                        <!-- ICON -->

                        <div class="mail-icon">

                            <?php if (
                                $mail['seen']
                            ): ?>

                                ✉️

                            <?php else: ?>

                                📩

                            <?php endif; ?>

                        </div>


                        <!-- CONTENT -->

                        <div class="mail-content">


                            <div class="mail-top">


                                <div class="mail-subject">

                                    <?= e(
                                        $mail['subject']
                                    ) ?>


                                    <?php if (
                                        !$mail['seen']
                                    ): ?>

                                        <span class="badge badge-new">
                                            NEW
                                        </span>

                                    <?php else: ?>

                                        <span class="badge badge-read">
                                            READ
                                        </span>

                                    <?php endif; ?>


                                </div>


                                <div class="mail-date">

                                    <?= e(
                                        $mail['date']
                                    ) ?>

                                </div>


                            </div>


                            <div class="mail-from">

                                <strong>
                                    From:
                                </strong>

                                <?= e(
                                    $mail['from']
                                ) ?>

                            </div>


                            <div class="mail-preview">

                                <?php if (
                                    $mail['seen']
                                ): ?>

                                    Read email

                                <?php else: ?>

                                    New unread message

                                <?php endif; ?>


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

                                    · NIN match

                                <?php endif; ?>

                            </div>


                        </div>


                    </div>


                </a>


            <?php endforeach; ?>


            </div>


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

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


                <div class="pagination">


                    <div class="page-info">

                        <?php

                        $firstNumber =
                            (
                                $page - 1
                            ) *
                            $perPage +
                            1;


                        $lastNumber =
                            min(
                                $page * $perPage,
                                $inboxResultCount
                            );

                        ?>


                        Showing

                        <?= $firstNumber ?>

                        -

                        <?= $lastNumber ?>

                        of

                        <?= $inboxResultCount ?>

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

                            matching emails

                        <?php else: ?>

                            inbox emails

                        <?php endif; ?>


                    </div>


                    <!-- PREVIOUS -->

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

                        <a
                            href="<?= e(
                                pageUrl(
                                    'inbox',
                                    $page - 1,
                                    $ninSearch
                                )
                            ) ?>"
                            class="page-link"
                        >

                            ←

                        </a>

                    <?php endif; ?>


                    <?php

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


                    $endPage =
                        min(
                            $inboxTotalPages,
                            $page + 2
                        );

                    ?>


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

                        <a
                            href="<?= e(
                                pageUrl(
                                    'inbox',
                                    1,
                                    $ninSearch
                                )
                            ) ?>"
                            class="page-link"
                        >
                            1
                        </a>


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

                            <span>
                                ...
                            </span>

                        <?php endif; ?>

                    <?php endif; ?>


                    <?php for (
                        $p = $startPage;
                        $p <= $endPage;
                        $p++
                    ): ?>

                        <a
                            href="<?= e(
                                pageUrl(
                                    'inbox',
                                    $p,
                                    $ninSearch
                                )
                            ) ?>"
                            class="page-link
                            <?= $p === $page
                                ? 'active'
                                : ''
                            ?>"
                        >

                            <?= $p ?>

                        </a>

                    <?php endfor; ?>


                    <?php if (
                        $endPage < $inboxTotalPages
                    ): ?>


                        <?php if (
                            $endPage <
                            $inboxTotalPages - 1
                        ): ?>

                            <span>
                                ...
                            </span>

                        <?php endif; ?>


                        <a
                            href="<?= e(
                                pageUrl(
                                    'inbox',
                                    $inboxTotalPages,
                                    $ninSearch
                                )
                            ) ?>"
                            class="page-link"
                        >

                            <?= $inboxTotalPages ?>

                        </a>


                    <?php endif; ?>


                    <!-- NEXT -->

                    <?php if (
                        $page < $inboxTotalPages
                    ): ?>

                        <a
                            href="<?= e(
                                pageUrl(
                                    'inbox',
                                    $page + 1,
                                    $ninSearch
                                )
                            ) ?>"
                            class="page-link"
                        >

                            →

                        </a>

                    <?php endif; ?>


                </div>


            <?php endif; ?>


        <?php endif; ?>


    <?php endif; ?>


    </div>


<?php endif; ?>


<!-- =====================================================
     SENT FOLDER WARNING
====================================================== -->

<?php if (
    $sentFolder === null
): ?>

    <div class="warning">

        ⚠️

        <strong>
            Sent folder not detected:
        </strong>

        The server did not expose a recognizable
        Sent folder.

    </div>

<?php endif; ?>


<!-- =====================================================
     REFRESH
====================================================== -->

<div class="refresh-wrapper">

    <a
        href="<?= e(
            pageUrl(
                $view,
                $page,
                $ninSearch
            )
        ) ?>"
        class="refresh"
    >

        🔄

        <span>
            Refresh Mail
        </span>

    </a>

</div>


</main>


</body>

</html>


<?php

/* =========================================================
   CLOSE INBOX
========================================================= */

@imap_close(
    $inbox
);

?>