<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| ASOVERIFY AGENT ADMIN
|--------------------------------------------------------------------------
| File: admin_agent.php
|
| Uses the tables created by the manual ASOVERIFY Agent SQL.
| No CREATE TABLE statements are executed here.
|
| Admin session accepted:
|   $_SESSION['is_admin'] = true
| OR
|   $_SESSION['role'] = admin / superadmin / administrator
|
| Change aso_is_admin() if your existing admin system uses another
| session variable.
|--------------------------------------------------------------------------
*/

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

require_once __DIR__ . '/db.php';

if (!isset($conn) || !($conn instanceof mysqli)) {
    http_response_code(500);
    exit('Database connection ($conn) was not found in db.php.');
}

$conn->set_charset('utf8mb4');

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

function aso_is_admin(): bool
{
    if (!empty($_SESSION['admin'])) {
        return true;
    }

    $role = strtolower(trim((string)($_SESSION['role'] ?? '')));

    return in_array(
        $role,
        ['admin', 'superadmin', 'administrator'],
        true
    );
}

if (!aso_is_admin()) {
    http_response_code(403);
    ?>
    <!doctype html>
    <html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width,initial-scale=1">
        <title>Access Denied</title>
        <style>
            body{
                margin:0;
                min-height:100vh;
                display:flex;
                align-items:center;
                justify-content:center;
                background:#07152f;
                color:#fff;
                font-family:Arial,sans-serif;
            }
            .box{
                width:min(92%,430px);
                background:#0d254d;
                padding:30px;
                border-radius:18px;
                text-align:center;
                box-shadow:0 20px 50px #0006;
            }
            h1{margin-top:0}
        </style>
    </head>
    <body>
        <div class="box">
            <h1>Access Denied</h1>
            <p>You must be an ASOVERIFY administrator to access this page.</p>
        </div>
    </body>
    </html>
    <?php
    exit;
}

/*
|--------------------------------------------------------------------------
| DATABASE CHECK
|--------------------------------------------------------------------------
*/

try {
    $check = $conn->query(
        "SELECT id FROM aso_agent_settings WHERE id = 1 LIMIT 1"
    );

    if (!$check) {
        throw new RuntimeException(
            'ASOVERIFY Agent tables are missing. Import the supplied Agent SQL first.'
        );
    }

    $check->free();
} catch (Throwable $e) {
    http_response_code(500);
    exit(
        'Agent database error: ' .
        h($e->getMessage())
    );
}

/*
|--------------------------------------------------------------------------
| ACTIONS
|--------------------------------------------------------------------------
*/

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action !== '') {
    header('Content-Type: application/json; charset=utf-8');

    try {

        /*
         * SAVE GENERAL SETTINGS
         */
        if ($action === 'save_settings') {

            $registrationPrice = max(
                0,
                (float)($_POST['registration_price'] ?? 5000)
            );

            $defaultCommission = max(
                0,
                min(
                    100,
                    (float)($_POST['default_commission_percent'] ?? 5)
                )
            );

            $stmt = $conn->prepare(
                "UPDATE aso_agent_settings
                 SET registration_price = ?,
                     default_commission_percent = ?
                 WHERE id = 1"
            );

            $stmt->bind_param(
                'dd',
                $registrationPrice,
                $defaultCommission
            );

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

            echo json_encode([
                'success' => true,
                'message' => 'Agent settings updated successfully.'
            ]);
            exit;
        }

        /*
         * UPDATE ONE AGENT
         */
        if ($action === 'update_agent') {

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

            $commission = max(
                0,
                min(
                    100,
                    (float)($_POST['commission_percent'] ?? 0)
                )
            );

            $rank = strtolower(
                trim((string)($_POST['agent_rank'] ?? 'default_agent'))
            );

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

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

            if (!in_array(
                $rank,
                ['default_agent', 'super_agent', 'md'],
                true
            )) {
                throw new RuntimeException('Invalid agent rank.');
            }

            if (!in_array(
                $status,
                ['active', 'suspended'],
                true
            )) {
                throw new RuntimeException('Invalid agent status.');
            }

            $stmt = $conn->prepare(
                "UPDATE aso_agents
                 SET agent_rank = ?,
                     commission_percent = ?,
                     status = ?
                 WHERE id = ?
                 LIMIT 1"
            );

            $stmt->bind_param(
                'sdsi',
                $rank,
                $commission,
                $status,
                $agentId
            );

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

            echo json_encode([
                'success' => true,
                'message' => 'Agent updated successfully.'
            ]);
            exit;
        }

        /*
         * ADD / REMOVE COMMISSION WALLET BALANCE
         */
        if ($action === 'adjust_wallet') {

            $agentId = (int)($_POST['agent_id'] ?? 0);
            $amount = (float)($_POST['amount'] ?? 0);
            $type = strtolower(trim((string)($_POST['type'] ?? 'adjustment')));
            $description = trim((string)($_POST['description'] ?? ''));

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

            if (!in_array($type, ['credit', 'debit'], true)) {
                throw new RuntimeException('Invalid wallet action.');
            }

            if ($amount <= 0) {
                throw new RuntimeException('Enter a valid amount.');
            }

            $amount = round($amount, 2);

            $conn->begin_transaction();

            try {
                $stmt = $conn->prepare(
                    "SELECT amount
                     FROM aso_agent_wallet
                     WHERE agent_id = ?
                     LIMIT 1
                     FOR UPDATE"
                );

                $stmt->bind_param('i', $agentId);
                $stmt->execute();

                $wallet = $stmt->get_result()->fetch_assoc();

                $stmt->close();

                if (!$wallet) {
                    $stmt = $conn->prepare(
                        "INSERT INTO aso_agent_wallet
                         (agent_id, amount)
                         VALUES (?, 0)"
                    );

                    $stmt->bind_param('i', $agentId);
                    $stmt->execute();
                    $stmt->close();

                    $balance = 0;
                } else {
                    $balance = (float)$wallet['amount'];
                }

                if ($type === 'debit') {

                    if ($balance < $amount) {
                        throw new RuntimeException(
                            'Agent commission wallet does not have enough balance.'
                        );
                    }

                    $stmt = $conn->prepare(
                        "UPDATE aso_agent_wallet
                         SET amount = amount - ?
                         WHERE agent_id = ?
                         LIMIT 1"
                    );

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

                } else {

                    $stmt = $conn->prepare(
                        "UPDATE aso_agent_wallet
                         SET amount = amount + ?
                         WHERE agent_id = ?
                         LIMIT 1"
                    );

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

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

                $logAmount = $amount;

                $logDescription = $description !== ''
                    ? $description
                    : (
                        $type === 'credit'
                            ? 'Admin wallet credit'
                            : 'Admin wallet debit'
                    );

                $reference = 'ADMIN-' . strtoupper(
                    bin2hex(random_bytes(5))
                );

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

                $stmt->bind_param(
                    'idss',
                    $agentId,
                    $logAmount,
                    $logDescription,
                    $reference
                );

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

                $conn->commit();

                echo json_encode([
                    'success' => true,
                    'message' => 'Agent commission wallet updated.'
                ]);
                exit;

            } catch (Throwable $e) {
                $conn->rollback();
                throw $e;
            }
        }

        /*
         * APPROVE / REJECT WITHDRAWAL
         */
        if ($action === 'withdrawal') {

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

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

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

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

            if (!in_array(
                $decision,
                ['approve', 'reject'],
                true
            )) {
                throw new RuntimeException(
                    'Invalid withdrawal decision.'
                );
            }

            $conn->begin_transaction();

            try {

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

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

                $stmt->execute();

                $withdrawal =
                    $stmt->get_result()->fetch_assoc();

                $stmt->close();

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

                if ($withdrawal['status'] !== 'pending') {
                    throw new RuntimeException(
                        'This withdrawal has already been processed.'
                    );
                }

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

                $amount =
                    round(
                        (float)$withdrawal['amount'],
                        2
                    );

                if ($decision === 'reject') {

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

                    $stmt->bind_param(
                        'si',
                        $adminNote,
                        $withdrawalId
                    );

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

                    $conn->commit();

                    echo json_encode([
                        'success' => true,
                        'message' => 'Withdrawal rejected.'
                    ]);
                    exit;
                }

                /*
                 * APPROVAL:
                 * Lock wallet and deduct commission.
                 */
                $stmt = $conn->prepare(
                    "SELECT amount
                     FROM aso_agent_wallet
                     WHERE agent_id = ?
                     LIMIT 1
                     FOR UPDATE"
                );

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

                $stmt->execute();

                $wallet =
                    $stmt->get_result()->fetch_assoc();

                $stmt->close();

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

                if ($balance < $amount) {
                    throw new RuntimeException(
                        'Agent commission wallet does not have enough balance.'
                    );
                }

                $stmt = $conn->prepare(
                    "UPDATE aso_agent_wallet
                     SET amount = amount - ?
                     WHERE agent_id = ?
                       AND amount >= ?
                     LIMIT 1"
                );

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

                $stmt->execute();

                if ($stmt->affected_rows !== 1) {
                    $stmt->close();

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

                $stmt->close();

                $reference =
                    'AGENT-WD-' . $withdrawalId;

                $description =
                    'Approved agent commission withdrawal';

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

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

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

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

                $stmt->bind_param(
                    'si',
                    $adminNote,
                    $withdrawalId
                );

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

                $conn->commit();

                echo json_encode([
                    'success' => true,
                    'message' =>
                        'Withdrawal approved and commission deducted.'
                ]);
                exit;

            } catch (Throwable $e) {
                $conn->rollback();
                throw $e;
            }
        }

        /*
         * DELETE AGENT
         *
         * This removes the agent's own records only if there are no
         * transaction/withdrawal records. This prevents accidental
         * destruction of financial history.
         */
        if ($action === 'delete_agent') {

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

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

            $stmt = $conn->prepare(
                "SELECT
                    (SELECT COUNT(*)
                     FROM aso_agent_transactions
                     WHERE agent_id = ?) AS transactions_count,

                    (SELECT COUNT(*)
                     FROM aso_agent_withdrawals
                     WHERE agent_id = ?) AS withdrawals_count,

                    (SELECT COUNT(*)
                     FROM aso_agent_customers
                     WHERE agent_id = ?) AS customers_count"
            );

            $stmt->bind_param(
                'iii',
                $agentId,
                $agentId,
                $agentId
            );

            $stmt->execute();

            $counts =
                $stmt->get_result()->fetch_assoc();

            $stmt->close();

            if (
                (int)$counts['transactions_count'] > 0 ||
                (int)$counts['withdrawals_count'] > 0 ||
                (int)$counts['customers_count'] > 0
            ) {
                throw new RuntimeException(
                    'This agent has financial/customer history. Suspend the agent instead of deleting it.'
                );
            }

            $conn->begin_transaction();

            try {

                $stmt = $conn->prepare(
                    "DELETE FROM aso_agent_wallet
                     WHERE agent_id = ?
                     LIMIT 1"
                );

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

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

                $stmt = $conn->prepare(
                    "DELETE FROM aso_agents
                     WHERE id = ?
                     LIMIT 1"
                );

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

                $stmt->execute();

                if ($stmt->affected_rows !== 1) {
                    throw new RuntimeException(
                        'Agent not found.'
                    );
                }

                $stmt->close();

                $conn->commit();

                echo json_encode([
                    'success' => true,
                    'message' => 'Agent deleted.'
                ]);
                exit;

            } catch (Throwable $e) {
                $conn->rollback();
                throw $e;
            }
        }

        throw new RuntimeException(
            'Unknown admin action.'
        );

    } catch (Throwable $e) {

        http_response_code(400);

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

        exit;
    }
}

/*
|--------------------------------------------------------------------------
| SETTINGS
|--------------------------------------------------------------------------
*/

$settings = [
    'registration_price' => 5000,
    'default_commission_percent' => 5
];

$result = $conn->query(
    "SELECT registration_price,
            default_commission_percent
     FROM aso_agent_settings
     WHERE id = 1
     LIMIT 1"
);

if ($result) {
    $row = $result->fetch_assoc();

    if ($row) {
        $settings = $row;
    }

    $result->free();
}

/*
|--------------------------------------------------------------------------
| STATISTICS
|--------------------------------------------------------------------------
*/

$stats = [
    'agents' => 0,
    'active_agents' => 0,
    'customers' => 0,
    'transaction_value' => 0,
    'commission' => 0,
    'wallet_balance' => 0,
    'pending_withdrawals' => 0,
    'pending_withdrawal_amount' => 0
];

$result = $conn->query(
    "SELECT
        COUNT(*) AS agents,
        SUM(status = 'active') AS active_agents,
        COALESCE(SUM(total_customers),0) AS customers,
        COALESCE(SUM(total_transaction_amount),0) AS transaction_value,
        COALESCE(SUM(total_commission),0) AS commission
     FROM aso_agents"
);

if ($result) {
    $row = $result->fetch_assoc();

    if ($row) {
        $stats['agents'] =
            (int)$row['agents'];

        $stats['active_agents'] =
            (int)$row['active_agents'];

        $stats['customers'] =
            (int)$row['customers'];

        $stats['transaction_value'] =
            (float)$row['transaction_value'];

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

    $result->free();
}

$result = $conn->query(
    "SELECT
        COALESCE(SUM(amount),0) AS wallet_balance
     FROM aso_agent_wallet"
);

if ($result) {
    $row = $result->fetch_assoc();

    $stats['wallet_balance'] =
        (float)($row['wallet_balance'] ?? 0);

    $result->free();
}

$result = $conn->query(
    "SELECT
        COUNT(*) AS pending_withdrawals,
        COALESCE(SUM(amount),0) AS pending_amount
     FROM aso_agent_withdrawals
     WHERE status = 'pending'"
);

if ($result) {
    $row = $result->fetch_assoc();

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

    $stats['pending_withdrawal_amount'] =
        (float)($row['pending_amount'] ?? 0);

    $result->free();
}

/*
|--------------------------------------------------------------------------
| AGENTS
|--------------------------------------------------------------------------
*/

$agents = [];

$result = $conn->query(
    "SELECT
        a.id,
        a.user_email,
        a.referral_code,
        a.agent_rank,
        a.commission_percent,
        a.status,
        a.total_customers,
        a.total_transaction_amount,
        a.total_commission,
        a.created_at,
        COALESCE(w.amount,0) AS wallet_balance
     FROM aso_agents a
     LEFT JOIN aso_agent_wallet w
        ON w.agent_id = a.id
     ORDER BY
        a.total_transaction_amount DESC,
        a.total_customers DESC,
        a.total_commission DESC,
        a.id ASC"
);

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

    $result->free();
}

/*
|--------------------------------------------------------------------------
| WITHDRAWALS
|--------------------------------------------------------------------------
*/

$withdrawals = [];

$result = $conn->query(
    "SELECT
        w.id,
        w.agent_id,
        w.amount,
        w.bank_name,
        w.account_number,
        w.status,
        w.admin_note,
        w.created_at,
        w.processed_at,
        a.user_email,
        a.referral_code,
        COALESCE(aw.amount,0) AS wallet_balance
     FROM aso_agent_withdrawals w
     INNER JOIN aso_agents a
        ON a.id = w.agent_id
     LEFT JOIN aso_agent_wallet aw
        ON aw.agent_id = w.agent_id
     ORDER BY
        CASE
            WHEN w.status = 'pending' THEN 0
            WHEN w.status = 'approved' THEN 1
            ELSE 2
        END,
        w.id DESC
     LIMIT 500"
);

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

    $result->free();
}

/*
|--------------------------------------------------------------------------
| RECENT TRANSACTIONS
|--------------------------------------------------------------------------
*/

$transactions = [];

$result = $conn->query(
    "SELECT
        t.id,
        t.customer_email,
        t.external_transaction_id,
        t.service_name,
        t.transaction_amount,
        t.commission_percent,
        t.commission_amount,
        t.status,
        t.created_at,
        a.user_email AS agent_email
     FROM aso_agent_transactions t
     INNER JOIN aso_agents a
        ON a.id = t.agent_id
     ORDER BY t.id DESC
     LIMIT 200"
);

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

    $result->free();
}

/*
|--------------------------------------------------------------------------
| CUSTOMER LEADERBOARD
|--------------------------------------------------------------------------
*/

$customers = [];

$result = $conn->query(
    "SELECT
        c.customer_email,
        c.total_transactions,
        c.total_spend,
        c.total_commission,
        c.first_referred_at,
        c.last_transaction_at,
        a.user_email AS agent_email,
        a.agent_rank
     FROM aso_agent_customers c
     INNER JOIN aso_agents a
        ON a.id = c.agent_id
     ORDER BY c.total_spend DESC, c.total_transactions DESC
     LIMIT 200"
);

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

    $result->free();
}

function rankLabel(string $rank): string
{
    return match ($rank) {
        'super_agent' => 'SUPER AGENT',
        'md' => 'MD',
        default => 'DEFAULT AGENT'
    };
}

function statusClass(string $status): string
{
    return match (strtolower($status)) {
        'approved', 'active' => 'success',
        'rejected', 'suspended' => 'danger',
        default => 'warning'
    };
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>ASOVERIFY Agent Admin</title>

<style>
:root{
    --bg:#06132d;
    --panel:#0b2147;
    --panel2:#102d5c;
    --accent:#00d5ff;
    --text:#f4f8ff;
    --muted:#9fb5d2;
    --green:#29d17f;
    --red:#ff5e6c;
    --orange:#ffb84d;
    --border:rgba(255,255,255,.10);
}

*{
    box-sizing:border-box;
}

body{
    margin:0;
    color:var(--text);
    font-family:Arial,Helvetica,sans-serif;
    background:
        radial-gradient(circle at top right,#0e4b91 0,#071b3b 35%,#040d20 100%);
}

.container{
    width:min(1450px,96%);
    margin:auto;
    padding:18px;
}

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

.brand{
    font-size:27px;
    font-weight:900;
}

.brand span{
    color:var(--accent);
}

.admin-badge{
    background:#12345f;
    padding:9px 13px;
    border-radius:999px;
    font-size:12px;
    font-weight:800;
}

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

.card{
    background:rgba(11,33,71,.94);
    border:1px solid var(--border);
    border-radius:18px;
    padding:18px;
    margin-bottom:18px;
    box-shadow:0 18px 45px rgba(0,0,0,.20);
}

.stat{
    min-height:125px;
}

.stat .label{
    color:var(--muted);
    font-size:13px;
}

.stat .value{
    margin-top:9px;
    font-size:25px;
    font-weight:900;
}

.stat .sub{
    color:var(--muted);
    font-size:11px;
    margin-top:7px;
}

h1,h2,h3{
    margin-top:0;
}

h2{
    font-size:20px;
}

.muted{
    color:var(--muted);
}

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

label{
    display:block;
    color:var(--muted);
    font-size:12px;
    margin-bottom:6px;
}

input,select,textarea{
    width:100%;
    background:#06152f;
    border:1px solid var(--border);
    color:white;
    padding:11px;
    border-radius:10px;
    outline:none;
}

textarea{
    resize:vertical;
    min-height:80px;
}

button{
    border:0;
    background:var(--accent);
    color:#001522;
    font-weight:900;
    padding:11px 14px;
    border-radius:10px;
    cursor:pointer;
}

button:hover{
    filter:brightness(1.08);
}

.btn-red{
    background:var(--red);
    color:white;
}

.btn-orange{
    background:var(--orange);
    color:#201200;
}

.btn-small{
    padding:8px 10px;
    font-size:11px;
}

.table-wrap{
    overflow:auto;
}

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

th,td{
    padding:11px 9px;
    border-bottom:1px solid var(--border);
    text-align:left;
    vertical-align:middle;
}

th{
    color:var(--muted);
    font-size:11px;
    text-transform:uppercase;
    white-space:nowrap;
}

td{
    font-size:13px;
}

.badge{
    display:inline-block;
    padding:6px 9px;
    border-radius:999px;
    background:#173b6b;
    font-size:10px;
    font-weight:900;
    white-space:nowrap;
}

.success{
    color:var(--green);
}

.danger{
    color:var(--red);
}

.warning{
    color:var(--orange);
}

.tabs{
    display:flex;
    gap:8px;
    flex-wrap:wrap;
    margin-bottom:18px;
}

.tab{
    background:#102d5c;
    color:white;
    border:1px solid var(--border);
}

.tab.active{
    background:var(--accent);
    color:#001522;
}

.section{
    display:none;
}

.section.active{
    display:block;
}

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

.notice{
    background:#0a315e;
    border:1px solid rgba(0,213,255,.25);
    padding:12px;
    border-radius:11px;
    margin-bottom:15px;
}

@media(max-width:1050px){
    .stats{
        grid-template-columns:repeat(2,minmax(0,1fr));
    }
}

@media(max-width:650px){
    .container{
        width:100%;
        padding:10px;
    }

    .stats{
        grid-template-columns:1fr 1fr;
        gap:9px;
    }

    .stat{
        min-height:105px;
        padding:13px;
    }

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

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

    .card{
        padding:14px;
        border-radius:15px;
    }

    .brand{
        font-size:21px;
    }
}
</style>
</head>

<body>

<div class="container">

    <div class="header">
        <div class="brand">
            ASO<span>VERIFY</span> AGENT ADMIN
        </div>

        <div class="admin-badge">
            ADMIN CONTROL PANEL
        </div>
    </div>

    <!-- STATS -->

    <div class="stats">

        <div class="card stat">
            <div class="label">TOTAL AGENTS</div>
            <div class="value">
                <?= number_format($stats['agents']) ?>
            </div>
            <div class="sub">
                <?= number_format($stats['active_agents']) ?> active
            </div>
        </div>

        <div class="card stat">
            <div class="label">INVITED CUSTOMERS</div>
            <div class="value">
                <?= number_format($stats['customers']) ?>
            </div>
        </div>

        <div class="card stat">
            <div class="label">CUSTOMER TRANSACTIONS</div>
            <div class="value">
                ₦<?= number_format($stats['transaction_value'],2) ?>
            </div>
        </div>

        <div class="card stat">
            <div class="label">TOTAL COMMISSION</div>
            <div class="value success">
                ₦<?= number_format($stats['commission'],2) ?>
            </div>
        </div>

        <div class="card stat">
            <div class="label">AGENT WALLET BALANCE</div>
            <div class="value">
                ₦<?= number_format($stats['wallet_balance'],2) ?>
            </div>
        </div>

        <div class="card stat">
            <div class="label">PENDING WITHDRAWALS</div>
            <div class="value warning">
                <?= number_format($stats['pending_withdrawals']) ?>
            </div>
        </div>

        <div class="card stat">
            <div class="label">PENDING WITHDRAWAL VALUE</div>
            <div class="value warning">
                ₦<?= number_format($stats['pending_withdrawal_amount'],2) ?>
            </div>
        </div>

        <div class="card stat">
            <div class="label">REGISTRATION PRICE</div>
            <div class="value">
                ₦<?= number_format((float)$settings['registration_price'],2) ?>
            </div>
        </div>

    </div>

    <!-- TABS -->

    <div class="tabs">
        <button class="tab active" onclick="showTab('dashboard',this)">
            DASHBOARD
        </button>

        <button class="tab" onclick="showTab('agents',this)">
            AGENTS
        </button>

        <button class="tab" onclick="showTab('withdrawals',this)">
            WITHDRAWALS
        </button>

        <button class="tab" onclick="showTab('transactions',this)">
            TRANSACTIONS
        </button>

        <button class="tab" onclick="showTab('customers',this)">
            CUSTOMERS
        </button>

        <button class="tab" onclick="showTab('settings',this)">
            SETTINGS
        </button>
    </div>

    <!-- DASHBOARD -->

    <section id="dashboard" class="section active">

        <div class="card">
            <h2>Agent Ranking</h2>

            <p class="muted">
                Agents are ranked by the total transaction value generated
                by customers they invited. Customer count is the secondary
                ranking factor.
            </p>

            <div class="table-wrap">
                <table>
                    <thead>
                    <tr>
                        <th>#</th>
                        <th>Agent</th>
                        <th>Rank</th>
                        <th>Customers</th>
                        <th>Transaction Value</th>
                        <th>Commission</th>
                        <th>Wallet</th>
                    </tr>
                    </thead>

                    <tbody>

                    <?php foreach ($agents as $i => $agent): ?>

                        <tr>

                            <td>
                                <strong>
                                    <?= $i + 1 ?>
                                </strong>
                            </td>

                            <td>
                                <?= h((string)$agent['user_email']) ?>
                            </td>

                            <td>
                                <span class="badge">
                                    <?= h(rankLabel((string)$agent['agent_rank'])) ?>
                                </span>
                            </td>

                            <td>
                                <?= number_format((int)$agent['total_customers']) ?>
                            </td>

                            <td>
                                ₦<?= number_format(
                                    (float)$agent['total_transaction_amount'],
                                    2
                                ) ?>
                            </td>

                            <td class="success">
                                ₦<?= number_format(
                                    (float)$agent['total_commission'],
                                    2
                                ) ?>
                            </td>

                            <td>
                                ₦<?= number_format(
                                    (float)$agent['wallet_balance'],
                                    2
                                ) ?>
                            </td>

                        </tr>

                    <?php endforeach; ?>

                    </tbody>
                </table>
            </div>
        </div>

    </section>

    <!-- AGENTS -->

    <section id="agents" class="section">

        <div class="card">

            <h2>Manage Agents</h2>

            <div class="table-wrap">

                <table>

                    <thead>
                    <tr>
                        <th>Agent</th>
                        <th>Referral Code</th>
                        <th>Rank</th>
                        <th>Commission %</th>
                        <th>Customers</th>
                        <th>Transactions</th>
                        <th>Commission</th>
                        <th>Wallet</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                    </thead>

                    <tbody>

                    <?php foreach ($agents as $agent): ?>

                        <tr>

                            <td>
                                <?= h((string)$agent['user_email']) ?>
                            </td>

                            <td>
                                <span class="badge">
                                    <?= h((string)$agent['referral_code']) ?>
                                </span>
                            </td>

                            <td>

                                <select
                                    id="rank_<?= (int)$agent['id'] ?>"
                                >

                                    <option
                                        value="default_agent"
                                        <?= $agent['agent_rank'] === 'default_agent'
                                            ? 'selected'
                                            : '' ?>
                                    >
                                        DEFAULT AGENT
                                    </option>

                                    <option
                                        value="super_agent"
                                        <?= $agent['agent_rank'] === 'super_agent'
                                            ? 'selected'
                                            : '' ?>
                                    >
                                        SUPER AGENT
                                    </option>

                                    <option
                                        value="md"
                                        <?= $agent['agent_rank'] === 'md'
                                            ? 'selected'
                                            : '' ?>
                                    >
                                        MD
                                    </option>

                                </select>

                            </td>

                            <td>

                                <input
                                    id="commission_<?= (int)$agent['id'] ?>"
                                    type="number"
                                    min="0"
                                    max="100"
                                    step="0.01"
                                    value="<?= h(
                                        (string)$agent['commission_percent']
                                    ) ?>"
                                >

                            </td>

                            <td>
                                <?= number_format(
                                    (int)$agent['total_customers']
                                ) ?>
                            </td>

                            <td>
                                ₦<?= number_format(
                                    (float)$agent['total_transaction_amount'],
                                    2
                                ) ?>
                            </td>

                            <td class="success">
                                ₦<?= number_format(
                                    (float)$agent['total_commission'],
                                    2
                                ) ?>
                            </td>

                            <td>
                                ₦<?= number_format(
                                    (float)$agent['wallet_balance'],
                                    2
                                ) ?>
                            </td>

                            <td>

                                <select
                                    id="status_<?= (int)$agent['id'] ?>"
                                >

                                    <option
                                        value="active"
                                        <?= $agent['status'] === 'active'
                                            ? 'selected'
                                            : '' ?>
                                    >
                                        ACTIVE
                                    </option>

                                    <option
                                        value="suspended"
                                        <?= $agent['status'] === 'suspended'
                                            ? 'selected'
                                            : '' ?>
                                    >
                                        SUSPENDED
                                    </option>

                                </select>

                            </td>

                            <td>

                                <div class="actions">

                                    <button
                                        class="btn-small"
                                        onclick="updateAgent(
                                            <?= (int)$agent['id'] ?>
                                        )"
                                    >
                                        SAVE
                                    </button>

                                    <button
                                        class="btn-small btn-orange"
                                        onclick="walletAdjust(
                                            <?= (int)$agent['id'] ?>,
                                            '<?= h((string)$agent['user_email']) ?>'
                                        )"
                                    >
                                        WALLET
                                    </button>

                                </div>

                            </td>

                        </tr>

                    <?php endforeach; ?>

                    </tbody>

                </table>

            </div>

        </div>

    </section>

    <!-- WITHDRAWALS -->

    <section id="withdrawals" class="section">

        <div class="card">

            <h2>Agent Withdrawal Requests</h2>

            <p class="muted">
                Approving a withdrawal automatically deducts the approved
                amount from the agent's commission wallet.
            </p>

            <div class="table-wrap">

                <table>

                    <thead>
                    <tr>
                        <th>Date</th>
                        <th>Agent</th>
                        <th>Amount</th>
                        <th>Bank</th>
                        <th>Account</th>
                        <th>Wallet</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                    </thead>

                    <tbody>

                    <?php if (!$withdrawals): ?>

                        <tr>
                            <td colspan="8">
                                No withdrawal requests.
                            </td>
                        </tr>

                    <?php else: ?>

                        <?php foreach ($withdrawals as $withdrawal): ?>

                            <?php
                            $status =
                                strtolower(
                                    (string)$withdrawal['status']
                                );
                            ?>

                            <tr>

                                <td>
                                    <?= h(
                                        (string)$withdrawal['created_at']
                                    ) ?>
                                </td>

                                <td>
                                    <?= h(
                                        (string)$withdrawal['user_email']
                                    ) ?>
                                </td>

                                <td>
                                    <strong>
                                        ₦<?= number_format(
                                            (float)$withdrawal['amount'],
                                            2
                                        ) ?>
                                    </strong>
                                </td>

                                <td>
                                    <?= h(
                                        (string)$withdrawal['bank_name']
                                    ) ?>
                                </td>

                                <td>
                                    <?= h(
                                        (string)$withdrawal['account_number']
                                    ) ?>
                                </td>

                                <td>
                                    ₦<?= number_format(
                                        (float)$withdrawal['wallet_balance'],
                                        2
                                    ) ?>
                                </td>

                                <td
                                    class="<?= h(
                                        statusClass($status)
                                    ) ?>"
                                >
                                    <?= h(
                                        strtoupper($status)
                                    ) ?>
                                </td>

                                <td>

                                    <?php if ($status === 'pending'): ?>

                                        <div class="actions">

                                            <button
                                                class="btn-small"
                                                onclick="processWithdrawal(
                                                    <?= (int)$withdrawal['id'] ?>,
                                                    'approve'
                                                )"
                                            >
                                                APPROVE
                                            </button>

                                            <button
                                                class="btn-small btn-red"
                                                onclick="processWithdrawal(
                                                    <?= (int)$withdrawal['id'] ?>,
                                                    'reject'
                                                )"
                                            >
                                                REJECT
                                            </button>

                                        </div>

                                    <?php else: ?>

                                        <span class="muted">
                                            Processed
                                        </span>

                                    <?php endif; ?>

                                </td>

                            </tr>

                        <?php endforeach; ?>

                    <?php endif; ?>

                    </tbody>

                </table>

            </div>

        </div>

    </section>

    <!-- TRANSACTIONS -->

    <section id="transactions" class="section">

        <div class="card">

            <h2>Customer Transactions</h2>

            <div class="table-wrap">

                <table>

                    <thead>
                    <tr>
                        <th>Date</th>
                        <th>Agent</th>
                        <th>Customer</th>
                        <th>Service</th>
                        <th>Transaction ID</th>
                        <th>Amount</th>
                        <th>Commission %</th>
                        <th>Commission</th>
                        <th>Status</th>
                    </tr>
                    </thead>

                    <tbody>

                    <?php if (!$transactions): ?>

                        <tr>
                            <td colspan="9">
                                No agent transactions.
                            </td>
                        </tr>

                    <?php else: ?>

                        <?php foreach ($transactions as $transaction): ?>

                            <tr>

                                <td>
                                    <?= h(
                                        (string)$transaction['created_at']
                                    ) ?>
                                </td>

                                <td>
                                    <?= h(
                                        (string)$transaction['agent_email']
                                    ) ?>
                                </td>

                                <td>
                                    <?= h(
                                        (string)$transaction['customer_email']
                                    ) ?>
                                </td>

                                <td>
                                    <?= h(
                                        (string)($transaction['service_name'] ?: 'Service')
                                    ) ?>
                                </td>

                                <td>
                                    <?= h(
                                        (string)$transaction['external_transaction_id']
                                    ) ?>
                                </td>

                                <td>
                                    ₦<?= number_format(
                                        (float)$transaction['transaction_amount'],
                                        2
                                    ) ?>
                                </td>

                                <td>
                                    <?= number_format(
                                        (float)$transaction['commission_percent'],
                                        2
                                    ) ?>%
                                </td>

                                <td class="success">
                                    ₦<?= number_format(
                                        (float)$transaction['commission_amount'],
                                        2
                                    ) ?>
                                </td>

                                <td class="<?= h(
                                    statusClass(
                                        (string)$transaction['status']
                                    )
                                ) ?>">
                                    <?= h(
                                        strtoupper(
                                            (string)$transaction['status']
                                        )
                                    ) ?>
                                </td>

                            </tr>

                        <?php endforeach; ?>

                    <?php endif; ?>

                    </tbody>

                </table>

            </div>

        </div>

    </section>

    <!-- CUSTOMERS -->

    <section id="customers" class="section">

        <div class="card">

            <h2>Invited Customers</h2>

            <div class="table-wrap">

                <table>

                    <thead>
                    <tr>
                        <th>Customer</th>
                        <th>Agent</th>
                        <th>Agent Rank</th>
                        <th>Transactions</th>
                        <th>Total Spend</th>
                        <th>Commission</th>
                        <th>First Referred</th>
                        <th>Last Transaction</th>
                    </tr>
                    </thead>

                    <tbody>

                    <?php if (!$customers): ?>

                        <tr>
                            <td colspan="8">
                                No invited customers.
                            </td>
                        </tr>

                    <?php else: ?>

                        <?php foreach ($customers as $customer): ?>

                            <tr>

                                <td>
                                    <?= h(
                                        (string)$customer['customer_email']
                                    ) ?>
                                </td>

                                <td>
                                    <?= h(
                                        (string)$customer['agent_email']
                                    ) ?>
                                </td>

                                <td>
                                    <span class="badge">
                                        <?= h(
                                            rankLabel(
                                                (string)$customer['agent_rank']
                                            )
                                        ) ?>
                                    </span>
                                </td>

                                <td>
                                    <?= number_format(
                                        (int)$customer['total_transactions']
                                    ) ?>
                                </td>

                                <td>
                                    ₦<?= number_format(
                                        (float)$customer['total_spend'],
                                        2
                                    ) ?>
                                </td>

                                <td class="success">
                                    ₦<?= number_format(
                                        (float)$customer['total_commission'],
                                        2
                                    ) ?>
                                </td>

                                <td>
                                    <?= h(
                                        (string)$customer['first_referred_at']
                                    ) ?>
                                </td>

                                <td>
                                    <?= h(
                                        (string)($customer['last_transaction_at'] ?? '-')
                                    ) ?>
                                </td>

                            </tr>

                        <?php endforeach; ?>

                    <?php endif; ?>

                    </tbody>

                </table>

            </div>

        </div>

    </section>

    <!-- SETTINGS -->

    <section id="settings" class="section">

        <div class="card">

            <h2>Agent System Settings</h2>

            <div class="notice">
                Changes here affect new agent registrations and the default
                commission percentage assigned to newly registered agents.
            </div>

            <form id="settingsForm">

                <input
                    type="hidden"
                    name="action"
                    value="save_settings"
                >

                <div class="form-grid">

                    <div>

                        <label>
                            AGENT REGISTRATION PRICE
                        </label>

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

                    </div>

                    <div>

                        <label>
                            DEFAULT COMMISSION PERCENTAGE
                        </label>

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

                    </div>

                </div>

                <br>

                <button type="submit">
                    SAVE SETTINGS
                </button>

            </form>

        </div>

        <div class="card">

            <h2>Wallet Adjustment</h2>

            <p class="muted">
                Admin can manually credit or debit an agent commission wallet.
                Every adjustment is recorded in the wallet log.
            </p>

            <div class="form-grid">

                <div>

                    <label>
                        SELECT AGENT
                    </label>

                    <select id="walletAgent">

                        <option value="">
                            Select agent
                        </option>

                        <?php foreach ($agents as $agent): ?>

                            <option value="<?= (int)$agent['id'] ?>">
                                <?= h(
                                    (string)$agent['user_email']
                                ) ?>
                                — ₦<?= number_format(
                                    (float)$agent['wallet_balance'],
                                    2
                                ) ?>
                            </option>

                        <?php endforeach; ?>

                    </select>

                </div>

                <div>

                    <label>
                        ACTION
                    </label>

                    <select id="walletType">

                        <option value="credit">
                            CREDIT
                        </option>

                        <option value="debit">
                            DEBIT
                        </option>

                    </select>

                </div>

                <div>

                    <label>
                        AMOUNT
                    </label>

                    <input
                        id="walletAmount"
                        type="number"
                        min="0.01"
                        step="0.01"
                        placeholder="Amount"
                    >

                </div>

                <div>

                    <label>
                        DESCRIPTION
                    </label>

                    <input
                        id="walletDescription"
                        type="text"
                        maxlength="255"
                        placeholder="Reason"
                    >

                </div>

            </div>

            <br>

            <button onclick="applyWalletAdjustment()">
                UPDATE WALLET
            </button>

        </div>

    </section>

</div>

<script>
async function postData(formData) {

    const response = await fetch(location.href, {
        method: 'POST',
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: formData
    });

    let data;

    try {
        data = await response.json();
    } catch (e) {
        throw new Error('Invalid server response.');
    }

    if (!response.ok || !data.success) {
        throw new Error(
            data.message || 'Request failed.'
        );
    }

    return data;
}

function showTab(id, button) {

    document
        .querySelectorAll('.section')
        .forEach(section => {
            section.classList.remove('active');
        });

    document
        .querySelectorAll('.tab')
        .forEach(tab => {
            tab.classList.remove('active');
        });

    document
        .getElementById(id)
        .classList.add('active');

    button.classList.add('active');
}

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

        e.preventDefault();

        try {

            const data =
                await postData(
                    new FormData(this)
                );

            alert(data.message);

            location.reload();

        } catch (error) {

            alert(error.message);
        }

    });

async function updateAgent(agentId) {

    const fd = new FormData();

    fd.append(
        'action',
        'update_agent'
    );

    fd.append(
        'agent_id',
        agentId
    );

    fd.append(
        'agent_rank',
        document.getElementById(
            'rank_' + agentId
        ).value
    );

    fd.append(
        'commission_percent',
        document.getElementById(
            'commission_' + agentId
        ).value
    );

    fd.append(
        'status',
        document.getElementById(
            'status_' + agentId
        ).value
    );

    try {

        const data =
            await postData(fd);

        alert(data.message);

        location.reload();

    } catch (error) {

        alert(error.message);
    }
}

async function processWithdrawal(
    withdrawalId,
    decision
) {

    let note = '';

    if (decision === 'approve') {

        if (!confirm(
            'Approve this withdrawal?\n\n' +
            'The withdrawal amount will be deducted ' +
            'from the agent commission wallet.'
        )) {
            return;
        }

        note =
            prompt(
                'Admin note (optional):',
                ''
            ) || '';

    } else {

        note =
            prompt(
                'Reason for rejection:',
                ''
            ) || '';

    }

    const fd = new FormData();

    fd.append(
        'action',
        'withdrawal'
    );

    fd.append(
        'withdrawal_id',
        withdrawalId
    );

    fd.append(
        'decision',
        decision
    );

    fd.append(
        'admin_note',
        note
    );

    try {

        const data =
            await postData(fd);

        alert(data.message);

        location.reload();

    } catch (error) {

        alert(error.message);
    }
}

async function walletAdjust(
    agentId,
    email
) {

    const type =
        prompt(
            'Enter CREDIT or DEBIT:',
            'CREDIT'
        );

    if (!type) {
        return;
    }

    const normalized =
        type.toLowerCase().trim();

    if (
        normalized !== 'credit' &&
        normalized !== 'debit'
    ) {
        alert('Enter CREDIT or DEBIT.');
        return;
    }

    const amount =
        prompt(
            'Amount for ' +
            email +
            ':'
        );

    if (!amount || Number(amount) <= 0) {
        return;
    }

    const description =
        prompt(
            'Reason:',
            'Admin wallet adjustment'
        ) || '';

    const fd = new FormData();

    fd.append(
        'action',
        'adjust_wallet'
    );

    fd.append(
        'agent_id',
        agentId
    );

    fd.append(
        'type',
        normalized
    );

    fd.append(
        'amount',
        amount
    );

    fd.append(
        'description',
        description
    );

    try {

        const data =
            await postData(fd);

        alert(data.message);

        location.reload();

    } catch (error) {

        alert(error.message);
    }
}

async function applyWalletAdjustment() {

    const agent =
        document.getElementById(
            'walletAgent'
        ).value;

    const type =
        document.getElementById(
            'walletType'
        ).value;

    const amount =
        document.getElementById(
            'walletAmount'
        ).value;

    const description =
        document.getElementById(
            'walletDescription'
        ).value;

    if (!agent) {
        alert('Select an agent.');
        return;
    }

    if (!amount || Number(amount) <= 0) {
        alert('Enter a valid amount.');
        return;
    }

    const fd = new FormData();

    fd.append(
        'action',
        'adjust_wallet'
    );

    fd.append(
        'agent_id',
        agent
    );

    fd.append(
        'type',
        type
    );

    fd.append(
        'amount',
        amount
    );

    fd.append(
        'description',
        description
    );

    try {

        const data =
            await postData(fd);

        alert(data.message);

        location.reload();

    } catch (error) {

        alert(error.message);
    }
}
</script>

</body>
</html>
