<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| ASOVERIFY ADMIN AGENT MANAGER
|--------------------------------------------------------------------------
| File:
|   /admin/admin_agent.php
|
| ADMIN SESSION:
|   $_SESSION['admin']
|
| TABLES:
|   aso_agents
|   aso_agent_customers
|   aso_agent_transactions
|   aso_agent_wallet
|   aso_agent_wallet_logs
|   aso_agent_withdrawals
|   aso_agent_competition_settings
|   aso_agent_competition_months
|   aso_agent_competition_winners
|--------------------------------------------------------------------------
*/

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

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

require_once __DIR__ . '/db.php';

if (!isset($conn) || !($conn instanceof mysqli)) {
    die('Database connection error.');
}

$conn->set_charset('utf8mb4');


/* =========================================================================
   ADMIN AUTHENTICATION
========================================================================= */

if (!isset($_SESSION['admin'])) {
    http_response_code(403);
    die('Access denied');
}


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

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

function money(float $amount): string
{
    return '₦' . number_format(
        $amount,
        2
    );
}

function json_response(array $data): never
{
    while (ob_get_level() > 0) {
        @ob_end_clean();
    }

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

    echo json_encode(
        $data,
        JSON_UNESCAPED_UNICODE |
        JSON_UNESCAPED_SLASHES
    );

    exit;
}

function table_exists(
    mysqli $conn,
    string $table
): bool {

    $table = $conn->real_escape_string($table);

    $result = $conn->query(
        "SHOW TABLES LIKE '{$table}'"
    );

    return
        $result instanceof mysqli_result &&
        $result->num_rows > 0;
}

function column_exists(
    mysqli $conn,
    string $table,
    string $column
): bool {

    if (!table_exists($conn, $table)) {
        return false;
    }

    $tableSafe = str_replace(
        '`',
        '``',
        $table
    );

    $columnSafe =
        $conn->real_escape_string($column);

    $result = $conn->query(
        "SHOW COLUMNS FROM `{$tableSafe}`
         LIKE '{$columnSafe}'"
    );

    return
        $result instanceof mysqli_result &&
        $result->num_rows > 0;
}

function fetch_one(
    mysqli $conn,
    string $sql,
    string $types = '',
    array $params = []
): ?array {

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

    if (!$stmt) {
        return null;
    }

    if ($types !== '') {
        $stmt->bind_param(
            $types,
            ...$params
        );
    }

    if (!$stmt->execute()) {
        $stmt->close();
        return null;
    }

    $result = $stmt->get_result();

    $row =
        $result
            ? $result->fetch_assoc()
            : null;

    $stmt->close();

    return $row ?: null;
}

function fetch_all_rows(
    mysqli $conn,
    string $sql,
    string $types = '',
    array $params = []
): array {

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

    if (!$stmt) {
        return [];
    }

    if ($types !== '') {
        $stmt->bind_param(
            $types,
            ...$params
        );
    }

    if (!$stmt->execute()) {
        $stmt->close();
        return [];
    }

    $result = $stmt->get_result();

    $rows = [];

    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }
    }

    $stmt->close();

    return $rows;
}

function successful_status_sql(
    string $column = 'status'
): string {

    return "
        (
            TRIM(COALESCE({$column}, '')) = ''
            OR LOWER(TRIM({$column})) IN
            (
                'success',
                'successful',
                'approved',
                'completed',
                'complete',
                'done',
                'paid'
            )
        )
    ";
}

function current_month(): string
{
    return date('Y-m');
}

function month_start(string $month): string
{
    if (!preg_match('/^\d{4}-\d{2}$/', $month)) {
        return date('Y-m-01 00:00:00');
    }

    return $month . '-01 00:00:00';
}

function next_month_start(string $month): string
{
    $date = DateTime::createFromFormat(
        'Y-m-d H:i:s',
        month_start($month)
    );

    if (!$date) {
        $date = new DateTime(
            'first day of this month'
        );
    }

    $date->modify('+1 month');

    return $date->format(
        'Y-m-d H:i:s'
    );
}


/* =========================================================================
   COMPETITION SETTINGS
========================================================================= */

function get_competition_settings(
    mysqli $conn
): array {

    $defaults = [
        'target_transactions' => 3000,
        'prize_1' => 20000,
        'prize_2' => 15000,
        'prize_3' => 10000
    ];

    if (!table_exists(
        $conn,
        'aso_agent_competition_settings'
    )) {
        return $defaults;
    }

    $row = fetch_one(
        $conn,
        "SELECT *
         FROM aso_agent_competition_settings
         ORDER BY id ASC
         LIMIT 1"
    );

    if (!$row) {

        if (
            column_exists(
                $conn,
                'aso_agent_competition_settings',
                'target_transactions'
            ) &&
            column_exists(
                $conn,
                'aso_agent_competition_settings',
                'prize_1'
            ) &&
            column_exists(
                $conn,
                'aso_agent_competition_settings',
                'prize_2'
            ) &&
            column_exists(
                $conn,
                'aso_agent_competition_settings',
                'prize_3'
            )
        ) {

            $stmt = $conn->prepare(
                "INSERT INTO
                 aso_agent_competition_settings
                 (
                    target_transactions,
                    prize_1,
                    prize_2,
                    prize_3
                 )
                 VALUES (?, ?, ?, ?)"
            );

            if ($stmt) {

                $target = 3000;
                $p1 = 20000.0;
                $p2 = 15000.0;
                $p3 = 10000.0;

                $stmt->bind_param(
                    'iddd',
                    $target,
                    $p1,
                    $p2,
                    $p3
                );

                $stmt->execute();
                $stmt->close();
            }
        }

        return $defaults;
    }

    return [
        'target_transactions' =>
            max(
                1,
                (int)(
                    $row['target_transactions']
                    ?? 3000
                )
            ),

        'prize_1' =>
            (float)(
                $row['prize_1']
                ?? 20000
            ),

        'prize_2' =>
            (float)(
                $row['prize_2']
                ?? 15000
            ),

        'prize_3' =>
            (float)(
                $row['prize_3']
                ?? 10000
            )
    ];
}

$settings =
    get_competition_settings($conn);


/* =========================================================================
   WALLET
========================================================================= */

function wallet_column(
    mysqli $conn
): ?string {

    if (!table_exists(
        $conn,
        'aso_agent_wallet'
    )) {
        return null;
    }

    foreach (
        [
            'balance',
            'amount',
            'wallet_balance'
        ] as $candidate
    ) {

        if (
            column_exists(
                $conn,
                'aso_agent_wallet',
                $candidate
            )
        ) {
            return $candidate;
        }
    }

    return null;
}

function get_agent_wallet(
    mysqli $conn,
    int $agentId
): float {

    $column =
        wallet_column($conn);

    if ($column !== null) {

        $safe =
            preg_replace(
                '/[^a-zA-Z0-9_]/',
                '',
                $column
            );

        $row = fetch_one(
            $conn,
            "SELECT `{$safe}` AS balance
             FROM aso_agent_wallet
             WHERE agent_id = ?
             LIMIT 1",
            'i',
            [$agentId]
        );

        if ($row) {
            return (float)$row['balance'];
        }
    }

    if (
        table_exists(
            $conn,
            'aso_agent_wallet_logs'
        )
    ) {

        $row = fetch_one(
            $conn,
            "SELECT
                COALESCE(
                    SUM(
                        CASE
                            WHEN LOWER(type) IN
                            (
                                'commission',
                                'competition_reward',
                                'reward',
                                'credit',
                                'registration_refund'
                            )
                            THEN amount
                            ELSE 0
                        END
                    ),
                    0
                )
                -
                COALESCE(
                    SUM(
                        CASE
                            WHEN LOWER(type) IN
                            (
                                'withdrawal',
                                'withdraw',
                                'registration_fee',
                                'debit'
                            )
                            THEN amount
                            ELSE 0
                        END
                    ),
                    0
                ) AS balance
             FROM aso_agent_wallet_logs
             WHERE agent_id = ?",
            'i',
            [$agentId]
        );

        return
            $row
                ? (float)$row['balance']
                : 0.0;
    }

    return 0.0;
}


/* =========================================================================
   AGENT STATISTICS
========================================================================= */

function agent_customer_count(
    mysqli $conn,
    int $agentId
): int {

    if (!table_exists(
        $conn,
        'aso_agent_customers'
    )) {
        return 0;
    }

    $row = fetch_one(
        $conn,
        "SELECT COUNT(*) AS total
         FROM aso_agent_customers
         WHERE agent_id = ?",
        'i',
        [$agentId]
    );

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

function agent_transaction_count(
    mysqli $conn,
    int $agentId,
    ?string $start = null,
    ?string $end = null
): int {

    if (!table_exists(
        $conn,
        'aso_agent_transactions'
    )) {
        return 0;
    }

    $sql =
        "SELECT COUNT(*) AS total
         FROM aso_agent_transactions
         WHERE agent_id = ?";

    $types = 'i';
    $params = [$agentId];

    if ($start !== null) {
        $sql .= " AND created_at >= ?";
        $types .= 's';
        $params[] = $start;
    }

    if ($end !== null) {
        $sql .= " AND created_at < ?";
        $types .= 's';
        $params[] = $end;
    }

    $sql .=
        " AND " .
        successful_status_sql('status');

    $row =
        fetch_one(
            $conn,
            $sql,
            $types,
            $params
        );

    return
        $row
            ? (int)$row['total']
            : 0;
}

function agent_commission_total(
    mysqli $conn,
    int $agentId
): float {

    if (!table_exists(
        $conn,
        'aso_agent_transactions'
    )) {
        return 0.0;
    }

    $row = fetch_one(
        $conn,
        "SELECT
            COALESCE(
                SUM(commission_amount),
                0
            ) AS total
         FROM aso_agent_transactions
         WHERE agent_id = ?
         AND " .
         successful_status_sql('status'),
        'i',
        [$agentId]
    );

    return
        $row
            ? (float)$row['total']
            : 0.0;
}


/* =========================================================================
   AJAX
========================================================================= */

if (
    isset($_GET['ajax']) ||
    isset($_POST['ajax'])
) {

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


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

    if ($action === 'stats') {

        $totalAgents = 0;

        /*
         * IMPORTANT:
         * Only agents with at least one customer.
         */
        if (
            table_exists($conn, 'aso_agents') &&
            table_exists($conn, 'aso_agent_customers')
        ) {

            $row = fetch_one(
                $conn,
                "SELECT COUNT(*) AS total
                 FROM aso_agents a
                 WHERE EXISTS (
                    SELECT 1
                    FROM aso_agent_customers ac
                    WHERE ac.agent_id = a.id
                 )"
            );

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

        $activeAgents = 0;

        if (
            table_exists($conn, 'aso_agents') &&
            table_exists($conn, 'aso_agent_customers')
        ) {

            $row = fetch_one(
                $conn,
                "SELECT COUNT(*) AS total
                 FROM aso_agents a
                 WHERE LOWER(
                    COALESCE(a.status,'active')
                 ) NOT IN
                 (
                    'inactive',
                    'disabled',
                    'suspended'
                 )
                 AND EXISTS (
                    SELECT 1
                    FROM aso_agent_customers ac
                    WHERE ac.agent_id = a.id
                 )"
            );

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

        $customers = 0;

        if (
            table_exists(
                $conn,
                'aso_agent_customers'
            )
        ) {

            $row = fetch_one(
                $conn,
                "SELECT COUNT(*) AS total
                 FROM aso_agent_customers"
            );

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

        $transactions = 0;
        $volume = 0.0;
        $commission = 0.0;

        if (
            table_exists(
                $conn,
                'aso_agent_transactions'
            )
        ) {

            $row = fetch_one(
                $conn,
                "SELECT
                    COUNT(*) AS transactions,
                    COALESCE(
                        SUM(transaction_amount),
                        0
                    ) AS volume,
                    COALESCE(
                        SUM(commission_amount),
                        0
                    ) AS commission
                 FROM aso_agent_transactions
                 WHERE " .
                 successful_status_sql('status')
            );

            if ($row) {

                $transactions =
                    (int)$row['transactions'];

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

                $commission =
                    (float)$row['commission'];
            }
        }

        $pendingWithdrawals = 0;
        $pendingAmount = 0.0;

        if (
            table_exists(
                $conn,
                'aso_agent_withdrawals'
            )
        ) {

            $row = fetch_one(
                $conn,
                "SELECT
                    COUNT(*) AS total,
                    COALESCE(
                        SUM(amount),
                        0
                    ) AS amount
                 FROM aso_agent_withdrawals
                 WHERE LOWER(status) = 'pending'"
            );

            if ($row) {

                $pendingWithdrawals =
                    (int)$row['total'];

                $pendingAmount =
                    (float)$row['amount'];
            }
        }

        json_response([
            'success' => true,
            'total_agents' => $totalAgents,
            'active_agents' => $activeAgents,
            'customers' => $customers,
            'transactions' => $transactions,
            'volume' => $volume,
            'commission' => $commission,
            'pending_withdrawals' =>
                $pendingWithdrawals,
            'pending_amount' =>
                $pendingAmount
        ]);
    }


    /* =====================================================================
       AGENTS
       ONLY AGENTS WITH CUSTOMERS
    ===================================================================== */

    if ($action === 'agents') {

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

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

        $limit = 25;
        $offset =
            ($page - 1) * $limit;

        $where =
            "WHERE EXISTS (
                SELECT 1
                FROM aso_agent_customers acx
                WHERE acx.agent_id = a.id
            )";

        $types = '';
        $params = [];

        if ($search !== '') {

            $where .=
                " AND (
                    a.user_email LIKE ?
                    OR a.referral_code LIKE ?
                    OR CAST(a.id AS CHAR) LIKE ?
                )";

            $like =
                '%' . $search . '%';

            $types = 'sss';

            $params = [
                $like,
                $like,
                $like
            ];
        }

        $row = fetch_one(
            $conn,
            "SELECT COUNT(*) AS total
             FROM aso_agents a
             {$where}",
            $types,
            $params
        );

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

        $pages =
            max(
                1,
                (int)ceil(
                    $total / $limit
                )
            );

        if ($page > $pages) {
            $page = $pages;
            $offset =
                ($page - 1) * $limit;
        }

        $rows =
            fetch_all_rows(
                $conn,
                "SELECT
                    a.*,
                    (
                        SELECT COUNT(*)
                        FROM aso_agent_customers ac
                        WHERE ac.agent_id = a.id
                    ) AS customer_count
                 FROM aso_agents a
                 {$where}
                 ORDER BY a.id DESC
                 LIMIT {$limit}
                 OFFSET {$offset}",
                $types,
                $params
            );

        foreach ($rows as &$row) {

            $aid =
                (int)$row['id'];

            $row['wallet'] =
                get_agent_wallet(
                    $conn,
                    $aid
                );

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

            $row['transactions'] =
                agent_transaction_count(
                    $conn,
                    $aid
                );

            $row['commission'] =
                agent_commission_total(
                    $conn,
                    $aid
                );
        }

        unset($row);

        json_response([
            'success' => true,
            'rows' => $rows,
            'page' => $page,
            'pages' => $pages,
            'total' => $total
        ]);
    }


    /* =====================================================================
       AGENT DETAIL
    ===================================================================== */

    if ($action === 'agent_detail') {

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

        if ($agentId <= 0) {
            json_response([
                'success' => false,
                'message' => 'Invalid agent.'
            ]);
        }

        $agent = fetch_one(
            $conn,
            "SELECT *
             FROM aso_agents
             WHERE id = ?
             LIMIT 1",
            'i',
            [$agentId]
        );

        if (!$agent) {
            json_response([
                'success' => false,
                'message' => 'Agent not found.'
            ]);
        }

        $customerCount =
            agent_customer_count(
                $conn,
                $agentId
            );

        $transactionCount =
            agent_transaction_count(
                $conn,
                $agentId
            );

        $commission =
            agent_commission_total(
                $conn,
                $agentId
            );

        $wallet =
            get_agent_wallet(
                $conn,
                $agentId
            );

        json_response([
            'success' => true,
            'agent' => $agent,
            'customers' =>
                $customerCount,
            'transactions' =>
                $transactionCount,
            'commission' =>
                $commission,
            'wallet' =>
                $wallet
        ]);
    }


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

    if ($action === 'update_agent_status') {

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            json_response([
                'success' => false,
                'message' => 'Invalid request.'
            ]);
        }

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

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

        $allowed = [
            'active',
            'inactive',
            'suspended',
            'disabled'
        ];

        if (
            $agentId <= 0 ||
            !in_array(
                $status,
                $allowed,
                true
            )
        ) {
            json_response([
                'success' => false,
                'message' =>
                    'Invalid agent or status.'
            ]);
        }

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

        if (!$stmt) {
            json_response([
                'success' => false,
                'message' =>
                    'Unable to prepare update.'
            ]);
        }

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

        $ok =
            $stmt->execute();

        $stmt->close();

        json_response([
            'success' => $ok,
            'message' =>
                $ok
                    ? 'Agent status updated.'
                    : 'Unable to update agent.'
        ]);
    }


    /* =====================================================================
       CUSTOMERS
    ===================================================================== */

    if ($action === 'customers') {

        $agentId =
            (int)(
                $_GET['agent_id']
                ?? 0
            );

        if ($agentId <= 0) {
            json_response([
                'success' => false,
                'message' => 'Invalid agent.'
            ]);
        }

        $rows =
            fetch_all_rows(
                $conn,
                "SELECT *
                 FROM aso_agent_customers
                 WHERE agent_id = ?
                 ORDER BY
                    COALESCE(
                        last_transaction_at,
                        first_referred_at
                    ) DESC,
                    id DESC
                 LIMIT 500",
                'i',
                [$agentId]
            );

        json_response([
            'success' => true,
            'rows' => $rows
        ]);
    }


    /* =====================================================================
       TRANSACTIONS
    ===================================================================== */

    if ($action === 'transactions') {

        $agentId =
            (int)(
                $_GET['agent_id']
                ?? 0
            );

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

        $limit = 30;
        $offset =
            ($page - 1) * $limit;

        if ($agentId <= 0) {
            json_response([
                'success' => false,
                'message' => 'Invalid agent.'
            ]);
        }

        $row = fetch_one(
            $conn,
            "SELECT COUNT(*) AS total
             FROM aso_agent_transactions
             WHERE agent_id = ?",
            'i',
            [$agentId]
        );

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

        $pages =
            max(
                1,
                (int)ceil(
                    $total / $limit
                )
            );

        $rows =
            fetch_all_rows(
                $conn,
                "SELECT
                    id,
                    customer_email,
                    external_transaction_id,
                    service_name,
                    transaction_amount,
                    commission_percent,
                    commission_amount,
                    status,
                    created_at
                 FROM aso_agent_transactions
                 WHERE agent_id = ?
                 ORDER BY id DESC
                 LIMIT {$limit}
                 OFFSET {$offset}",
                'i',
                [$agentId]
            );

        json_response([
            'success' => true,
            'rows' => $rows,
            'page' => $page,
            'pages' => $pages,
            'total' => $total
        ]);
    }


    /* =====================================================================
       WITHDRAWALS
    ===================================================================== */

    if ($action === 'withdrawals') {

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

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

        $limit = 30;
        $offset =
            ($page - 1) * $limit;

        $where = '';
        $types = '';
        $params = [];

        if (
            $status !== '' &&
            $status !== 'all'
        ) {

            $where =
                "WHERE LOWER(w.status) = ?";

            $types = 's';
            $params = [$status];
        }

        $row = fetch_one(
            $conn,
            "SELECT COUNT(*) AS total
             FROM aso_agent_withdrawals w
             {$where}",
            $types,
            $params
        );

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

        $pages =
            max(
                1,
                (int)ceil(
                    $total / $limit
                )
            );

        $rows =
            fetch_all_rows(
                $conn,
                "SELECT
                    w.*,
                    a.user_email,
                    a.referral_code
                 FROM aso_agent_withdrawals w
                 LEFT JOIN aso_agents a
                    ON a.id = w.agent_id
                 {$where}
                 ORDER BY w.id DESC
                 LIMIT {$limit}
                 OFFSET {$offset}",
                $types,
                $params
            );

        json_response([
            'success' => true,
            'rows' => $rows,
            'page' => $page,
            'pages' => $pages,
            'total' => $total
        ]);
    }


    /* =====================================================================
       APPROVE / REJECT WITHDRAWAL
    ===================================================================== */

    if ($action === 'update_withdrawal') {

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            json_response([
                'success' => false,
                'message' => 'Invalid request.'
            ]);
        }

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

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

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

        if ($withdrawalId <= 0) {
            json_response([
                'success' => false,
                'message' =>
                    'Invalid withdrawal ID.'
            ]);
        }

        /*
         * Admin action is intentionally limited to
         * approve or reject for this manager.
         */
        if (!in_array(
            $newStatus,
            [
                'approved',
                'rejected'
            ],
            true
        )) {
            json_response([
                'success' => false,
                'message' =>
                    'Only approve or reject is allowed.'
            ]);
        }

        if (!table_exists(
            $conn,
            'aso_agent_withdrawals'
        )) {
            json_response([
                'success' => false,
                'message' =>
                    'Withdrawal table does not exist.'
            ]);
        }

        $conn->begin_transaction();

        try {

            /*
             * Lock withdrawal row.
             */
            $withdrawal =
                fetch_one(
                    $conn,
                    "SELECT *
                     FROM aso_agent_withdrawals
                     WHERE id = ?
                     LIMIT 1
                     FOR UPDATE",
                    'i',
                    [$withdrawalId]
                );

            if (!$withdrawal) {
                throw new RuntimeException(
                    'Withdrawal request not found.'
                );
            }

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

            /*
             * Do not process already completed
             * withdrawals again.
             */
            if (in_array(
                $oldStatus,
                [
                    'approved',
                    'successful',
                    'paid'
                ],
                true
            )) {

                throw new RuntimeException(
                    'This withdrawal has already been approved/paid.'
                );
            }

            if (in_array(
                $oldStatus,
                [
                    'rejected',
                    'failed'
                ],
                true
            )) {

                throw new RuntimeException(
                    'This withdrawal has already been rejected.'
                );
            }

            $amount =
                (float)(
                    $withdrawal['amount']
                    ?? 0
                );

            $agentId =
                (int)(
                    $withdrawal['agent_id']
                    ?? 0
                );

            if ($agentId <= 0) {
                throw new RuntimeException(
                    'Invalid agent attached to withdrawal.'
                );
            }

            if ($amount <= 0) {
                throw new RuntimeException(
                    'Invalid withdrawal amount.'
                );
            }


            /* =============================================================
               APPROVE
            ============================================================= */

            if ($newStatus === 'approved') {

                $walletColumn =
                    wallet_column($conn);

                if ($walletColumn === null) {
                    throw new RuntimeException(
                        'Agent wallet table or balance column not found.'
                    );
                }

                $safe =
                    preg_replace(
                        '/[^a-zA-Z0-9_]/',
                        '',
                        $walletColumn
                    );

                /*
                 * Lock wallet row.
                 */
                $wallet =
                    fetch_one(
                        $conn,
                        "SELECT
                            `{$safe}` AS balance
                         FROM aso_agent_wallet
                         WHERE agent_id = ?
                         LIMIT 1
                         FOR UPDATE",
                        'i',
                        [$agentId]
                    );

                if (!$wallet) {
                    throw new RuntimeException(
                        'Agent wallet not found.'
                    );
                }

                $balance =
                    (float)$wallet['balance'];

                if ($balance < $amount) {
                    throw new RuntimeException(
                        'Insufficient agent wallet balance. Current balance: ' .
                        money($balance)
                    );
                }

                /*
                 * Deduct exactly once.
                 */
                $stmt =
                    $conn->prepare(
                        "UPDATE aso_agent_wallet
                         SET `{$safe}` =
                             `{$safe}` - ?
                         WHERE agent_id = ?"
                    );

                if (!$stmt) {
                    throw new RuntimeException(
                        'Unable to prepare wallet deduction.'
                    );
                }

                $stmt->bind_param(
                    'di',
                    $amount,
                    $agentId
                );

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

                    throw new RuntimeException(
                        'Unable to deduct wallet balance.'
                    );
                }

                $stmt->close();


                /*
                 * Save wallet log.
                 */
                if (
                    table_exists(
                        $conn,
                        'aso_agent_wallet_logs'
                    )
                ) {

                    $reference =
                        'WD-' .
                        $withdrawalId;

                    $description =
                        'Approved agent withdrawal #' .
                        $withdrawalId;

                    $stmt =
                        $conn->prepare(
                            "INSERT INTO
                             aso_agent_wallet_logs
                             (
                                agent_id,
                                type,
                                amount,
                                description,
                                reference,
                                created_at
                             )
                             VALUES
                             (
                                ?,
                                'withdrawal',
                                ?,
                                ?,
                                ?,
                                NOW()
                             )"
                        );

                    if ($stmt) {

                        $stmt->bind_param(
                            'idss',
                            $agentId,
                            $amount,
                            $description,
                            $reference
                        );

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

                            throw new RuntimeException(
                                'Unable to create withdrawal wallet log.'
                            );
                        }

                        $stmt->close();
                    }
                }
            }


            /* =============================================================
               UPDATE WITHDRAWAL
            ============================================================= */

            $processedAt =
                date('Y-m-d H:i:s');

            if (
                column_exists(
                    $conn,
                    'aso_agent_withdrawals',
                    'processed_at'
                )
            ) {

                $stmt =
                    $conn->prepare(
                        "UPDATE aso_agent_withdrawals
                         SET
                            status = ?,
                            admin_note = ?,
                            processed_at = ?
                         WHERE id = ?"
                    );

                if (!$stmt) {
                    throw new RuntimeException(
                        'Unable to update withdrawal.'
                    );
                }

                $stmt->bind_param(
                    'sssi',
                    $newStatus,
                    $note,
                    $processedAt,
                    $withdrawalId
                );

            } else {

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

                if (!$stmt) {
                    throw new RuntimeException(
                        'Unable to update withdrawal.'
                    );
                }

                $stmt->bind_param(
                    'ssi',
                    $newStatus,
                    $note,
                    $withdrawalId
                );
            }

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

                throw new RuntimeException(
                    'Unable to save withdrawal status.'
                );
            }

            $stmt->close();

            $conn->commit();

            json_response([
                'success' => true,
                'message' =>
                    $newStatus === 'approved'
                        ? 'Withdrawal approved and wallet debited successfully.'
                        : 'Withdrawal rejected successfully.'
            ]);

        } catch (Throwable $e) {

            $conn->rollback();

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


    /* =====================================================================
       LEADERBOARD
       ONLY AGENTS WITH SUCCESSFUL TRANSACTIONS
    ===================================================================== */

    if ($action === 'leaderboard') {

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

        if (!preg_match(
            '/^\d{4}-\d{2}$/',
            $month
        )) {
            $month =
                current_month();
        }

        $start =
            month_start($month);

        $end =
            next_month_start($month);

        /*
         * We only retrieve agents who have
         * successful transactions in this month.
         *
         * This also guarantees zero-transaction
         * agents are excluded.
         */
        $agents =
            fetch_all_rows(
                $conn,
                "SELECT
                    a.id,
                    a.user_email,
                    a.referral_code,
                    a.status,
                    a.agent_rank,
                    COUNT(t.id) AS monthly_transactions
                 FROM aso_agents a
                 INNER JOIN aso_agent_transactions t
                    ON t.agent_id = a.id
                    AND t.created_at >= ?
                    AND t.created_at < ?
                    AND " .
                    successful_status_sql('t.status') . "
                 WHERE LOWER(
                    COALESCE(a.status,'active')
                 ) NOT IN
                 (
                    'inactive',
                    'disabled',
                    'suspended'
                 )
                 GROUP BY
                    a.id,
                    a.user_email,
                    a.referral_code,
                    a.status,
                    a.agent_rank
                 HAVING COUNT(t.id) > 0
                 ORDER BY
                    monthly_transactions DESC,
                    a.id ASC",
                'ss',
                [
                    $start,
                    $end
                ]
            );

        $rows = [];

        foreach ($agents as $agent) {

            $aid =
                (int)$agent['id'];

            /*
             * Count is already filtered to
             * successful transactions.
             */
            $count =
                (int)(
                    $agent[
                        'monthly_transactions'
                    ]
                    ?? 0
                );

            if ($count <= 0) {
                continue;
            }

            $rows[] = [
                'id' =>
                    $aid,

                /*
                 * EMAIL INCLUDED
                 */
                'email' =>
                    (string)(
                        $agent['user_email']
                        ?? ''
                    ),

                'referral_code' =>
                    (string)(
                        $agent['referral_code']
                        ?? ''
                    ),

                'rank' =>
                    (string)(
                        $agent['agent_rank']
                        ?? ''
                    ),

                'count' =>
                    $count
            ];
        }

        /*
         * Sort again to guarantee ranking.
         */
        usort(
            $rows,
            static function (
                array $a,
                array $b
            ): int {

                if (
                    $a['count']
                    ===
                    $b['count']
                ) {
                    return
                        $a['id']
                        <=>
                        $b['id'];
                }

                return
                    $b['count']
                    <=>
                    $a['count'];
            }
        );

        foreach (
            $rows as $index => &$row
        ) {

            $position =
                $index + 1;

            $reward = 0.0;

            if ($position === 1) {
                $reward =
                    (float)$settings['prize_1'];
            } elseif ($position === 2) {
                $reward =
                    (float)$settings['prize_2'];
            } elseif ($position === 3) {
                $reward =
                    (float)$settings['prize_3'];
            }

            $eligible =
                $position <= 3 &&
                $row['count'] >=
                (int)$settings[
                    'target_transactions'
                ];

            $row['position'] =
                $position;

            $row['reward'] =
                $reward;

            $row['eligible'] =
                $eligible;

            $row['medal'] =
                $position === 1
                    ? '🥇 Gold'
                    : (
                        $position === 2
                            ? '🥈 Silver'
                            : (
                                $position === 3
                                    ? '🥉 Bronze'
                                    : ''
                            )
                    );
        }

        unset($row);

        json_response([
            'success' => true,
            'month' => $month,
            'target' =>
                (int)$settings[
                    'target_transactions'
                ],
            'rows' => $rows
        ]);
    }


    /* =====================================================================
       SAVE COMPETITION SETTINGS
    ===================================================================== */

    if (
        $action ===
        'save_competition_settings'
    ) {

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            json_response([
                'success' => false,
                'message' => 'Invalid request.'
            ]);
        }

        $target =
            max(
                1,
                (int)(
                    $_POST[
                        'target_transactions'
                    ]
                    ?? 3000
                )
            );

        $p1 =
            max(
                0,
                (float)(
                    $_POST['prize_1']
                    ?? 20000
                )
            );

        $p2 =
            max(
                0,
                (float)(
                    $_POST['prize_2']
                    ?? 15000
                )
            );

        $p3 =
            max(
                0,
                (float)(
                    $_POST['prize_3']
                    ?? 10000
                )
            );

        if (!table_exists(
            $conn,
            'aso_agent_competition_settings'
        )) {
            json_response([
                'success' => false,
                'message' =>
                    'Competition settings table does not exist.'
            ]);
        }

        $existing =
            fetch_one(
                $conn,
                "SELECT id
                 FROM aso_agent_competition_settings
                 ORDER BY id ASC
                 LIMIT 1"
            );

        if ($existing) {

            $stmt =
                $conn->prepare(
                    "UPDATE
                     aso_agent_competition_settings
                     SET
                        target_transactions = ?,
                        prize_1 = ?,
                        prize_2 = ?,
                        prize_3 = ?,
                        updated_at = NOW()
                     WHERE id = ?"
                );

            if (!$stmt) {
                json_response([
                    'success' => false,
                    'message' =>
                        'Unable to update settings.'
                ]);
            }

            $id =
                (int)$existing['id'];

            $stmt->bind_param(
                'idddi',
                $target,
                $p1,
                $p2,
                $p3,
                $id
            );

        } else {

            $stmt =
                $conn->prepare(
                    "INSERT INTO
                     aso_agent_competition_settings
                     (
                        target_transactions,
                        prize_1,
                        prize_2,
                        prize_3
                     )
                     VALUES (?, ?, ?, ?)"
                );

            if (!$stmt) {
                json_response([
                    'success' => false,
                    'message' =>
                        'Unable to create settings.'
                ]);
            }

            $stmt->bind_param(
                'iddd',
                $target,
                $p1,
                $p2,
                $p3
            );
        }

        $ok =
            $stmt->execute();

        $stmt->close();

        if (!$ok) {
            json_response([
                'success' => false,
                'message' =>
                    'Unable to save settings.'
            ]);
        }

        $settings =
            get_competition_settings(
                $conn
            );

        json_response([
            'success' => true,
            'message' =>
                'Competition settings saved.',
            'settings' =>
                $settings
        ]);
    }


    /* =====================================================================
       PREVIOUS WINNERS
    ===================================================================== */

    if (
        $action ===
        'previous_winners'
    ) {

        if (!table_exists(
            $conn,
            'aso_agent_competition_winners'
        )) {
            json_response([
                'success' => true,
                'rows' => []
            ]);
        }

        $rows =
            fetch_all_rows(
                $conn,
                "SELECT
                    w.*,
                    a.user_email,
                    a.referral_code
                 FROM
                    aso_agent_competition_winners w
                 LEFT JOIN aso_agents a
                    ON a.id = w.agent_id
                 WHERE w.position <= 3
                 ORDER BY
                    w.competition_month DESC,
                    w.position ASC
                 LIMIT 100"
            );

        json_response([
            'success' => true,
            'rows' => $rows
        ]);
    }


    /* =====================================================================
       PROCESS COMPETITION
    ===================================================================== */

    if (
        $action ===
        'process_competition'
    ) {

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

        if ($month === '') {
            $month =
                date(
                    'Y-m',
                    strtotime(
                        'first day of last month'
                    )
                );
        }

        if (!preg_match(
            '/^\d{4}-\d{2}$/',
            $month
        )) {
            json_response([
                'success' => false,
                'message' =>
                    'Invalid competition month.'
            ]);
        }

        if (
            !table_exists(
                $conn,
                'aso_agent_competition_months'
            ) ||
            !table_exists(
                $conn,
                'aso_agent_competition_winners'
            )
        ) {
            json_response([
                'success' => false,
                'message' =>
                    'Competition tables are missing.'
            ]);
        }

        $monthRow =
            fetch_one(
                $conn,
                "SELECT *
                 FROM aso_agent_competition_months
                 WHERE competition_month = ?
                 LIMIT 1",
                's',
                [$month]
            );

        if (
            $monthRow &&
            strtolower(
                (string)(
                    $monthRow['status']
                    ?? ''
                )
            ) === 'processed'
        ) {
            json_response([
                'success' => false,
                'message' =>
                    'This competition month has already been processed.'
            ]);
        }

        $start =
            month_start($month);

        $end =
            next_month_start($month);

        $target =
            (int)$settings[
                'target_transactions'
            ];

        $prizes = [
            1 =>
                (float)$settings['prize_1'],
            2 =>
                (float)$settings['prize_2'],
            3 =>
                (float)$settings['prize_3']
        ];

        /*
         * Only agents with successful
         * transactions participate.
         */
        $ranking =
            fetch_all_rows(
                $conn,
                "SELECT
                    a.id AS agent_id,
                    COUNT(t.id) AS transaction_count
                 FROM aso_agents a
                 INNER JOIN aso_agent_transactions t
                    ON t.agent_id = a.id
                    AND t.created_at >= ?
                    AND t.created_at < ?
                    AND " .
                    successful_status_sql('t.status') . "
                 WHERE LOWER(
                    COALESCE(a.status,'active')
                 ) NOT IN
                 (
                    'inactive',
                    'disabled',
                    'suspended'
                 )
                 GROUP BY a.id
                 HAVING COUNT(t.id) > 0
                 ORDER BY
                    transaction_count DESC,
                    a.id ASC",
                'ss',
                [
                    $start,
                    $end
                ]
            );

        $rankingFormatted = [];

        foreach ($ranking as $item) {

            $rankingFormatted[] = [
                'agent_id' =>
                    (int)$item['agent_id'],

                'transaction_count' =>
                    (int)$item['transaction_count']
            ];
        }

        $ranking =
            $rankingFormatted;

        $conn->begin_transaction();

        try {

            if (!$monthRow) {

                $stmt =
                    $conn->prepare(
                        "INSERT INTO
                         aso_agent_competition_months
                         (
                            competition_month,
                            target_transactions,
                            status,
                            created_at
                         )
                         VALUES
                         (?, ?, 'open', NOW())"
                    );

                if (!$stmt) {
                    throw new RuntimeException(
                        'Unable to create competition month.'
                    );
                }

                $stmt->bind_param(
                    'si',
                    $month,
                    $target
                );

                $stmt->execute();
                $stmt->close();
            }

            $created = 0;
            $credited = 0;

            foreach (
                array_slice(
                    $ranking,
                    0,
                    3
                ) as $index => $item
            ) {

                $position =
                    $index + 1;

                $aid =
                    (int)$item['agent_id'];

                $count =
                    (int)$item[
                        'transaction_count'
                    ];

                $reward =
                    $prizes[$position]
                    ?? 0.0;

                $eligible =
                    $count >= $target
                        ? 1
                        : 0;

                $existing =
                    fetch_one(
                        $conn,
                        "SELECT
                            id,
                            credited
                         FROM
                            aso_agent_competition_winners
                         WHERE
                            competition_month = ?
                         AND agent_id = ?
                         LIMIT 1
                         FOR UPDATE",
                        'si',
                        [
                            $month,
                            $aid
                        ]
                    );

                if ($existing) {
                    continue;
                }

                $isCredited = 0;

                $stmt =
                    $conn->prepare(
                        "INSERT INTO
                         aso_agent_competition_winners
                         (
                            competition_month,
                            agent_id,
                            position,
                            transaction_count,
                            target_transactions,
                            prize_amount,
                            eligible,
                            credited,
                            wallet_log_reference,
                            credited_at,
                            created_at
                         )
                         VALUES
                         (
                            ?,
                            ?,
                            ?,
                            ?,
                            ?,
                            ?,
                            ?,
                            ?,
                            NULL,
                            NULL,
                            NOW()
                         )"
                    );

                if (!$stmt) {
                    throw new RuntimeException(
                        'Unable to create winner record.'
                    );
                }

                $stmt->bind_param(
                    'siiiidii',
                    $month,
                    $aid,
                    $position,
                    $count,
                    $target,
                    $reward,
                    $eligible,
                    $isCredited
                );

                $stmt->execute();

                $winnerId =
                    $stmt->insert_id;

                $stmt->close();

                if (
                    $eligible &&
                    $reward > 0
                ) {

                    $walletColumn =
                        wallet_column(
                            $conn
                        );

                    if ($walletColumn !== null) {

                        $safe =
                            preg_replace(
                                '/[^a-zA-Z0-9_]/',
                                '',
                                $walletColumn
                            );

                        $wallet =
                            fetch_one(
                                $conn,
                                "SELECT
                                    `{$safe}` AS balance
                                 FROM aso_agent_wallet
                                 WHERE agent_id = ?
                                 LIMIT 1
                                 FOR UPDATE",
                                'i',
                                [$aid]
                            );

                        if (!$wallet) {

                            $stmt =
                                $conn->prepare(
                                    "INSERT INTO
                                     aso_agent_wallet
                                     (
                                        agent_id,
                                        `{$safe}`
                                     )
                                     VALUES (?, ?)"
                                );

                            if ($stmt) {

                                $zero = 0.0;

                                $stmt->bind_param(
                                    'id',
                                    $aid,
                                    $zero
                                );

                                $stmt->execute();
                                $stmt->close();
                            }
                        }

                        $reference =
                            'COMP-' .
                            $month .
                            '-P' .
                            $position .
                            '-' .
                            $aid;

                        $stmt =
                            $conn->prepare(
                                "UPDATE
                                 aso_agent_wallet
                                 SET `{$safe}` =
                                     `{$safe}` + ?
                                 WHERE agent_id = ?"
                            );

                        if ($stmt) {

                            $stmt->bind_param(
                                'di',
                                $reward,
                                $aid
                            );

                            $stmt->execute();
                            $stmt->close();
                        }

                        if (
                            table_exists(
                                $conn,
                                'aso_agent_wallet_logs'
                            )
                        ) {

                            $medal =
                                $position === 1
                                    ? 'Gold'
                                    : (
                                        $position === 2
                                            ? 'Silver'
                                            : 'Bronze'
                                    );

                            $description =
                                'ASOVERIFY ' .
                                $month .
                                ' ' .
                                $medal .
                                ' competition reward';

                            $stmt =
                                $conn->prepare(
                                    "INSERT INTO
                                     aso_agent_wallet_logs
                                     (
                                        agent_id,
                                        type,
                                        amount,
                                        description,
                                        reference,
                                        created_at
                                     )
                                     VALUES
                                     (
                                        ?,
                                        'competition_reward',
                                        ?,
                                        ?,
                                        ?,
                                        NOW()
                                     )"
                                );

                            if ($stmt) {

                                $stmt->bind_param(
                                    'idss',
                                    $aid,
                                    $reward,
                                    $description,
                                    $reference
                                );

                                $stmt->execute();
                                $stmt->close();
                            }
                        }

                        $stmt =
                            $conn->prepare(
                                "UPDATE
                                 aso_agent_competition_winners
                                 SET
                                    credited = 1,
                                    wallet_log_reference = ?,
                                    credited_at = NOW()
                                 WHERE id = ?"
                            );

                        if ($stmt) {

                            $stmt->bind_param(
                                'si',
                                $reference,
                                $winnerId
                            );

                            $stmt->execute();
                            $stmt->close();
                        }

                        $credited++;
                    }
                }

                $created++;
            }

            $stmt =
                $conn->prepare(
                    "UPDATE
                     aso_agent_competition_months
                     SET
                        status = 'processed',
                        processed_at = NOW()
                     WHERE competition_month = ?"
                );

            if (!$stmt) {
                throw new RuntimeException(
                    'Unable to close competition month.'
                );
            }

            $stmt->bind_param(
                's',
                $month
            );

            $stmt->execute();
            $stmt->close();

            $conn->commit();

            json_response([
                'success' => true,
                'message' =>
                    'Competition processed successfully.',
                'month' =>
                    $month,
                'winner_records' =>
                    $created,
                'credited' =>
                    $credited
            ]);

        } catch (Throwable $e) {

            $conn->rollback();

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


    /* =====================================================================
       WALLET LOGS
    ===================================================================== */

    if ($action === 'wallet_logs') {

        $agentId =
            (int)(
                $_GET['agent_id']
                ?? 0
            );

        if ($agentId <= 0) {
            json_response([
                'success' => false,
                'message' => 'Invalid agent.'
            ]);
        }

        if (!table_exists(
            $conn,
            'aso_agent_wallet_logs'
        )) {
            json_response([
                'success' => true,
                'rows' => []
            ]);
        }

        $rows =
            fetch_all_rows(
                $conn,
                "SELECT *
                 FROM aso_agent_wallet_logs
                 WHERE agent_id = ?
                 ORDER BY id DESC
                 LIMIT 200",
                'i',
                [$agentId]
            );

        json_response([
            'success' => true,
            'balance' =>
                get_agent_wallet(
                    $conn,
                    $agentId
                ),
            'rows' => $rows
        ]);
    }


    json_response([
        'success' => false,
        'message' =>
            'Unknown AJAX action.'
    ]);
}


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

$settings =
    get_competition_settings(
        $conn
    );

$adminName =
    is_string(
        $_SESSION['admin']
    )
        ? $_SESSION['admin']
        : 'Administrator';

?>
<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>ASOVERIFY Agent Management</title>

<style>

*{
    box-sizing:border-box;
}

:root{
    --bg:#020b18;
    --panel:#07182d;
    --panel2:#0a2039;
    --line:rgba(255,255,255,.075);
    --text:#f5f9ff;
    --muted:#7890ae;
    --cyan:#00d5ff;
    --blue:#168cff;
    --green:#32e982;
    --red:#ff5364;
    --gold:#ffd447;
    --orange:#ffae35;
}

body{
    margin:0;
    font-family:
        Inter,
        system-ui,
        -apple-system,
        BlinkMacSystemFont,
        "Segoe UI",
        Arial,
        sans-serif;

    background:
        radial-gradient(
            circle at 10% 0%,
            rgba(0,213,255,.18),
            transparent 28%
        ),
        radial-gradient(
            circle at 90% 10%,
            rgba(35,100,255,.15),
            transparent 25%
        ),
        linear-gradient(
            145deg,
            #020817,
            #04152a 55%,
            #020817
        );

    color:var(--text);
    min-height:100vh;
}

button,
input,
select,
textarea{
    font:inherit;
}

button{
    cursor:pointer;
}

.container{
    width:min(1480px,95%);
    margin:auto;
    padding:20px 0 60px;
}

.topbar{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:15px;
    margin-bottom:20px;
}

.logo{
    font-size:28px;
    font-weight:1000;
    letter-spacing:-1px;
}

.logo span{
    color:var(--cyan);
}

.logo small{
    font-size:10px;
    color:#67809e;
    margin-left:8px;
    letter-spacing:1px;
}

.admin-badge{
    padding:10px 15px;
    border-radius:14px;
    background:rgba(255,255,255,.045);
    border:1px solid var(--line);
    color:#8da5c2;
    font-size:12px;
    backdrop-filter:blur(10px);
}

.admin-badge strong{
    color:#fff;
}

.hero{
    position:relative;
    overflow:hidden;
    padding:30px;
    border-radius:26px;
    margin-bottom:18px;

    background:
        linear-gradient(
            135deg,
            rgba(0,213,255,.14),
            rgba(20,75,180,.12)
        );

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

    box-shadow:
        0 25px 80px
        rgba(0,0,0,.3);
}

.hero:after{
    content:"";
    position:absolute;
    width:230px;
    height:230px;
    right:-80px;
    top:-100px;
    border-radius:50%;
    background:rgba(0,213,255,.12);
    filter:blur(5px);
}

.hero h1{
    position:relative;
    z-index:2;
    margin:0 0 8px;
    font-size:clamp(27px,5vw,40px);
    font-weight:1000;
}

.hero p{
    position:relative;
    z-index:2;
    margin:0;
    color:#91a8c5;
    line-height:1.6;
}

.stats{
    display:grid;
    grid-template-columns:
        repeat(6,minmax(0,1fr));
    gap:12px;
    margin-bottom:18px;
}

.card{
    background:
        linear-gradient(
            145deg,
            rgba(8,28,51,.96),
            rgba(4,18,36,.96)
        );

    border:1px solid var(--line);
    border-radius:22px;
    padding:19px;

    box-shadow:
        0 18px 55px
        rgba(0,0,0,.22);
}

.stat-card{
    position:relative;
    overflow:hidden;
}

.stat-card:after{
    content:"";
    position:absolute;
    right:-35px;
    bottom:-45px;
    width:110px;
    height:110px;
    border-radius:50%;
    background:rgba(0,213,255,.06);
}

.stat-label{
    color:#7189a7;
    font-size:10px;
    font-weight:900;
    text-transform:uppercase;
    letter-spacing:.8px;
}

.stat-value{
    margin-top:8px;
    font-size:25px;
    font-weight:1000;
}

.cyan{color:var(--cyan);}
.green{color:var(--green);}
.gold{color:var(--gold);}
.red{color:var(--red);}
.purple{color:#bd8cff;}

.layout{
    display:grid;
    grid-template-columns:
        minmax(0,1.72fr)
        minmax(310px,.78fr);
    gap:18px;
}

.section-title{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:10px;
    margin-bottom:15px;
}

.section-title h2{
    margin:0;
    font-size:18px;
    font-weight:1000;
}

.section-title h2:first-letter{
    font-size:21px;
}

.badge{
    display:inline-flex;
    align-items:center;
    padding:7px 11px;
    border-radius:99px;
    background:rgba(0,213,255,.08);
    border:1px solid rgba(0,213,255,.1);
    color:var(--cyan);
    font-size:10px;
    font-weight:900;
}

.toolbar{
    display:flex;
    gap:8px;
    flex-wrap:wrap;
    margin-bottom:14px;
}

input,
select,
textarea{
    background:#041326;
    color:#fff;
    border:1px solid rgba(255,255,255,.09);
    border-radius:12px;
    padding:11px 13px;
    outline:none;
}

input:focus,
select:focus,
textarea:focus{
    border-color:rgba(0,213,255,.65);
    box-shadow:0 0 0 3px rgba(0,213,255,.06);
}

.search{
    flex:1;
    min-width:210px;
}

.btn{
    border:0;
    border-radius:11px;
    padding:10px 14px;
    background:linear-gradient(
        135deg,
        #00d5ff,
        #009be8
    );
    color:#00121d;
    font-weight:1000;
    box-shadow:0 8px 22px rgba(0,213,255,.12);
}

.btn:hover{
    transform:translateY(-1px);
}

.btn-secondary{
    background:rgba(255,255,255,.07);
    color:#fff;
    border:1px solid rgba(255,255,255,.07);
    box-shadow:none;
}

.btn-success{
    background:linear-gradient(
        135deg,
        #42ed8b,
        #1bc66b
    );
    color:#00170a;
}

.btn-danger{
    background:linear-gradient(
        135deg,
        #ff6473,
        #e92e47
    );
    color:#fff;
}

.btn-warning{
    background:linear-gradient(
        135deg,
        #ffc84b,
        #f59e0b
    );
    color:#211400;
}

.btn-small{
    padding:7px 10px;
    font-size:10px;
    border-radius:9px;
}

.table-wrap{
    overflow-x:auto;
    border-radius:15px;
}

table{
    width:100%;
    border-collapse:collapse;
    min-width:920px;
}

th,
td{
    padding:13px 10px;
    border-bottom:1px solid rgba(255,255,255,.055);
    text-align:left;
    font-size:11px;
    white-space:nowrap;
}

th{
    color:#66809f;
    font-size:9px;
    text-transform:uppercase;
    letter-spacing:.8px;
    font-weight:1000;
}

tr:hover td{
    background:rgba(0,213,255,.025);
}

.status{
    display:inline-flex;
    align-items:center;
    gap:5px;
    padding:5px 9px;
    border-radius:99px;
    font-size:9px;
    font-weight:1000;
    text-transform:capitalize;
    border:1px solid transparent;
}

.status:before{
    content:"";
    width:5px;
    height:5px;
    border-radius:50%;
    background:currentColor;
}

.status.active,
.status.approved,
.status.successful,
.status.paid{
    color:#36e883;
    background:rgba(34,197,94,.08);
    border-color:rgba(34,197,94,.1);
}

.status.pending,
.status.processing{
    color:#ffc44d;
    background:rgba(245,158,11,.08);
    border-color:rgba(245,158,11,.1);
}

.status.inactive,
.status.disabled,
.status.rejected,
.status.failed,
.status.suspended{
    color:#ff6876;
    background:rgba(239,68,68,.08);
    border-color:rgba(239,68,68,.1);
}

.mini{
    color:#617b9a;
    font-size:9px;
}

.actions{
    display:flex;
    gap:5px;
    flex-wrap:wrap;
}

.settings-grid{
    display:grid;
    grid-template-columns:repeat(2,minmax(0,1fr));
    gap:11px;
}

.field{
    display:grid;
    gap:6px;
}

.field label{
    color:#8098b5;
    font-size:9px;
    font-weight:1000;
    letter-spacing:.5px;
}

.field.full{
    grid-column:1/-1;
}

.reward-grid{
    display:grid;
    grid-template-columns:repeat(3,1fr);
    gap:9px;
    margin-top:13px;
}

.reward{
    padding:15px 10px;
    text-align:center;
    border-radius:16px;
    background:rgba(255,255,255,.035);
    border:1px solid rgba(255,255,255,.045);
}

.reward-icon{
    font-size:27px;
}

.reward-name{
    font-size:10px;
    font-weight:1000;
    margin-top:3px;
}

.reward-price{
    color:var(--cyan);
    font-size:12px;
    font-weight:1000;
    margin-top:5px;
}

.info-box{
    padding:12px 14px;
    border-left:3px solid var(--cyan);
    background:rgba(0,213,255,.045);
    color:#829bb8;
    font-size:11px;
    line-height:1.7;
    margin-bottom:14px;
}

.leaderboard-top{
    display:grid;
    grid-template-columns:repeat(3,1fr);
    gap:9px;
    margin-bottom:12px;
}

.top-medal{
    padding:14px;
    text-align:center;
    border-radius:16px;
    background:rgba(255,255,255,.035);
    border:1px solid rgba(255,255,255,.05);
}

.top-medal .emoji{
    font-size:25px;
}

.top-medal .count{
    display:block;
    margin-top:5px;
    color:var(--cyan);
    font-weight:1000;
    font-size:11px;
}

.gold-row{
    background:rgba(255,212,71,.035);
}

.silver-row{
    background:rgba(220,228,239,.025);
}

.bronze-row{
    background:rgba(205,139,86,.025);
}

.progress{
    width:150px;
    height:6px;
    background:#102945;
    border-radius:99px;
    overflow:hidden;
    margin-top:6px;
}

.progress > div{
    height:100%;
    background:linear-gradient(
        90deg,
        #00d5ff,
        #168cff
    );
    border-radius:99px;
}

.eligibility{
    display:inline-flex;
    padding:5px 8px;
    border-radius:99px;
    font-size:9px;
    font-weight:1000;
}

.eligible{
    color:#3be889;
    background:rgba(34,197,94,.08);
}

.not-eligible{
    color:#ffc44d;
    background:rgba(245,158,11,.08);
}

.withdrawal-summary{
    display:grid;
    grid-template-columns:repeat(3,1fr);
    gap:9px;
    margin-bottom:14px;
}

.summary-box{
    background:rgba(255,255,255,.035);
    border:1px solid rgba(255,255,255,.045);
    padding:14px;
    border-radius:15px;
}

.summary-box small{
    display:block;
    color:#667f9d;
    font-size:8px;
    font-weight:1000;
    text-transform:uppercase;
}

.summary-box strong{
    display:block;
    margin-top:6px;
    font-size:17px;
}

.approve-reject{
    display:flex;
    gap:5px;
}

.empty{
    padding:35px 20px;
    text-align:center;
    color:#5e7897;
    font-size:12px;
}

.pagination{
    display:flex;
    justify-content:center;
    align-items:center;
    gap:6px;
    padding-top:14px;
    flex-wrap:wrap;
}

.page-btn{
    padding:8px 11px;
    border:0;
    border-radius:9px;
    background:rgba(255,255,255,.06);
    color:#fff;
}

.page-btn.active{
    background:var(--cyan);
    color:#00131f;
    font-weight:1000;
}

.modal{
    display:none;
    position:fixed;
    inset:0;
    z-index:1000;
    padding:18px;
    overflow:auto;
    background:rgba(0,0,0,.82);
    backdrop-filter:blur(7px);
}

.modal-box{
    width:min(1200px,100%);
    margin:3vh auto;
    background:#06172c;
    border:1px solid rgba(255,255,255,.09);
    border-radius:24px;
    padding:20px;
    box-shadow:0 30px 100px rgba(0,0,0,.55);
}

.modal-header{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:10px;
    margin-bottom:15px;
}

.modal-header h2{
    margin:0;
    font-size:20px;
}

.close{
    width:39px;
    height:39px;
    border:0;
    border-radius:50%;
    background:rgba(255,255,255,.07);
    color:#fff;
    font-size:21px;
}

.detail-grid{
    display:grid;
    grid-template-columns:repeat(4,1fr);
    gap:9px;
    margin-bottom:18px;
}

.detail{
    padding:14px;
    background:rgba(255,255,255,.035);
    border:1px solid rgba(255,255,255,.045);
    border-radius:14px;
}

.detail small{
    display:block;
    color:#647e9d;
    font-size:9px;
    margin-bottom:5px;
}

.detail strong{
    font-size:15px;
}

.withdraw-modal{
    display:none;
}

.toast{
    position:fixed;
    right:18px;
    bottom:18px;
    z-index:3000;
    max-width:380px;
    padding:13px 16px;
    border-radius:13px;
    background:#092344;
    border:1px solid rgba(0,213,255,.18);
    box-shadow:0 18px 50px rgba(0,0,0,.4);
    font-size:12px;
}

.toast.success{
    border-color:rgba(34,197,94,.25);
}

.toast.error{
    border-color:rgba(239,68,68,.3);
}

@media(max-width:1200px){

    .stats{
        grid-template-columns:repeat(3,1fr);
    }

    .layout{
        grid-template-columns:1fr;
    }
}

@media(max-width:700px){

    .container{
        width:94%;
        padding-top:13px;
    }

    .topbar{
        align-items:flex-start;
    }

    .logo{
        font-size:23px;
    }

    .admin-badge{
        font-size:9px;
        padding:8px;
    }

    .hero{
        padding:21px;
    }

    .stats{
        grid-template-columns:repeat(2,1fr);
    }

    .stat-value{
        font-size:20px;
    }

    .settings-grid{
        grid-template-columns:1fr;
    }

    .reward-grid,
    .leaderboard-top,
    .withdrawal-summary{
        grid-template-columns:1fr;
    }

    .detail-grid{
        grid-template-columns:repeat(2,1fr);
    }

    .section-title{
        align-items:flex-start;
    }

    .progress{
        width:110px;
    }
}

</style>

</head>

<body>

<div class="container">

    <div class="topbar">

        <div class="logo">
            ASO<span>VERIFY</span>
            <small>ADMIN AGENT CENTER</small>
        </div>

        <div class="admin-badge">
            Logged in as:
            <strong><?=h($adminName)?></strong>
        </div>

    </div>


    <div class="hero">

        <h1>Agent Management</h1>

        <p>
            Manage active agents, referral customers,
            successful transactions, commissions,
            withdrawals and monthly competition.
        </p>

    </div>


    <!-- STATS -->

    <div class="stats">

        <div class="card stat-card">
            <div class="stat-label">
                Agents With Customers
            </div>

            <div
                id="totalAgents"
                class="stat-value cyan">
                0
            </div>
        </div>

        <div class="card stat-card">
            <div class="stat-label">
                Active Agents
            </div>

            <div
                id="activeAgents"
                class="stat-value green">
                0
            </div>
        </div>

        <div class="card stat-card">
            <div class="stat-label">
                Referred Customers
            </div>

            <div
                id="totalCustomers"
                class="stat-value purple">
                0
            </div>
        </div>

        <div class="card stat-card">
            <div class="stat-label">
                Successful Transactions
            </div>

            <div
                id="totalTransactions"
                class="stat-value cyan">
                0
            </div>
        </div>

        <div class="card stat-card">
            <div class="stat-label">
                Total Commission
            </div>

            <div
                id="totalCommission"
                class="stat-value gold">
                ₦0.00
            </div>
        </div>

        <div class="card stat-card">
            <div class="stat-label">
                Pending Withdrawals
            </div>

            <div
                id="pendingWithdrawals"
                class="stat-value red">
                0
            </div>

            <div
                id="pendingAmount"
                class="mini">
                ₦0.00
            </div>
        </div>

    </div>


    <div class="layout">

        <div>


            <!-- AGENTS -->

            <div class="card">

                <div class="section-title">

                    <h2>👥 Agents With Customers</h2>

                    <span
                        id="agentCountBadge"
                        class="badge">
                        Loading...
                    </span>

                </div>

                <div class="toolbar">

                    <input
                        id="agentSearch"
                        class="search"
                        type="text"
                        placeholder="Search email, referral code or ID...">

                    <button
                        class="btn"
                        onclick="loadAgents(1)">
                        Search
                    </button>

                </div>

                <div
                    id="agentsTable"
                    class="table-wrap">

                    <div class="empty">
                        Loading agents...
                    </div>

                </div>

                <div
                    id="agentsPagination"
                    class="pagination">
                </div>

            </div>


            <!-- LEADERBOARD -->

            <div
                class="card"
                style="margin-top:18px;">

                <div class="section-title">

                    <div>
                        <h2>🏆 Monthly Leaderboard</h2>

                        <div class="mini">
                            Only agents with successful
                            transactions are displayed.
                        </div>
                    </div>

                    <div class="toolbar">

                        <input
                            id="leaderboardMonth"
                            type="month"
                            value="<?=h(current_month())?>">

                        <button
                            class="btn btn-small"
                            onclick="loadLeaderboard()">
                            Refresh
                        </button>

                    </div>

                </div>

                <div
                    id="leaderboardTop"
                    class="leaderboard-top">
                </div>

                <div class="info-box">

                    🎯 Required target:
                    <strong
                        id="leaderboardTarget"
                        class="cyan">
                        <?=number_format(
                            (int)$settings[
                                'target_transactions'
                            ]
                        )?>
                    </strong>

                    successful transactions.

                    <br>

                    🏆 Agents with zero successful
                    transactions are automatically excluded.

                </div>

                <div
                    id="leaderboardTable"
                    class="table-wrap">

                    <div class="empty">
                        Loading leaderboard...
                    </div>

                </div>

            </div>


            <!-- WITHDRAWALS -->

            <div
                class="card"
                style="margin-top:18px;">

                <div class="section-title">

                    <div>
                        <h2>💸 Withdrawal Requests</h2>

                        <div class="mini">
                            Approve or reject agent withdrawal requests.
                        </div>
                    </div>

                    <select
                        id="withdrawStatus"
                        onchange="loadWithdrawals(1)">

                        <option value="all">
                            All Requests
                        </option>

                        <option value="pending">
                            Pending
                        </option>

                        <option value="approved">
                            Approved
                        </option>

                        <option value="rejected">
                            Rejected
                        </option>

                    </select>

                </div>

                <div class="withdrawal-summary">

                    <div class="summary-box">

                        <small>Pending Requests</small>

                        <strong
                            id="withdrawPendingCount"
                            class="red">
                            0
                        </strong>

                    </div>

                    <div class="summary-box">

                        <small>Pending Amount</small>

                        <strong
                            id="withdrawPendingAmount"
                            class="gold">
                            ₦0.00
                        </strong>

                    </div>

                    <div class="summary-box">

                        <small>Approved Amount</small>

                        <strong
                            id="withdrawApprovedAmount"
                            class="green">
                            ₦0.00
                        </strong>

                    </div>

                </div>

                <div
                    id="withdrawalsTable"
                    class="table-wrap">

                    <div class="empty">
                        Loading withdrawals...
                    </div>

                </div>

                <div
                    id="withdrawalsPagination"
                    class="pagination">
                </div>

            </div>


            <!-- WINNERS -->

            <div
                class="card"
                style="margin-top:18px;">

                <div class="section-title">

                    <h2>🏅 Competition Winners</h2>

                    <button
                        class="btn btn-small"
                        onclick="loadPreviousWinners()">
                        Refresh
                    </button>

                </div>

                <div
                    id="previousWinners"
                    class="table-wrap">

                    <div class="empty">
                        Loading winners...
                    </div>

                </div>

            </div>

        </div>


        <!-- RIGHT -->

        <div>


            <!-- SETTINGS -->

            <div class="card">

                <div class="section-title">

                    <h2>⚙️ Competition Settings</h2>

                </div>

                <form
                    id="settingsForm"
                    class="settings-grid">

                    <div class="field full">

                        <label>
                            REQUIRED MONTHLY TRANSACTIONS
                        </label>

                        <input
                            type="number"
                            name="target_transactions"
                            min="1"
                            value="<?=h(
                                $settings[
                                    'target_transactions'
                                ]
                            )?>"
                            required>

                    </div>

                    <div class="field">

                        <label>🥇 GOLD REWARD</label>

                        <input
                            type="number"
                            name="prize_1"
                            min="0"
                            step="0.01"
                            value="<?=h(
                                $settings[
                                    'prize_1'
                                ]
                            )?>"
                            required>

                    </div>

                    <div class="field">

                        <label>🥈 SILVER REWARD</label>

                        <input
                            type="number"
                            name="prize_2"
                            min="0"
                            step="0.01"
                            value="<?=h(
                                $settings[
                                    'prize_2'
                                ]
                            )?>"
                            required>

                    </div>

                    <div class="field">

                        <label>🥉 BRONZE REWARD</label>

                        <input
                            type="number"
                            name="prize_3"
                            min="0"
                            step="0.01"
                            value="<?=h(
                                $settings[
                                    'prize_3'
                                ]
                            )?>"
                            required>

                    </div>

                    <div
                        class="field"
                        style="
                            display:flex;
                            align-items:end;
                        ">

                        <button
                            class="btn"
                            style="width:100%;"
                            type="submit">
                            Save Settings
                        </button>

                    </div>

                </form>

                <div class="reward-grid">

                    <div class="reward">
                        <div class="reward-icon">🥇</div>
                        <div class="reward-name">GOLD</div>
                        <div
                            id="rewardGold"
                            class="reward-price">
                            <?=money(
                                (float)$settings[
                                    'prize_1'
                                ]
                            )?>
                        </div>
                    </div>

                    <div class="reward">
                        <div class="reward-icon">🥈</div>
                        <div class="reward-name">SILVER</div>
                        <div
                            id="rewardSilver"
                            class="reward-price">
                            <?=money(
                                (float)$settings[
                                    'prize_2'
                                ]
                            )?>
                        </div>
                    </div>

                    <div class="reward">
                        <div class="reward-icon">🥉</div>
                        <div class="reward-name">BRONZE</div>
                        <div
                            id="rewardBronze"
                            class="reward-price">
                            <?=money(
                                (float)$settings[
                                    'prize_3'
                                ]
                            )?>
                        </div>
                    </div>

                </div>

            </div>


            <!-- PROCESS -->

            <div
                class="card"
                style="margin-top:18px;">

                <div class="section-title">

                    <h2>🔄 Competition Processing</h2>

                </div>

                <p style="
                    color:#829bb7;
                    font-size:11px;
                    line-height:1.8;
                ">

                    Process a completed competition month.
                    Only agents with successful transactions
                    participate and only the top three can
                    receive rewards.

                </p>

                <input
                    id="processMonth"
                    type="month"
                    value="<?=h(
                        date(
                            'Y-m',
                            strtotime(
                                'first day of last month'
                            )
                        )
                    )?>"
                    style="
                        width:100%;
                        margin-bottom:9px;
                    ">

                <button
                    class="btn btn-warning"
                    style="width:100%;"
                    onclick="processCompetition()">

                    Process Selected Month

                </button>

            </div>


            <!-- RULES -->

            <div
                class="card"
                style="margin-top:18px;">

                <div class="section-title">

                    <h2>ℹ️ System Rules</h2>

                </div>

                <div style="
                    color:#8199b6;
                    font-size:11px;
                    line-height:2;
                ">

                    <div>🥇 Position 1 = Gold</div>
                    <div>🥈 Position 2 = Silver</div>
                    <div>🥉 Position 3 = Bronze</div>
                    <div>❌ Position 4+ = No reward</div>
                    <div>🎯 Target must be reached for reward eligibility.</div>
                    <div>📅 Leaderboard uses calendar months.</div>
                    <div>👥 Agents without customers are hidden.</div>
                    <div>📊 Agents without monthly transactions are hidden.</div>
                    <div>💰 Rewards are credited once.</div>

                </div>

            </div>

        </div>

    </div>

</div>


<!-- AGENT MODAL -->

<div
    id="agentModal"
    class="modal">

    <div class="modal-box">

        <div class="modal-header">

            <h2 id="agentModalTitle">
                Agent
            </h2>

            <button
                class="close"
                onclick="closeModal('agentModal')">
                ×
            </button>

        </div>

        <div
            id="agentDetails"
            class="detail-grid">
        </div>

        <div class="toolbar">

            <button
                class="btn"
                onclick="loadAgentCustomers()">
                Customers
            </button>

            <button
                class="btn btn-secondary"
                onclick="loadAgentTransactions()">
                Transactions
            </button>

            <button
                class="btn btn-secondary"
                onclick="loadWalletLogs()">
                Wallet Logs
            </button>

        </div>

        <div id="agentModalContent">
            <div class="empty">
                Select a section above.
            </div>
        </div>

    </div>

</div>


<!-- WITHDRAWAL MODAL -->

<div
    id="withdrawModal"
    class="modal">

    <div
        class="modal-box"
        style="max-width:550px;">

        <div class="modal-header">

            <h2>
                Withdrawal Request
            </h2>

            <button
                class="close"
                onclick="closeModal('withdrawModal')">
                ×
            </button>

        </div>

        <div id="withdrawModalContent"></div>

        <div
            class="field"
            style="margin-top:15px;">

            <label>
                ADMIN NOTE
            </label>

            <textarea
                id="withdrawNote"
                rows="4"
                placeholder="Optional admin note..."></textarea>

        </div>

        <div
            class="actions"
            style="
                margin-top:15px;
                justify-content:flex-end;
            ">

            <button
                class="btn btn-secondary"
                onclick="closeModal('withdrawModal')">
                Cancel
            </button>

            <button
                id="rejectWithdrawBtn"
                class="btn btn-danger"
                onclick="submitWithdrawal('rejected')">
                ✕ Reject
            </button>

            <button
                id="approveWithdrawBtn"
                class="btn btn-success"
                onclick="submitWithdrawal('approved')">
                ✓ Approve
            </button>

        </div>

    </div>

</div>


<div
    id="toast"
    class="toast">
</div>


<script>

const endpoint = 'admin_agent.php';

let selectedAgentId = 0;
let selectedWithdrawalId = 0;


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

function money(value){

    return '₦' +
        Number(value || 0)
        .toLocaleString(
            'en-NG',
            {
                minimumFractionDigits:2,
                maximumFractionDigits:2
            }
        );
}

function escapeHtml(value){

    return String(value ?? '')
        .replaceAll('&','&amp;')
        .replaceAll('<','&lt;')
        .replaceAll('>','&gt;')
        .replaceAll('"','&quot;')
        .replaceAll("'","&#039;");
}

function statusHtml(status){

    const s =
        String(
            status || 'pending'
        ).toLowerCase();

    return `
        <span class="status ${escapeHtml(s)}">
            ${escapeHtml(
                status || 'Pending'
            )}
        </span>
    `;
}

function toast(
    message,
    type = ''
){

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

    box.textContent =
        message;

    box.className =
        'toast ' +
        type;

    box.style.display =
        'block';

    setTimeout(
        () => {
            box.style.display =
                'none';
        },
        3500
    );
}

async function getJson(
    url,
    options = {}
){

    const response =
        await fetch(
            url,
            {
                cache:'no-store',
                ...options
            }
        );

    const text =
        await response.text();

    try{
        return JSON.parse(text);
    }catch(e){

        console.error(text);

        return {
            success:false,
            message:'Invalid server response.'
        };
    }
}

function openModal(id){

    document.getElementById(id)
        .style.display =
        'block';
}

function closeModal(id){

    document.getElementById(id)
        .style.display =
        'none';
}


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

async function loadStats(){

    try{

        const data =
            await getJson(
                endpoint +
                '?ajax=stats&_=' +
                Date.now()
            );

        if(!data.success){
            return;
        }

        document.getElementById(
            'totalAgents'
        ).textContent =
            Number(
                data.total_agents
            ).toLocaleString();

        document.getElementById(
            'activeAgents'
        ).textContent =
            Number(
                data.active_agents
            ).toLocaleString();

        document.getElementById(
            'totalCustomers'
        ).textContent =
            Number(
                data.customers
            ).toLocaleString();

        document.getElementById(
            'totalTransactions'
        ).textContent =
            Number(
                data.transactions
            ).toLocaleString();

        document.getElementById(
            'totalCommission'
        ).textContent =
            money(
                data.commission
            );

        document.getElementById(
            'pendingWithdrawals'
        ).textContent =
            Number(
                data.pending_withdrawals
            ).toLocaleString();

        document.getElementById(
            'pendingAmount'
        ).textContent =
            money(
                data.pending_amount
            );

        document.getElementById(
            'withdrawPendingCount'
        ).textContent =
            Number(
                data.pending_withdrawals
            ).toLocaleString();

        document.getElementById(
            'withdrawPendingAmount'
        ).textContent =
            money(
                data.pending_amount
            );

    }catch(error){

        console.error(error);

    }
}


/* =========================================================================
   AGENTS
========================================================================= */

async function loadAgents(
    page = 1
){

    const box =
        document.getElementById(
            'agentsTable'
        );

    box.innerHTML =
        '<div class="empty">Loading agents...</div>';

    const search =
        document.getElementById(
            'agentSearch'
        ).value;

    try{

        const data =
            await getJson(
                endpoint +
                '?ajax=agents' +
                '&page=' +
                page +
                '&search=' +
                encodeURIComponent(
                    search
                ) +
                '&_=' +
                Date.now()
            );

        if(!data.success){

            box.innerHTML =
                '<div class="empty">' +
                escapeHtml(
                    data.message ||
                    'Unable to load agents.'
                ) +
                '</div>';

            return;
        }

        document.getElementById(
            'agentCountBadge'
        ).textContent =
            Number(
                data.total
            ).toLocaleString() +
            ' agents';

        if(!data.rows.length){

            box.innerHTML =
                '<div class="empty">' +
                'No agents with customers found.' +
                '</div>';

            renderAgentPagination(
                data
            );

            return;
        }

        let html =
            '<table>' +
            '<thead>' +
            '<tr>' +
            '<th>ID</th>' +
            '<th>Agent</th>' +
            '<th>Referral</th>' +
            '<th>Customers</th>' +
            '<th>Transactions</th>' +
            '<th>Commission</th>' +
            '<th>Wallet</th>' +
            '<th>Status</th>' +
            '<th>Actions</th>' +
            '</tr>' +
            '</thead>' +
            '<tbody>';

        data.rows.forEach(
            row => {

                const active =
                    String(
                        row.status ||
                        'active'
                    ).toLowerCase()
                    === 'active';

                html +=
                    '<tr>' +

                    '<td><strong>#' +
                    escapeHtml(
                        row.id
                    ) +
                    '</strong></td>' +

                    '<td>' +

                    '<strong>' +
                    escapeHtml(
                        row.user_email
                    ) +
                    '</strong>' +

                    (
                        row.agent_rank
                            ? '<br><span class="mini">' +
                              escapeHtml(
                                  row.agent_rank
                              ) +
                              '</span>'
                            : ''
                    ) +

                    '</td>' +

                    '<td>' +

                    '<span class="cyan" style="font-weight:900;">' +
                    escapeHtml(
                        row.referral_code ||
                        '—'
                    ) +
                    '</span>' +

                    '</td>' +

                    '<td>' +
                    Number(
                        row.customers || 0
                    ).toLocaleString() +
                    '</td>' +

                    '<td>' +
                    Number(
                        row.transactions || 0
                    ).toLocaleString() +
                    '</td>' +

                    '<td class="green">' +
                    money(
                        row.commission
                    ) +
                    '</td>' +

                    '<td class="cyan">' +
                    money(
                        row.wallet
                    ) +
                    '</td>' +

                    '<td>' +
                    statusHtml(
                        row.status
                    ) +
                    '</td>' +

                    '<td>' +

                    '<div class="actions">' +

                    '<button ' +
                    'class="btn btn-small" ' +
                    'onclick="viewAgent(' +
                    Number(row.id) +
                    ')">' +
                    'View' +
                    '</button>' +

                    '<button ' +
                    'class="btn btn-secondary btn-small" ' +
                    'onclick="changeAgentStatus(' +
                    Number(row.id) +
                    ',\'' +
                    (
                        active
                            ? 'inactive'
                            : 'active'
                    ) +
                    '\')">' +

                    (
                        active
                            ? 'Disable'
                            : 'Activate'
                    ) +

                    '</button>' +

                    '</div>' +

                    '</td>' +

                    '</tr>';
            }
        );

        html +=
            '</tbody></table>';

        box.innerHTML =
            html;

        renderAgentPagination(
            data
        );

    }catch(error){

        console.error(error);

        box.innerHTML =
            '<div class="empty">' +
            'Unable to load agents.' +
            '</div>';
    }
}

function renderAgentPagination(
    data
){

    const box =
        document.getElementById(
            'agentsPagination'
        );

    if(data.pages <= 1){

        box.innerHTML =
            '';

        return;
    }

    let html = '';

    if(data.page > 1){

        html +=
            '<button class="page-btn" ' +
            'onclick="loadAgents(' +
            (data.page - 1) +
            ')">' +
            'Previous' +
            '</button>';
    }

    html +=
        '<span class="page-btn active">' +
        data.page +
        ' / ' +
        data.pages +
        '</span>';

    if(data.page < data.pages){

        html +=
            '<button class="page-btn" ' +
            'onclick="loadAgents(' +
            (data.page + 1) +
            ')">' +
            'Next' +
            '</button>';
    }

    box.innerHTML =
        html;
}


/* =========================================================================
   VIEW AGENT
========================================================================= */

async function viewAgent(id){

    selectedAgentId =
        Number(id);

    openModal(
        'agentModal'
    );

    document.getElementById(
        'agentModalTitle'
    ).textContent =
        'Agent #' + id;

    document.getElementById(
        'agentDetails'
    ).innerHTML =
        '<div class="empty">Loading...</div>';

    try{

        const data =
            await getJson(
                endpoint +
                '?ajax=agent_detail' +
                '&id=' +
                id +
                '&_=' +
                Date.now()
            );

        if(!data.success){

            toast(
                data.message ||
                'Unable to load agent.',
                'error'
            );

            return;
        }

        const a =
            data.agent;

        document.getElementById(
            'agentModalTitle'
        ).textContent =
            a.user_email ||
            'Agent #' + id;

        document.getElementById(
            'agentDetails'
        ).innerHTML =

            '<div class="detail">' +
            '<small>Email</small>' +
            '<strong>' +
            escapeHtml(
                a.user_email
            ) +
            '</strong>' +
            '</div>' +

            '<div class="detail">' +
            '<small>Referral Code</small>' +
            '<strong class="cyan">' +
            escapeHtml(
                a.referral_code ||
                '—'
            ) +
            '</strong>' +
            '</div>' +

            '<div class="detail">' +
            '<small>Customers</small>' +
            '<strong>' +
            Number(
                data.customers
            ).toLocaleString() +
            '</strong>' +
            '</div>' +

            '<div class="detail">' +
            '<small>Wallet</small>' +
            '<strong class="green">' +
            money(
                data.wallet
            ) +
            '</strong>' +
            '</div>' +

            '<div class="detail">' +
            '<small>Transactions</small>' +
            '<strong>' +
            Number(
                data.transactions
            ).toLocaleString() +
            '</strong>' +
            '</div>' +

            '<div class="detail">' +
            '<small>Commission</small>' +
            '<strong class="gold">' +
            money(
                data.commission
            ) +
            '</strong>' +
            '</div>' +

            '<div class="detail">' +
            '<small>Status</small>' +
            statusHtml(
                a.status
            ) +
            '</div>' +

            '<div class="detail">' +
            '<small>Agent ID</small>' +
            '<strong>#' +
            escapeHtml(
                a.id
            ) +
            '</strong>' +
            '</div>';

        document.getElementById(
            'agentModalContent'
        ).innerHTML =
            '<div class="empty">' +
            'Select Customers, Transactions or Wallet Logs.' +
            '</div>';

    }catch(error){

        console.error(error);

        toast(
            'Unable to load agent.',
            'error'
        );
    }
}


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

async function changeAgentStatus(
    id,
    status
){

    if(!confirm(
        'Change this agent status to ' +
        status +
        '?'
    )){
        return;
    }

    const fd =
        new FormData();

    fd.append(
        'ajax',
        'update_agent_status'
    );

    fd.append(
        'id',
        id
    );

    fd.append(
        'status',
        status
    );

    try{

        const data =
            await getJson(
                endpoint,
                {
                    method:'POST',
                    body:fd
                }
            );

        toast(
            data.message ||
            'Completed.',
            data.success
                ? 'success'
                : 'error'
        );

        if(data.success){

            loadAgents(1);
            loadStats();
        }

    }catch(error){

        console.error(error);

        toast(
            'Unable to update agent.',
            'error'
        );
    }
}


/* =========================================================================
   CUSTOMERS
========================================================================= */

async function loadAgentCustomers(){

    if(!selectedAgentId){
        return;
    }

    const box =
        document.getElementById(
            'agentModalContent'
        );

    box.innerHTML =
        '<div class="empty">Loading customers...</div>';

    try{

        const data =
            await getJson(
                endpoint +
                '?ajax=customers' +
                '&agent_id=' +
                selectedAgentId +
                '&_=' +
                Date.now()
            );

        if(!data.success){

            box.innerHTML =
                '<div class="empty">' +
                'Unable to load customers.' +
                '</div>';

            return;
        }

        if(!data.rows.length){

            box.innerHTML =
                '<div class="empty">' +
                'No referred customers.' +
                '</div>';

            return;
        }

        let html =
            '<table>' +
            '<thead>' +
            '<tr>' +
            '<th>ID</th>' +
            '<th>Customer</th>' +
            '<th>First Referred</th>' +
            '<th>Transactions</th>' +
            '<th>Spend</th>' +
            '<th>Commission</th>' +
            '<th>Last Transaction</th>' +
            '</tr>' +
            '</thead>' +
            '<tbody>';

        data.rows.forEach(
            row => {

                html +=
                    '<tr>' +

                    '<td>' +
                    escapeHtml(
                        row.id
                    ) +
                    '</td>' +

                    '<td>' +
                    escapeHtml(
                        row.customer_email
                    ) +
                    '</td>' +

                    '<td>' +
                    escapeHtml(
                        row.first_referred_at ||
                        ''
                    ) +
                    '</td>' +

                    '<td>' +
                    Number(
                        row.total_transactions ||
                        0
                    ).toLocaleString() +
                    '</td>' +

                    '<td>' +
                    money(
                        row.total_spend
                    ) +
                    '</td>' +

                    '<td class="green">' +
                    money(
                        row.total_commission
                    ) +
                    '</td>' +

                    '<td>' +
                    escapeHtml(
                        row.last_transaction_at ||
                        '—'
                    ) +
                    '</td>' +

                    '</tr>';
            }
        );

        html +=
            '</tbody></table>';

        box.innerHTML =
            html;

    }catch(error){

        console.error(error);

        box.innerHTML =
            '<div class="empty">' +
            'Unable to load customers.' +
            '</div>';
    }
}


/* =========================================================================
   TRANSACTIONS
========================================================================= */

async function loadAgentTransactions(
    page = 1
){

    if(!selectedAgentId){
        return;
    }

    const box =
        document.getElementById(
            'agentModalContent'
        );

    box.innerHTML =
        '<div class="empty">Loading transactions...</div>';

    try{

        const data =
            await getJson(
                endpoint +
                '?ajax=transactions' +
                '&agent_id=' +
                selectedAgentId +
                '&page=' +
                page +
                '&_=' +
                Date.now()
            );

        if(!data.success){

            box.innerHTML =
                '<div class="empty">' +
                'Unable to load transactions.' +
                '</div>';

            return;
        }

        if(!data.rows.length){

            box.innerHTML =
                '<div class="empty">' +
                'No transactions.' +
                '</div>';

            return;
        }

        let html =
            '<table>' +
            '<thead>' +
            '<tr>' +
            '<th>ID</th>' +
            '<th>Customer</th>' +
            '<th>Service</th>' +
            '<th>Amount</th>' +
            '<th>Commission</th>' +
            '<th>Status</th>' +
            '<th>Date</th>' +
            '</tr>' +
            '</thead>' +
            '<tbody>';

        data.rows.forEach(
            row => {

                html +=
                    '<tr>' +

                    '<td>' +
                    escapeHtml(
                        row.id
                    ) +

                    '<br>' +

                    '<span class="mini">' +
                    escapeHtml(
                        row.external_transaction_id ||
                        ''
                    ) +
                    '</span>' +

                    '</td>' +

                    '<td>' +
                    escapeHtml(
                        row.customer_email
                    ) +
                    '</td>' +

                    '<td>' +
                    escapeHtml(
                        row.service_name
                    ) +
                    '</td>' +

                    '<td>' +
                    money(
                        row.transaction_amount
                    ) +
                    '</td>' +

                    '<td class="green">' +
                    money(
                        row.commission_amount
                    ) +

                    '<br>' +

                    '<span class="mini">' +
                    Number(
                        row.commission_percent ||
                        0
                    ) +
                    '%</span>' +

                    '</td>' +

                    '<td>' +
                    statusHtml(
                        row.status ||
                        'Successful'
                    ) +
                    '</td>' +

                    '<td>' +
                    escapeHtml(
                        row.created_at
                    ) +
                    '</td>' +

                    '</tr>';
            }
        );

        html +=
            '</tbody></table>';

        if(data.pages > 1){

            html +=
                '<div class="pagination">' +

                (
                    data.page > 1
                        ? '<button class="page-btn" onclick="loadAgentTransactions(' +
                          (data.page - 1) +
                          ')">Previous</button>'
                        : ''
                ) +

                '<span class="page-btn active">' +
                data.page +
                ' / ' +
                data.pages +
                '</span>' +

                (
                    data.page < data.pages
                        ? '<button class="page-btn" onclick="loadAgentTransactions(' +
                          (data.page + 1) +
                          ')">Next</button>'
                        : ''
                ) +

                '</div>';
        }

        box.innerHTML =
            html;

    }catch(error){

        console.error(error);

        box.innerHTML =
            '<div class="empty">' +
            'Unable to load transactions.' +
            '</div>';
    }
}


/* =========================================================================
   WALLET LOGS
========================================================================= */

async function loadWalletLogs(){

    if(!selectedAgentId){
        return;
    }

    const box =
        document.getElementById(
            'agentModalContent'
        );

    box.innerHTML =
        '<div class="empty">Loading wallet logs...</div>';

    try{

        const data =
            await getJson(
                endpoint +
                '?ajax=wallet_logs' +
                '&agent_id=' +
                selectedAgentId +
                '&_=' +
                Date.now()
            );

        if(!data.success){

            box.innerHTML =
                '<div class="empty">' +
                'Unable to load wallet.' +
                '</div>';

            return;
        }

        let html =
            '<div style="' +
            'padding:15px;' +
            'background:rgba(0,213,255,.05);' +
            'border-radius:14px;' +
            'margin-bottom:15px;' +
            '">' +

            '<span class="mini">CURRENT BALANCE</span>' +

            '<strong class="green" ' +
            'style="display:block;font-size:25px;margin-top:5px;">' +

            money(
                data.balance
            ) +

            '</strong>' +

            '</div>';

        if(!data.rows.length){

            html +=
                '<div class="empty">' +
                'No wallet logs.' +
                '</div>';

            box.innerHTML =
                html;

            return;
        }

        html +=
            '<table>' +
            '<thead>' +
            '<tr>' +
            '<th>ID</th>' +
            '<th>Type</th>' +
            '<th>Amount</th>' +
            '<th>Description</th>' +
            '<th>Reference</th>' +
            '<th>Date</th>' +
            '</tr>' +
            '</thead>' +
            '<tbody>';

        data.rows.forEach(
            row => {

                const type =
                    String(
                        row.type || ''
                    ).toLowerCase();

                const negative =
                    [
                        'withdrawal',
                        'withdraw',
                        'debit',
                        'registration_fee'
                    ].includes(
                        type
                    );

                html +=
                    '<tr>' +

                    '<td>' +
                    escapeHtml(
                        row.id
                    ) +
                    '</td>' +

                    '<td>' +
                    escapeHtml(
                        row.type
                    ) +
                    '</td>' +

                    '<td class="' +
                    (
                        negative
                            ? 'red'
                            : 'green'
                    ) +
                    '">' +

                    (
                        negative
                            ? '-'
                            : '+'
                    ) +

                    money(
                        row.amount
                    ) +

                    '</td>' +

                    '<td>' +
                    escapeHtml(
                        row.description
                    ) +
                    '</td>' +

                    '<td>' +
                    escapeHtml(
                        row.reference
                    ) +
                    '</td>' +

                    '<td>' +
                    escapeHtml(
                        row.created_at
                    ) +
                    '</td>' +

                    '</tr>';
            }
        );

        html +=
            '</tbody></table>';

        box.innerHTML =
            html;

    }catch(error){

        console.error(error);

        box.innerHTML =
            '<div class="empty">' +
            'Unable to load wallet logs.' +
            '</div>';
    }
}


/* =========================================================================
   WITHDRAWALS
========================================================================= */

async function loadWithdrawals(
    page = 1
){

    const box =
        document.getElementById(
            'withdrawalsTable'
        );

    box.innerHTML =
        '<div class="empty">Loading withdrawals...</div>';

    const status =
        document.getElementById(
            'withdrawStatus'
        ).value;

    try{

        const data =
            await getJson(
                endpoint +
                '?ajax=withdrawals' +
                '&status=' +
                encodeURIComponent(
                    status
                ) +
                '&page=' +
                page +
                '&_=' +
                Date.now()
            );

        if(!data.success){

            box.innerHTML =
                '<div class="empty">' +
                escapeHtml(
                    data.message ||
                    'Unable to load withdrawals.'
                ) +
                '</div>';

            return;
        }

        /*
         * Approved amount on current result set.
         */
        let approvedAmount = 0;

        data.rows.forEach(
            row => {

                if(
                    [
                        'approved',
                        'successful',
                        'paid'
                    ].includes(
                        String(
                            row.status || ''
                        ).toLowerCase()
                    )
                ){
                    approvedAmount +=
                        Number(
                            row.amount || 0
                        );
                }
            }
        );

        document.getElementById(
            'withdrawApprovedAmount'
        ).textContent =
            money(
                approvedAmount
            );

        if(!data.rows.length){

            box.innerHTML =
                '<div class="empty">' +
                'No withdrawal requests.' +
                '</div>';

            document.getElementById(
                'withdrawalsPagination'
            ).innerHTML =
                '';

            return;
        }

        let html =
            '<table>' +
            '<thead>' +
            '<tr>' +
            '<th>ID</th>' +
            '<th>Agent</th>' +
            '<th>Amount</th>' +
            '<th>Bank Details</th>' +
            '<th>Status</th>' +
            '<th>Date</th>' +
            '<th>Action</th>' +
            '</tr>' +
            '</thead>' +
            '<tbody>';

        data.rows.forEach(
            row => {

                const currentStatus =
                    String(
                        row.status ||
                        'pending'
                    ).toLowerCase();

                const pending =
                    [
                        'pending',
                        'processing'
                    ].includes(
                        currentStatus
                    );

                html +=
                    '<tr>' +

                    '<td><strong>#' +
                    escapeHtml(
                        row.id
                    ) +
                    '</strong></td>' +

                    '<td>' +

                    '<strong>' +
                    escapeHtml(
                        row.user_email ||
                        ''
                    ) +
                    '</strong>' +

                    '<br>' +

                    '<span class="mini">' +
                    escapeHtml(
                        row.referral_code ||
                        ''
                    ) +
                    '</span>' +

                    '</td>' +

                    '<td class="gold">' +
                    money(
                        row.amount
                    ) +
                    '</td>' +

                    '<td>' +

                    '<strong>' +
                    escapeHtml(
                        row.account_name ||
                        '—'
                    ) +
                    '</strong>' +

                    '<br>' +

                    '<span class="mini">' +
                    escapeHtml(
                        row.bank_name ||
                        ''
                    ) +
                    ' • ' +
                    escapeHtml(
                        row.account_number ||
                        ''
                    ) +
                    '</span>' +

                    '</td>' +

                    '<td>' +
                    statusHtml(
                        row.status
                    ) +
                    (
                        row.admin_note
                            ? '<br><span class="mini">' +
                              escapeHtml(
                                  row.admin_note
                              ) +
                              '</span>'
                            : ''
                    ) +
                    '</td>' +

                    '<td>' +
                    escapeHtml(
                        row.created_at
                    ) +
                    '</td>' +

                    '<td>' +

                    (
                        pending

                            ? '<div class="approve-reject">' +

                              '<button ' +
                              'class="btn btn-success btn-small" ' +
                              'onclick="openWithdrawal(' +
                              Number(row.id) +
                              ')">' +
                              '✓ Manage' +
                              '</button>' +

                              '</div>'

                            : '<span class="mini">Processed</span>'
                    ) +

                    '</td>' +

                    '</tr>';
            }
        );

        html +=
            '</tbody></table>';

        box.innerHTML =
            html;

        renderWithdrawalPagination(
            data
        );

    }catch(error){

        console.error(error);

        box.innerHTML =
            '<div class="empty">' +
            'Unable to load withdrawals.' +
            '</div>';
    }
}

function renderWithdrawalPagination(
    data
){

    const box =
        document.getElementById(
            'withdrawalsPagination'
        );

    if(data.pages <= 1){

        box.innerHTML =
            '';

        return;
    }

    let html = '';

    if(data.page > 1){

        html +=
            '<button class="page-btn" ' +
            'onclick="loadWithdrawals(' +
            (data.page - 1) +
            ')">' +
            'Previous' +
            '</button>';
    }

    html +=
        '<span class="page-btn active">' +
        data.page +
        ' / ' +
        data.pages +
        '</span>';

    if(data.page < data.pages){

        html +=
            '<button class="page-btn" ' +
            'onclick="loadWithdrawals(' +
            (data.page + 1) +
            ')">' +
            'Next' +
            '</button>';
    }

    box.innerHTML =
        html;
}


/* =========================================================================
   OPEN WITHDRAWAL
========================================================================= */

async function openWithdrawal(
    id
){

    selectedWithdrawalId =
        Number(id);

    openModal(
        'withdrawModal'
    );

    const box =
        document.getElementById(
            'withdrawModalContent'
        );

    box.innerHTML =
        '<div class="empty">Loading request...</div>';

    document.getElementById(
        'withdrawNote'
    ).value = '';

    try{

        const data =
            await getJson(
                endpoint +
                '?ajax=withdrawals' +
                '&status=all' +
                '&page=1' +
                '&_=' +
                Date.now()
            );

        if(!data.success){

            box.innerHTML =
                '<div class="empty">' +
                'Unable to load request.' +
                '</div>';

            return;
        }

        const row =
            data.rows.find(
                item =>
                    Number(item.id) ===
                    Number(id)
            );

        if(!row){

            box.innerHTML =
                '<div class="empty">' +
                'Withdrawal request not found.' +
                '</div>';

            return;
        }

        document.getElementById(
            'withdrawNote'
        ).value =
            row.admin_note || '';

        box.innerHTML =

            '<div style="' +
            'padding:16px;' +
            'background:rgba(0,213,255,.04);' +
            'border-radius:15px;' +
            '">' +

            '<div style="margin-bottom:12px;">' +
            '<span class="mini">AGENT</span>' +
            '<strong style="display:block;margin-top:4px;">' +
            escapeHtml(
                row.user_email || ''
            ) +
            '</strong>' +
            '</div>' +

            '<div style="margin-bottom:12px;">' +
            '<span class="mini">AMOUNT</span>' +
            '<strong class="gold" style="display:block;margin-top:4px;font-size:24px;">' +
            money(
                row.amount
            ) +
            '</strong>' +
            '</div>' +

            '<div style="margin-bottom:12px;">' +
            '<span class="mini">BANK</span>' +
            '<strong style="display:block;margin-top:4px;">' +
            escapeHtml(
                row.bank_name || ''
            ) +
            '</strong>' +
            '</div>' +

            '<div style="margin-bottom:12px;">' +
            '<span class="mini">ACCOUNT NUMBER</span>' +
            '<strong style="display:block;margin-top:4px;">' +
            escapeHtml(
                row.account_number || ''
            ) +
            '</strong>' +
            '</div>' +

            '<div>' +
            '<span class="mini">ACCOUNT NAME</span>' +
            '<strong style="display:block;margin-top:4px;">' +
            escapeHtml(
                row.account_name || ''
            ) +
            '</strong>' +
            '</div>' +

            '</div>';

    }catch(error){

        console.error(error);

        box.innerHTML =
            '<div class="empty">' +
            'Unable to load request.' +
            '</div>';
    }
}


/* =========================================================================
   APPROVE / REJECT WITHDRAWAL
========================================================================= */

async function submitWithdrawal(
    status
){

    if(!selectedWithdrawalId){
        return;
    }

    const actionText =
        status === 'approved'
            ? 'APPROVE'
            : 'REJECT';

    if(!confirm(
        'Are you sure you want to ' +
        actionText +
        ' this withdrawal request?'
    )){
        return;
    }

    const note =
        document.getElementById(
            'withdrawNote'
        ).value;

    const fd =
        new FormData();

    fd.append(
        'ajax',
        'update_withdrawal'
    );

    fd.append(
        'id',
        selectedWithdrawalId
    );

    fd.append(
        'status',
        status
    );

    fd.append(
        'admin_note',
        note
    );

    const approveButton =
        document.getElementById(
            'approveWithdrawBtn'
        );

    const rejectButton =
        document.getElementById(
            'rejectWithdrawBtn'
        );

    approveButton.disabled = true;
    rejectButton.disabled = true;

    try{

        const data =
            await getJson(
                endpoint,
                {
                    method:'POST',
                    body:fd
                }
            );

        if(data.success){

            closeModal(
                'withdrawModal'
            );

            toast(
                data.message ||
                'Withdrawal updated successfully.',
                'success'
            );

            loadWithdrawals(1);
            loadStats();
            loadAgents(1);

        }else{

            toast(
                data.message ||
                'Unable to process withdrawal.',
                'error'
            );
        }

    }catch(error){

        console.error(error);

        toast(
            'Unable to process withdrawal.',
            'error'
        );

    }finally{

        approveButton.disabled = false;
        rejectButton.disabled = false;
    }
}


/* =========================================================================
   LEADERBOARD
========================================================================= */

async function loadLeaderboard(){

    const box =
        document.getElementById(
            'leaderboardTable'
        );

    const top =
        document.getElementById(
            'leaderboardTop'
        );

    box.innerHTML =
        '<div class="empty">Loading leaderboard...</div>';

    top.innerHTML = '';

    const month =
        document.getElementById(
            'leaderboardMonth'
        ).value;

    try{

        const data =
            await getJson(
                endpoint +
                '?ajax=leaderboard' +
                '&month=' +
                encodeURIComponent(
                    month
                ) +
                '&_=' +
                Date.now()
            );

        if(!data.success){

            box.innerHTML =
                '<div class="empty">' +
                'Unable to load leaderboard.' +
                '</div>';

            return;
        }

        document.getElementById(
            'leaderboardTarget'
        ).textContent =
            Number(
                data.target
            ).toLocaleString();

        if(!data.rows.length){

            box.innerHTML =
                '<div class="empty">' +
                'No agents have successful transactions for this month.' +
                '</div>';

            return;
        }

        /*
         * Top 3 cards.
         */
        let topHtml = '';

        for(let i = 0; i < 3; i++){

            const row =
                data.rows[i];

            if(!row){
                continue;
            }

            const medal =
                i === 0
                    ? '🥇'
                    : (
                        i === 1
                            ? '🥈'
                            : '🥉'
                    );

            topHtml +=

                '<div class="top-medal">' +

                '<div class="emoji">' +
                medal +
                '</div>' +

                '<strong>' +
                escapeHtml(
                    row.email
                ) +
                '</strong>' +

                '<span class="count">' +
                Number(
                    row.count
                ).toLocaleString() +
                ' successful transactions' +
                '</span>' +

                '</div>';
        }

        top.innerHTML =
            topHtml;


        /*
         * FULL TABLE
         *
         * EMAIL IS DISPLAYED HERE.
         */
        let html =
            '<table>' +

            '<thead>' +

            '<tr>' +
            '<th>Position</th>' +
            '<th>Agent Email</th>' +
            '<th>Referral</th>' +
            '<th>Transactions</th>' +
            '<th>Target Progress</th>' +
            '<th>Reward</th>' +
            '<th>Eligibility</th>' +
            '</tr>' +

            '</thead>' +

            '<tbody>';

        data.rows.forEach(
            row => {

                const percent =
                    Math.min(
                        100,
                        (
                            Number(
                                row.count
                            ) /
                            Math.max(
                                1,
                                Number(
                                    data.target
                                )
                            )
                        ) * 100
                    );

                let medal = '';

                if(
                    row.position === 1
                ){
                    medal = '🥇';
                }else if(
                    row.position === 2
                ){
                    medal = '🥈';
                }else if(
                    row.position === 3
                ){
                    medal = '🥉';
                }

                let rowClass = '';

                if(row.position === 1){
                    rowClass = 'gold-row';
                }else if(row.position === 2){
                    rowClass = 'silver-row';
                }else if(row.position === 3){
                    rowClass = 'bronze-row';
                }

                html +=
                    '<tr class="' +
                    rowClass +
                    '">' +

                    '<td>' +

                    '<strong style="font-size:17px;">' +

                    (
                        medal ||
                        '#' +
                        row.position
                    ) +

                    '</strong>' +

                    '</td>' +

                    /*
                     * AGENT EMAIL
                     */
                    '<td>' +

                    '<strong style="color:#fff;">' +
                    escapeHtml(
                        row.email ||
                        '—'
                    ) +
                    '</strong>' +

                    (
                        row.rank
                            ? '<br><span class="mini">' +
                              escapeHtml(
                                  row.rank
                              ) +
                              '</span>'
                            : ''
                    ) +

                    '</td>' +

                    '<td>' +

                    '<span class="cyan" style="font-weight:900;">' +
                    escapeHtml(
                        row.referral_code ||
                        '—'
                    ) +
                    '</span>' +

                    '</td>' +

                    '<td>' +

                    '<strong>' +
                    Number(
                        row.count
                    ).toLocaleString() +
                    '</strong>' +

                    '</td>' +

                    '<td>' +

                    Number(
                        percent
                    ).toFixed(0) +
                    '%' +

                    '<div class="progress">' +

                    '<div style="width:' +
                    percent +
                    '%;"></div>' +

                    '</div>' +

                    '</td>' +

                    '<td class="gold">' +

                    (
                        Number(
                            row.reward
                        ) > 0
                            ? money(
                                row.reward
                            )
                            : '—'
                    ) +

                    '</td>' +

                    '<td>' +

                    (
                        row.eligible

                            ? '<span class="eligibility eligible">✓ TARGET REACHED</span>'

                            : '<span class="eligibility not-eligible">• TARGET NOT REACHED</span>'
                    ) +

                    '</td>' +

                    '</tr>';
            }
        );

        html +=
            '</tbody></table>';

        box.innerHTML =
            html;

    }catch(error){

        console.error(error);

        box.innerHTML =
            '<div class="empty">' +
            'Unable to load leaderboard.' +
            '</div>';
    }
}


/* =========================================================================
   SAVE SETTINGS
========================================================================= */

document
    .getElementById(
        'settingsForm'
    )
    .addEventListener(
        'submit',
        async function(event){

            event.preventDefault();

            const fd =
                new FormData(this);

            fd.append(
                'ajax',
                'save_competition_settings'
            );

            try{

                const data =
                    await getJson(
                        endpoint,
                        {
                            method:'POST',
                            body:fd
                        }
                    );

                toast(
                    data.message ||
                    'Settings saved.',
                    data.success
                        ? 'success'
                        : 'error'
                );

                if(data.success){

                    const s =
                        data.settings;

                    document.getElementById(
                        'rewardGold'
                    ).textContent =
                        money(
                            s.prize_1
                        );

                    document.getElementById(
                        'rewardSilver'
                    ).textContent =
                        money(
                            s.prize_2
                        );

                    document.getElementById(
                        'rewardBronze'
                    ).textContent =
                        money(
                            s.prize_3
                        );

                    loadLeaderboard();
                }

            }catch(error){

                console.error(error);

                toast(
                    'Unable to save settings.',
                    'error'
                );
            }

        }
    );


/* =========================================================================
   PROCESS COMPETITION
========================================================================= */

async function processCompetition(){

    const month =
        document.getElementById(
            'processMonth'
        ).value;

    if(!month){

        toast(
            'Select a month.',
            'error'
        );

        return;
    }

    if(!confirm(
        'Process competition for ' +
        month +
        '?\n\n' +
        'Only agents with successful transactions ' +
        'will participate.\n\n' +
        'Only the top 3 can receive rewards.'
    )){
        return;
    }

    const fd =
        new FormData();

    fd.append(
        'ajax',
        'process_competition'
    );

    fd.append(
        'month',
        month
    );

    try{

        const data =
            await getJson(
                endpoint,
                {
                    method:'POST',
                    body:fd
                }
            );

        toast(
            data.message ||
            'Competition processed.',
            data.success
                ? 'success'
                : 'error'
        );

        if(data.success){

            loadLeaderboard();
            loadPreviousWinners();
            loadStats();
        }

    }catch(error){

        console.error(error);

        toast(
            'Unable to process competition.',
            'error'
        );
    }
}


/* =========================================================================
   PREVIOUS WINNERS
========================================================================= */

async function loadPreviousWinners(){

    const box =
        document.getElementById(
            'previousWinners'
        );

    box.innerHTML =
        '<div class="empty">Loading winners...</div>';

    try{

        const data =
            await getJson(
                endpoint +
                '?ajax=previous_winners&_=' +
                Date.now()
            );

        if(!data.success){

            box.innerHTML =
                '<div class="empty">' +
                'Unable to load winners.' +
                '</div>';

            return;
        }

        if(!data.rows.length){

            box.innerHTML =
                '<div class="empty">' +
                'No previous winners yet.' +
                '</div>';

            return;
        }

        let html =
            '<table>' +

            '<thead>' +

            '<tr>' +
            '<th>Month</th>' +
            '<th>Position</th>' +
            '<th>Agent Email</th>' +
            '<th>Transactions</th>' +
            '<th>Target</th>' +
            '<th>Prize</th>' +
            '<th>Eligible</th>' +
            '<th>Credited</th>' +
            '</tr>' +

            '</thead>' +

            '<tbody>';

        data.rows.forEach(
            row => {

                const medal =
                    Number(
                        row.position
                    ) === 1
                        ? '🥇 Gold'
                        : (
                            Number(
                                row.position
                            ) === 2
                                ? '🥈 Silver'
                                : '🥉 Bronze'
                        );

                html +=
                    '<tr>' +

                    '<td>' +
                    escapeHtml(
                        row.competition_month
                    ) +
                    '</td>' +

                    '<td>' +
                    medal +
                    '</td>' +

                    '<td>' +
                    '<strong>' +
                    escapeHtml(
                        row.user_email ||
                        ''
                    ) +
                    '</strong>' +
                    '</td>' +

                    '<td>' +
                    Number(
                        row.transaction_count ||
                        0
                    ).toLocaleString() +
                    '</td>' +

                    '<td>' +
                    Number(
                        row.target_transactions ||
                        0
                    ).toLocaleString() +
                    '</td>' +

                    '<td class="gold">' +
                    money(
                        row.prize_amount
                    ) +
                    '</td>' +

                    '<td>' +

                    (
                        Number(
                            row.eligible
                        ) === 1
                            ? '<span class="green">YES</span>'
                            : '<span class="red">NO</span>'
                    ) +

                    '</td>' +

                    '<td>' +

                    (
                        Number(
                            row.credited
                        ) === 1
                            ? '<span class="green">CREDITED</span>'
                            : '<span style="color:#ffc44d;">NOT CREDITED</span>'
                    ) +

                    '</td>' +

                    '</tr>';
            }
        );

        html +=
            '</tbody></table>';

        box.innerHTML =
            html;

    }catch(error){

        console.error(error);

        box.innerHTML =
            '<div class="empty">' +
            'Unable to load winners.' +
            '</div>';
    }
}


/* =========================================================================
   MODAL OUTSIDE CLICK
========================================================================= */

document
    .querySelectorAll('.modal')
    .forEach(
        modal => {

            modal.addEventListener(
                'click',
                event => {

                    if(
                        event.target ===
                        modal
                    ){

                        modal.style.display =
                            'none';
                    }

                }
            );

        }
    );


/* =========================================================================
   ENTER KEY SEARCH
========================================================================= */

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

            if(event.key === 'Enter'){
                event.preventDefault();
                loadAgents(1);
            }

        }
    );


/* =========================================================================
   INITIAL LOAD
========================================================================= */

loadStats();

loadAgents(1);

loadLeaderboard();

loadWithdrawals(1);

loadPreviousWinners();


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

setInterval(
    () => {

        loadStats();

        loadAgents(1);

        loadLeaderboard();

        loadWithdrawals(1);

    },
    30000
);

</script>

</body>
</html>