<?php
declare(strict_types=1);

/**
 * ============================================================================
 * ASOVERIFY — ADMIN DASHBOARD WITH SERVICE ACCESS CONTROL
 * ============================================================================
 * File: dashboard.php
 *
 * FEATURES
 * 1. Existing ASOVERIFY admin session.
 * 2. MD has access to all dashboard service boxes.
 * 3. Other ranks can open only services assigned by MD.
 * 4. Unassigned service boxes are visibly disabled.
 * 5. MD-only service assignment shortcut.
 * 6. Live database record counts.
 * 7. Responsive blue/white dashboard design.
 * 8. Prepared SQL statements and output escaping.
 *
 * IMPORTANT:
 * The direct PHP service pages must also contain the permission check
 * provided previously. Dashboard filtering alone is not sufficient security.
 * ============================================================================
 */

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

require_once __DIR__ . '/db.php';

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

if (!isset($conn) || !($conn instanceof mysqli)) {
    http_response_code(500);
    exit('Database connection unavailable.');
}

$conn->set_charset('utf8mb4');

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

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

function tableExists(mysqli $conn, string $table): bool
{
    $stmt = $conn->prepare(
        "SELECT COUNT(*) AS total
         FROM information_schema.tables
         WHERE table_schema = DATABASE()
           AND table_name = ?"
    );

    $stmt->bind_param('s', $table);
    $stmt->execute();

    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();

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

function countRows(mysqli $conn, string $table): int
{
    if (!preg_match('/^[a-zA-Z0-9_]+$/', $table)) {
        return 0;
    }

    if (!tableExists($conn, $table)) {
        return 0;
    }

    $result = $conn->query("SELECT COUNT(*) AS total FROM `$table`");
    $row = $result->fetch_assoc();

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

function formatInt($number): string
{
    return number_format((int)$number);
}

function formatMoney($amount): string
{
    return number_format((float)$amount, 2);
}

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

if (empty($_SESSION['admin'])) {
    header('Location: admin_login.php');
    exit;
}

/*
 * Prefer the admin database ID stored during login.
 * Otherwise, use the email/name stored in the existing admin session.
 */

$adminAccount = null;

if (!empty($_SESSION['admin_id'])) {
    $adminId = (int)$_SESSION['admin_id'];

    $stmt = $conn->prepare(
        "SELECT id, name, email, admin_rank
         FROM admin
         WHERE id = ?
         LIMIT 1"
    );

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

    $adminAccount = $stmt->get_result()->fetch_assoc();
    $stmt->close();
}

if (!$adminAccount) {
    $identity = trim((string)$_SESSION['admin']);

    $stmt = $conn->prepare(
        "SELECT id, name, email, admin_rank
         FROM admin
         WHERE email = ? OR name = ?
         LIMIT 1"
    );

    $stmt->bind_param('ss', $identity, $identity);
    $stmt->execute();

    $adminAccount = $stmt->get_result()->fetch_assoc();
    $stmt->close();
}

if (!$adminAccount) {
    http_response_code(403);
    exit('Admin account not found. Please log in again.');
}

$currentAdminId = (int)$adminAccount['id'];
$currentAdminName = (string)$adminAccount['name'];
$currentAdminRank = strtoupper(
    trim((string)($adminAccount['admin_rank'] ?? ''))
);

$isMD = ($currentAdminRank === 'MD');

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

$requestTables = [
    'transactions',
    'bvn_verification_logs',
    'bypass_requests',
    'data_transactions',
    'delink',
    'ipe_requests',
    'modification_requests',
    'nin_results',
    'personalization',
    'validation_requests',
    'agent_registration',
    'nin_result_new',
    'service_profits',
    'dashboard_services',
    'data_plans',
    'bvn_results',
    'bvn_modification_transactions',
    'api_prices',
    'api_keys',
    'api_transactions',
    'transaction',
    'vip_users',
    'referral_earnings',
    'bvn_api_responses',
    'enrolment_requests',
    'zepa_nin_verify',
    'agents',
    'nin_demo_simple',
    'vnin_transactions',
    'bvn_phone_logs',
    'unifiy_new',
    'unifiy_phone',
    'nin_details',
    'ipe_request',
    'nin_validation',
    'admin',
    'self_delink',
    'balance',
    'nin_request',
    'popup_message',
    'smod_requests',
    'tin_requests',
    'nonfresh_requests',
    'nimc_requests',
    'refund_transactions',
    'enroll_requests',
    'all_transactions',
    'all_transaction',
    'enrolment_request',
    'aso_agents',
    'nin_search_history',
    'unified_verifications',
    'active_customers',
    'funding_transactions',
    'tin_registrations',
    'zenithpay_webhook_transactions',
    'virtual_accounts'
];

$counts = [];

foreach ($requestTables as $table) {
    $counts[$table] = countRows($conn, $table);
}

/*
 * This preserves the original dashboard's total-record calculation.
 * Because it sums multiple tables, the result represents total table records,
 * not necessarily unique business transactions.
 */

$totalRecords = array_sum($counts);

$usersCount = 0;

if (tableExists($conn, 'customers')) {
    $usersCount = countRows($conn, 'customers');
}

$totalBalance = 0.00;

if (tableExists($conn, 'total_users_balance')) {
    $result = $conn->query(
        "SELECT COALESCE(SUM(total_amount), 0) AS total
         FROM total_users_balance"
    );

    $row = $result->fetch_assoc();
    $totalBalance = (float)($row['total'] ?? 0);
}

/* ============================================================================
   DASHBOARD SERVICE REGISTRY
============================================================================ */

$cards = [
    [
        'title' => 'API PROFIT',
        'count' => $counts['api_transactions'],
        'icon' => 'fa-code',
        'link' => 'admin_profit.php'
    ],
    [
        'title' => 'TIN ADMIN',
        'count' => $counts['tin_registrations'],
        'icon' => 'fa-file-invoice',
        'link' => 'admin_tin_registration.php'
    ],
    [
        'title' => 'TIN CERTIFICATES',
        'count' => $counts['tin_requests'],
        'icon' => 'fa-certificate',
        'link' => 'admin_tin_certificates.php'
    ],
    [
        'title' => 'SABILPAY ADMIN',
        'count' => $counts['popup_message'],
        'icon' => 'fa-building-columns',
        'link' => '../sabilpay/admin/login.php'
    ],
    [
        'title' => 'EMAIL CUSTOMERS',
        'count' => $counts['popup_message'],
        'icon' => 'fa-envelope',
        'link' => 'admin_send.php'
    ],
    [
        'title' => 'MANAGE USERS',
        'count' => $counts['active_customers'],
        'icon' => 'fa-users-gear',
        'link' => '../admin/users.php'
    ],
    [
        'title' => 'PAYMENT',
        'count' => $counts['zenithpay_webhook_transactions'],
        'icon' => 'fa-credit-card',
        'link' => '../payment.php'
    ],
    [
        'title' => 'VIRTUAL ACCOUNTS',
        'count' => $counts['virtual_accounts'],
        'icon' => 'fa-building-columns',
        'link' => 'admin_virtual.php'
    ],
    [
        'title' => 'ASOVERIFY AGENT ADMIN',
        'count' => $counts['aso_agents'],
        'icon' => 'fa-clipboard-check',
        'link' => '../admin/admin_agent.php'
    ],
    [
        'title' => 'VALIDATION ADMIN',
        'count' => $counts['validation_requests'],
        'icon' => 'fa-clipboard-check',
        'link' => '../admin/admin_validation.php'
    ],
    [
        'title' => 'VALIDATION SEND',
        'count' => $counts['validation_requests'],
        'icon' => 'fa-paper-plane',
        'link' => '../admin/nin_customer_support.php'
    ],
    [
        'title' => 'VALIDATION REPORT',
        'count' => $counts['validation_requests'],
        'icon' => 'fa-chart-line',
        'link' => '../admin/inbox_val.php'
    ],
    [
        'title' => 'API IPE',
        'count' => $counts['ipe_request'],
        'icon' => 'fa-plug',
        'link' => '../admin/admin_ipe2.php'
    ],
    [
        'title' => 'IPE STATUS CHECK',
        'count' => $counts['ipe_requests'],
        'icon' => 'fa-magnifying-glass-chart',
        'link' => 'admin_ipe_requests.php'
    ],
    [
        'title' => 'BVN PHONE ADMIN',
        'count' => $counts['bvn_phone_logs'],
        'icon' => 'fa-phone',
        'link' => 'bvn_admin_phone.php'
    ],
    [
        'title' => 'MANUAL TRANS',
        'count' => $counts['funding_transactions'],
        'icon' => 'fa-money-bill-transfer',
        'link' => 'admin_manual_funding.php'
    ],
    [
        'title' => 'MAIN VERIFY AGENT',
        'count' => $counts['nimc_requests'],
        'icon' => 'fa-shield-halved',
        'link' => 'mainverify.php'
    ],
    [
        'title' => 'NIN AGENT',
        'count' => $counts['agents'],
        'icon' => 'fa-user-secret',
        'link' => 'admin_add_agent.php'
    ],
    [
        'title' => 'MESSAGE TO USER',
        'count' => $counts['popup_message'],
        'icon' => 'fa-comment-dots',
        'link' => 'admin_demo.php'
    ],
    [
        'title' => 'UNIFY TRANSACTIONS',
        'count' => $counts['all_transactions'],
        'icon' => 'fa-arrows-rotate',
        'link' => 'admin_nindetails.php'
    ],
    [
        'title' => 'VALIDATION REFUND',
        'count' => $counts['refund_transactions'],
        'icon' => 'fa-rotate-left',
        'link' => '../admin/refund.php'
    ],
    [
        'title' => 'DELINK ADMIN',
        'count' => $counts['self_delink'],
        'icon' => 'fa-link-slash',
        'link' => '../admin/admin_delink.php'
    ],
    [
        'title' => 'FUNDING ADMIN',
        'count' => $counts['transaction'],
        'icon' => 'fa-wallet',
        'link' => '../admin/users_balance.php'
    ],
    [
        'title' => 'SECOND MOD',
        'count' => $counts['smod_requests'],
        'icon' => 'fa-pen-to-square',
        'link' => 'admin_modify2.php'
    ],
    [
        'title' => 'MODIFICATION ADMIN',
        'count' => $counts['modification_requests'],
        'icon' => 'fa-file-pen',
        'link' => '../admin/admin_mod.php'
    ],
    [
        'title' => 'MOD PENDING',
        'count' => $counts['modification_requests'],
        'icon' => 'fa-hourglass-half',
        'link' => '../admin/admin_mod2.php'
    ],
    [
        'title' => 'PERSONALIZATION',
        'count' => $counts['personalization'],
        'icon' => 'fa-id-card',
        'link' => 'admin_personalize.php'
    ],
    [
        'title' => 'IPE CLEARANCE',
        'count' => $counts['ipe_requests'],
        'icon' => 'fa-certificate',
        'link' => '../admin/admin_ipe5.php'
    ],
    [
        'title' => 'BVN PLASTIC2',
        'count' => $counts['bvn_api_responses'],
        'icon' => 'fa-chart-line',
        'link' => 'bvn_admin.php'
    ],
    [
        'title' => 'TRANSACTIONS',
        'count' => $counts['all_transaction'],
        'icon' => 'fa-right-left',
        'link' => '../admin/transaction.php'
    ],
    [
        'title' => 'USERS MANAGER',
        'count' => '₦' . formatMoney($totalBalance),
        'icon' => 'fa-wallet',
        'link' => 'admin_users.php'
    ],
    [
        'title' => 'BVN ADMIN',
        'count' => $counts['bvn_verification_logs'],
        'icon' => 'fa-fingerprint',
        'link' => 'admin_bvn.php'
    ],
    [
        'title' => 'NIN & PHONE',
        'count' => $counts['nin_result_new'],
        'icon' => 'fa-mobile-screen',
        'link' => 'nin_results_admin.php'
    ],
    [
        'title' => 'VNIN ADMIN',
        'count' => $counts['vnin_transactions'],
        'icon' => 'fa-id-card-clip',
        'link' => 'vnin_admin.php'
    ],
    [
        'title' => 'DATAV NIN',
        'count' => $counts['unified_verifications'],
        'icon' => 'fa-id-card',
        'link' => 'admin_datav.php'
    ],
    [
        'title' => 'MANAGE SERVICE',
        'count' => $counts['dashboard_services'],
        'icon' => 'fa-sliders',
        'link' => 'manage_services.php'
    ],
    [
        'title' => 'BVN MOD ADMIN',
        'count' => $counts['bvn_modification_transactions'],
        'icon' => 'fa-gears',
        'link' => 'admin_bvn_modifications.php'
    ],
    [
        'title' => 'API PRICE CTRL',
        'count' => $counts['api_prices'],
        'icon' => 'fa-tags',
        'link' => 'api_prices.php'
    ],
    [
        'title' => 'API USERS CTRL',
        'count' => $counts['api_keys'],
        'icon' => 'fa-key',
        'link' => 'admin_api_users.php'
    ],
    [
        'title' => 'API TRANSACTION',
        'count' => $counts['api_transactions'],
        'icon' => 'fa-code',
        'link' => 'api_transactions_report.php'
    ],
    [
        'title' => 'BVN USERS',
        'count' => $counts['agent_registration'],
        'icon' => 'fa-user-check',
        'link' => 'bvn_agent.php'
    ],
    [
        'title' => 'VIP USERS',
        'count' => $counts['vip_users'],
        'icon' => 'fa-crown',
        'link' => 'vip_users.php'
    ],
    [
        'title' => 'REFERRAL USERS',
        'count' => $counts['referral_earnings'],
        'icon' => 'fa-hand-holding-dollar',
        'link' => 'referral_admin.php'
    ],
    [
        'title' => 'PRICE MANAGER',
        'count' => $counts['admin'],
        'icon' => 'fa-chart-bar',
        'link' => 'price_maneger.php'
    ]
];

/* ============================================================================
   LOAD ASSIGNMENTS
============================================================================ */

$allowedLinks = [];

if ($isMD) {
    // MD is allowed to use all registered dashboard service boxes.
    foreach ($cards as $card) {
        $allowedLinks[] = (string)$card['link'];
    }
} elseif (tableExists($conn, 'admin_service_assignments')) {
    $stmt = $conn->prepare(
        "SELECT service_key
         FROM admin_service_assignments
         WHERE admin_id = ?"
    );

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

    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $allowedLinks[] = (string)$row['service_key'];
    }

    $stmt->close();
}

$allowedLinks = array_values(array_unique($allowedLinks));

$assignedServicesCount = 0;

foreach ($cards as $card) {
    if (in_array((string)$card['link'], $allowedLinks, true)) {
        $assignedServicesCount++;
    }
}

/* ============================================================================
   CLOSE CONNECTION AFTER ALL DATABASE QUERIES
============================================================================ */

$conn->close();

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>ASOVERIFY | Admin Dashboard</title>

<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" rel="stylesheet">

<style>
:root {
    --blue: #087bea;
    --deep-blue: #064b9c;
    --sky: #00bfff;
    --navy: #102b50;
    --white: #ffffff;
    --bg: #f2f7ff;
    --text: #173252;
    --muted: #71829b;
    --border: #e1eaf5;
    --green: #07885b;
    --shadow: 0 10px 30px rgba(26, 73, 125, .09);
}

* {
    box-sizing: border-box;
}

html {
    scroll-behavior: smooth;
}

body {
    margin: 0;
    min-height: 100vh;
    font-family: Inter, Arial, sans-serif;
    color: var(--text);
    background:
        radial-gradient(ellipse at top right, #dceeff 0%, transparent 36%),
        linear-gradient(135deg, #f8fbff, #edf5ff);
}

a {
    -webkit-tap-highlight-color: transparent;
}

.topbar {
    position: sticky;
    top: 0;
    z-index: 100;
    background: rgba(255,255,255,.94);
    backdrop-filter: blur(18px);
    -webkit-backdrop-filter: blur(18px);
    border-bottom: 1px solid var(--border);
    box-shadow: 0 4px 20px rgba(18,60,105,.05);
}

.top-inner {
    max-width: 1550px;
    margin: auto;
    padding: 13px 22px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 14px;
}

.brand {
    display: flex;
    align-items: center;
    gap: 12px;
}

.brand-logo {
    width: 46px;
    height: 46px;
    border-radius: 15px;
    display: grid;
    place-items: center;
    color: white;
    font-size: 21px;
    background: linear-gradient(135deg, var(--sky), var(--deep-blue));
    box-shadow: 0 8px 20px rgba(8,123,234,.24);
}

.brand-title {
    font-size: 20px;
    font-weight: 900;
    letter-spacing: -.8px;
    color: var(--deep-blue);
}

.brand-subtitle {
    margin-top: 3px;
    font-size: 9px;
    font-weight: 800;
    letter-spacing: 1.6px;
    color: var(--muted);
}

.header-right {
    display: flex;
    align-items: center;
    gap: 9px;
    flex-wrap: wrap;
}

.admin-chip {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    background: #edf6ff;
    border: 1px solid #d6eaff;
    padding: 10px 13px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 800;
}

.rank-chip {
    display: inline-flex;
    align-items: center;
    padding: 5px 8px;
    border-radius: 7px;
    background: #dcecff;
    color: #0756b5;
    font-size: 9px;
    font-weight: 900;
}

.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 11px 15px;
    border: 0;
    border-radius: 11px;
    text-decoration: none;
    font-family: inherit;
    font-size: 11px;
    font-weight: 800;
    cursor: pointer;
    transition: .2s;
}

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

.btn-primary {
    color: #fff;
    background: linear-gradient(135deg, var(--blue), var(--deep-blue));
    box-shadow: 0 5px 14px rgba(8,123,234,.2);
}

.btn-light {
    color: var(--deep-blue);
    background: #edf6ff;
    border: 1px solid #dcecff;
}

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

.container {
    max-width: 1550px;
    margin: auto;
    padding: 24px 20px 45px;
}

.hero {
    position: relative;
    overflow: hidden;
    padding: 28px;
    border-radius: 24px;
    color: white;
    background: linear-gradient(115deg, #062b63, #087bea 66%, #00bfff);
    box-shadow: 0 16px 38px rgba(8,105,213,.20);
    margin-bottom: 20px;
}

.hero::after {
    content: "";
    position: absolute;
    width: 280px;
    height: 280px;
    border-radius: 50%;
    right: -75px;
    top: -135px;
    border: 45px solid rgba(255,255,255,.08);
    pointer-events: none;
}

.hero-content {
    position: relative;
    z-index: 1;
}

.hero h1 {
    margin: 0 0 9px;
    font-size: clamp(24px, 4vw, 34px);
    font-weight: 900;
    letter-spacing: -1px;
}

.hero p {
    margin: 0;
    color: #e0efff;
    font-size: 12px;
    line-height: 1.8;
}

.hero-meta {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
    margin-top: 15px;
}

.hero-pill {
    display: inline-flex;
    align-items: center;
    gap: 7px;
    padding: 8px 11px;
    border: 1px solid rgba(255,255,255,.22);
    border-radius: 9px;
    background: rgba(255,255,255,.12);
    font-size: 10px;
    font-weight: 800;
}

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

.stat {
    display: flex;
    align-items: center;
    gap: 14px;
    min-width: 0;
    padding: 19px;
    border: 1px solid var(--border);
    border-radius: 19px;
    background: #fff;
    box-shadow: var(--shadow);
    transition: transform .2s;
}

.stat:hover {
    transform: translateY(-3px);
}

.stat-icon {
    flex-shrink: 0;
    width: 48px;
    height: 48px;
    display: grid;
    place-items: center;
    border-radius: 15px;
    color: #fff;
    font-size: 19px;
}

.stat-blue .stat-icon {
    background: linear-gradient(135deg, #087bea, #064b9c);
}

.stat-green .stat-icon {
    background: linear-gradient(135deg, #10b981, #047857);
}

.stat-purple .stat-icon {
    background: linear-gradient(135deg, #8b5cf6, #5b21b6);
}

.stat-label {
    font-size: 9px;
    font-weight: 800;
    letter-spacing: .8px;
    color: var(--muted);
    text-transform: uppercase;
}

.stat-value {
    margin-top: 7px;
    font-size: clamp(19px, 2.5vw, 27px);
    line-height: 1.15;
    font-weight: 900;
    overflow-wrap: anywhere;
}

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

.section-title {
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 17px;
    font-weight: 900;
}

.section-icon {
    width: 37px;
    height: 37px;
    display: grid;
    place-items: center;
    border-radius: 12px;
    background: #e0efff;
    color: var(--blue);
}

.section-description {
    margin-top: 5px;
    color: var(--muted);
    font-size: 11px;
    line-height: 1.6;
}

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

.search-box {
    position: relative;
    flex: 1;
    min-width: 190px;
    max-width: 380px;
}

.search-box i {
    position: absolute;
    left: 14px;
    top: 50%;
    transform: translateY(-50%);
    color: #8a9bb1;
    font-size: 13px;
}

.search-box input {
    width: 100%;
    padding: 13px 14px 13px 38px;
    border: 1px solid var(--border);
    border-radius: 12px;
    outline: none;
    background: #fff;
    color: var(--text);
    font-family: inherit;
    font-size: 12px;
}

.search-box input:focus {
    border-color: var(--blue);
    box-shadow: 0 0 0 3px rgba(8,123,234,.09);
}

.legend {
    display: flex;
    gap: 12px;
    align-items: center;
    flex-wrap: wrap;
    color: var(--muted);
    font-size: 10px;
    font-weight: 700;
}

.legend span {
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

.legend-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
}

.dot-enabled {
    background: #10b981;
}

.dot-disabled {
    background: #94a3b8;
}

.card-grid {
    display: grid;
    grid-template-columns: repeat(3, minmax(0,1fr));
    gap: 12px;
}

.card {
    --card-a: #087bea;
    --card-b: #064b9c;

    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-width: 0;
    min-height: 135px;
    padding: 17px 10px;
    overflow: hidden;
    text-align: center;
    text-decoration: none;
    color: #fff;
    border: 1px solid rgba(255,255,255,.25);
    border-radius: 18px;
    background: linear-gradient(135deg, var(--card-a), var(--card-b));
    box-shadow: 0 7px 18px rgba(21,64,116,.13);
    transition: transform .22s, box-shadow .22s, filter .22s;
    isolation: isolate;
}

.card::before {
    content: "";
    position: absolute;
    z-index: -1;
    inset: 0;
    background: linear-gradient(
        120deg,
        transparent 0%,
        rgba(255,255,255,.2) 50%,
        transparent 100%
    );
    transform: translateX(-120%);
    transition: transform .5s;
}

.card:hover::before {
    transform: translateX(120%);
}

.card:not(.service-disabled):hover {
    transform: translateY(-5px);
    box-shadow: 0 15px 28px rgba(21,64,116,.24);
}

.card-inner {
    position: relative;
    z-index: 2;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
}

.card-icon-wrap {
    display: grid;
    place-items: center;
    width: 43px;
    height: 43px;
    margin-bottom: 10px;
    border: 1px solid rgba(255,255,255,.3);
    border-radius: 14px;
    background: rgba(255,255,255,.17);
    font-size: 18px;
}

.card-title {
    font-size: 10px;
    font-weight: 900;
    line-height: 1.5;
    letter-spacing: .45px;
    overflow-wrap: anywhere;
}

.card-count {
    margin-top: 6px;
    font-size: 19px;
    font-weight: 900;
    line-height: 1.2;
    overflow-wrap: anywhere;
}

.pulse-badge {
    position: absolute;
    top: 11px;
    right: 11px;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #fff;
    box-shadow: 0 0 0 5px rgba(255,255,255,.13);
}

.locked-label {
    margin-top: 8px;
    font-size: 8px;
    font-weight: 900;
    letter-spacing: .55px;
}

.service-disabled {
    opacity: .45;
    filter: grayscale(.8);
    cursor: not-allowed;
    pointer-events: none;
    box-shadow: none;
}

.service-disabled::before {
    display: none;
}

.service-disabled .card-icon-wrap {
    background: rgba(255,255,255,.1);
}

.c0  {--card-a:#16a34a;--card-b:#15803d}
.c1  {--card-a:#0369a1;--card-b:#0e7490}
.c2  {--card-a:#7c3aed;--card-b:#6d28d9}
.c3  {--card-a:#d97706;--card-b:#b45309}
.c4  {--card-a:#065f46;--card-b:#047857}
.c5  {--card-a:#1d4ed8;--card-b:#1e40af}
.c6  {--card-a:#15803d;--card-b:#166534}
.c7  {--card-a:#92400e;--card-b:#78350f}
.c8  {--card-a:#5b21b6;--card-b:#4c1d95}
.c9  {--card-a:#0f766e;--card-b:#0d5f5a}
.c10 {--card-a:#1e40af;--card-b:#1e3a8a}
.c11 {--card-a:#9f1239;--card-b:#881337}
.c12 {--card-a:#0369a1;--card-b:#075985}
.c13 {--card-a:#c2410c;--card-b:#9a3412}
.c14 {--card-a:#0891b2;--card-b:#0e7490}
.c15 {--card-a:#db2777;--card-b:#be185d}
.c16 {--card-a:#059669;--card-b:#047857}
.c17 {--card-a:#b91c1c;--card-b:#991b1b}
.c18 {--card-a:#6d28d9;--card-b:#5b21b6}
.c19 {--card-a:#0284c7;--card-b:#0369a1}
.c20 {--card-a:#047857;--card-b:#065f46}
.c21 {--card-a:#d946ef;--card-b:#a21caf}
.c22 {--card-a:#ca8a04;--card-b:#a16207}
.c23 {--card-a:#ea580c;--card-b:#c2410c}
.c24 {--card-a:#be185d;--card-b:#9d174d}
.c25 {--card-a:#4338ca;--card-b:#3730a3}
.c26 {--card-a:#166534;--card-b:#14532d}
.c27 {--card-a:#dc2626;--card-b:#b91c1c}
.c28 {--card-a:#c2410c;--card-b:#b45309}
.c29 {--card-a:#7c3aed;--card-b:#db2777}
.c30 {--card-a:#0f766e;--card-b:#0891b2}
.c31 {--card-a:#854d0e;--card-b:#92400e}
.c32 {--card-a:#6d28d9;--card-b:#7c3aed}
.c33 {--card-a:#9d174d;--card-b:#831843}
.c34 {--card-a:#ca8a04;--card-b:#d97706}
.c35 {--card-a:#a16207;--card-b:#92400e}
.c36 {--card-a:#1e3a8a;--card-b:#312e81}
.c37 {--card-a:#15803d;--card-b:#0f766e}
.c38 {--card-a:#991b1b;--card-b:#7f1d1d}
.c39 {--card-a:#4c1d95;--card-b:#5b21b6}
.c40 {--card-a:#155e75;--card-b:#0369a1}
.c41 {--card-a:#166534;--card-b:#15803d}

.no-results {
    display: none;
    padding: 35px 15px;
    margin-top: 10px;
    text-align: center;
    background: white;
    border: 1px dashed #cbd9ea;
    border-radius: 16px;
    color: var(--muted);
    font-size: 12px;
}

.assignment-notice {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    margin-top: 23px;
    padding: 16px;
    background: #fff8e8;
    border: 1px solid #f5dfaa;
    border-radius: 15px;
    color: #825a00;
    font-size: 11px;
    line-height: 1.8;
}

.assignment-notice i {
    margin-top: 2px;
    font-size: 17px;
}

footer {
    padding: 26px 12px;
    text-align: center;
    color: #8a9bb1;
    font-size: 10px;
    font-weight: 600;
}

@media(min-width:640px) {
    .card-grid {
        grid-template-columns: repeat(4, minmax(0,1fr));
        gap: 14px;
    }
}

@media(min-width:1000px) {
    .card-grid {
        grid-template-columns: repeat(5, minmax(0,1fr));
        gap: 15px;
    }
}

@media(min-width:1300px) {
    .card-grid {
        grid-template-columns: repeat(6, minmax(0,1fr));
        gap: 16px;
    }
}

@media(max-width:640px) {
    .top-inner {
        padding: 12px;
    }

    .brand-logo {
        width: 40px;
        height: 40px;
    }

    .brand-title {
        font-size: 17px;
    }

    .header-right {
        width: 100%;
    }

    .admin-chip {
        flex: 1;
        min-width: 0;
        overflow-wrap: anywhere;
    }

    .header-right .btn {
        padding: 10px 11px;
    }

    .container {
        padding: 16px 12px 30px;
    }

    .hero {
        padding: 22px 18px;
        border-radius: 19px;
    }

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

    .stat {
        padding: 13px 11px;
        gap: 10px;
        border-radius: 15px;
    }

    .stat:last-child {
        grid-column: 1 / -1;
    }

    .stat-icon {
        width: 39px;
        height: 39px;
        border-radius: 12px;
        font-size: 15px;
    }

    .stat-label {
        font-size: 8px;
        letter-spacing: .3px;
    }

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

    .section-title {
        font-size: 15px;
    }

    .service-toolbar {
        align-items: stretch;
    }

    .search-box {
        max-width: none;
        min-width: 100%;
    }

    .legend {
        font-size: 9px;
    }

    .card-grid {
        grid-template-columns: repeat(3, minmax(0,1fr));
        gap: 8px;
    }

    .card {
        min-height: 112px;
        padding: 12px 5px;
        border-radius: 14px;
    }

    .card-icon-wrap {
        width: 33px;
        height: 33px;
        margin-bottom: 8px;
        border-radius: 10px;
        font-size: 14px;
    }

    .card-title {
        font-size: 8px;
        letter-spacing: .1px;
    }

    .card-count {
        font-size: 14px;
        margin-top: 5px;
    }

    .locked-label {
        font-size: 6px;
        letter-spacing: 0;
    }

    .assignment-notice {
        padding: 13px;
    }
}

@media(max-width:350px) {
    .card-grid {
        grid-template-columns: repeat(2, minmax(0,1fr));
    }
}
</style>
</head>

<body>

<header class="topbar">
    <div class="top-inner">

        <div class="brand">
            <div class="brand-logo">
                <i class="fa-solid fa-shield-halved"></i>
            </div>

            <div>
                <div class="brand-title">ASOVERIFY</div>
                <div class="brand-subtitle">ADMIN CONTROL PANEL</div>
            </div>
        </div>

        <div class="header-right">

            <div class="admin-chip">
                <i class="fa-solid fa-user-shield" style="color:#087bea"></i>

                <span><?= h($currentAdminName) ?></span>

                <span class="rank-chip"><?= h($currentAdminRank) ?></span>
            </div>

            <?php if ($isMD): ?>
                <a href="admin_service_assignments.php" class="btn btn-primary">
                    <i class="fa-solid fa-users-gear"></i>
                    Assign Services
                </a>
            <?php endif; ?>

            <a href="admin_logout.php" class="btn btn-danger">
                <i class="fa-solid fa-right-from-bracket"></i>
                Logout
            </a>

        </div>
    </div>
</header>

<main class="container">

    <section class="hero">
        <div class="hero-content">

            <h1>Welcome to ASOVERIFY</h1>

            <p>
                Manage verification services, transactions, customer requests
                and administrative operations from one secure dashboard.
            </p>

            <div class="hero-meta">

                <span class="hero-pill">
                    <i class="fa-solid fa-circle-check"></i>
                    Dashboard Active
                </span>

                <span class="hero-pill">
                    <i class="fa-solid fa-user-shield"></i>
                    <?= h($currentAdminRank) ?> ACCESS
                </span>

                <span class="hero-pill">
                    <i class="fa-solid fa-lock"></i>
                    <?= $assignedServicesCount ?> / <?= count($cards) ?>
                    SERVICES AVAILABLE
                </span>

            </div>
        </div>
    </section>

    <section class="stats">

        <div class="stat stat-blue">
            <div class="stat-icon">
                <i class="fa-solid fa-database"></i>
            </div>

            <div>
                <div class="stat-label">Total Records</div>
                <div class="stat-value"><?= formatInt($totalRecords) ?></div>
            </div>
        </div>

        <div class="stat stat-green">
            <div class="stat-icon">
                <i class="fa-solid fa-users"></i>
            </div>

            <div>
                <div class="stat-label">Total Customers</div>
                <div class="stat-value"><?= formatInt($usersCount) ?></div>
            </div>
        </div>

        <div class="stat stat-purple">
            <div class="stat-icon">
                <i class="fa-solid fa-wallet"></i>
            </div>

            <div>
                <div class="stat-label">Total Customer Balance</div>
                <div class="stat-value">
                    ₦<?= formatMoney($totalBalance) ?>
                </div>
            </div>
        </div>

    </section>

    <section id="services">

        <div class="section-heading">
            <div>
                <div class="section-title">
                    <span class="section-icon">
                        <i class="fa-solid fa-border-all"></i>
                    </span>

                    Service Modules
                </div>

                <div class="section-description">
                    <?php if ($isMD): ?>
                        You have access to every registered dashboard service.
                    <?php else: ?>
                        Only services assigned to your admin account can be opened.
                        Contact the MD to request additional access.
                    <?php endif; ?>
                </div>
            </div>

            <?php if ($isMD): ?>
                <a href="admin_service_assignments.php" class="btn btn-primary">
                    <i class="fa-solid fa-user-lock"></i>
                    Manage Staff Access
                </a>
            <?php endif; ?>
        </div>

        <div class="service-toolbar">

            <div class="search-box">
                <i class="fa-solid fa-magnifying-glass"></i>

                <input
                    type="search"
                    id="serviceSearch"
                    placeholder="Search dashboard services..."
                    autocomplete="off"
                >
            </div>

            <div class="legend">
                <span>
                    <i class="legend-dot dot-enabled"></i>
                    Accessible
                </span>

                <span>
                    <i class="legend-dot dot-disabled"></i>
                    Locked
                </span>
            </div>

        </div>

        <div class="card-grid" id="serviceGrid">

            <?php foreach ($cards as $i => $card): ?>

                <?php
                $link = (string)$card['link'];

                $allowed = in_array(
                    $link,
                    $allowedLinks,
                    true
                );

                $title = (string)$card['title'];

                $count = $card['count'];

                if (is_numeric($count)) {
                    $displayCount = number_format((float)$count);
                } else {
                    $displayCount = (string)$count;
                }

                $icon = (string)$card['icon'];

                if (!preg_match('/^[a-z0-9-]+$/', $icon)) {
                    $icon = 'fa-lock';
                }

                $searchText = strtolower(
                    $title . ' ' . $link
                );
                ?>

                <?php if ($allowed): ?>

                    <a
                        href="<?= h($link) ?>"
                        class="card c<?= $i % 42 ?> service-card"
                        data-search="<?= h($searchText) ?>"
                        aria-label="<?= h($title) ?>"
                    >

                        <?php if (
                            is_numeric($count) &&
                            (float)$count > 0
                        ): ?>
                            <span class="pulse-badge"></span>
                        <?php endif; ?>

                        <div class="card-inner">

                            <div class="card-icon-wrap">
                                <i class="fa-solid <?= h($icon) ?>"></i>
                            </div>

                            <div class="card-title">
                                <?= h($title) ?>
                            </div>

                            <div class="card-count">
                                <?= h($displayCount) ?>
                            </div>

                        </div>

                    </a>

                <?php else: ?>

                    <div
                        class="card c<?= $i % 42 ?> service-card service-disabled"
                        data-search="<?= h($searchText) ?>"
                        aria-disabled="true"
                        title="This service has not been assigned to your account."
                    >

                        <div class="card-inner">

                            <div class="card-icon-wrap">
                                <i class="fa-solid fa-lock"></i>
                            </div>

                            <div class="card-title">
                                <?= h($title) ?>
                            </div>

                            <div class="card-count">
                                <i class="fa-solid fa-lock"></i>
                                Locked
                            </div>

                            <div class="locked-label">
                                ACCESS NOT ASSIGNED
                            </div>

                        </div>

                    </div>

                <?php endif; ?>

            <?php endforeach; ?>

        </div>

        <div class="no-results" id="noResults">
            <i class="fa-solid fa-magnifying-glass" style="font-size:25px;margin-bottom:10px"></i>
            <div>No matching service was found.</div>
        </div>

    </section>

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

        <div class="assignment-notice">
            <i class="fa-solid fa-circle-info"></i>

            <div>
                <strong>Service access information</strong><br>

                Your dashboard access is controlled by the ASOVERIFY MD.
                Locked services cannot be opened from this dashboard.
                If you require another service, contact the MD to have it assigned
                to your account. Access to a service's direct URL must also be
                verified by that service's PHP permission check.
            </div>
        </div>

    <?php endif; ?>

</main>

<footer>
    <i class="fa-solid fa-shield-halved"></i>
    &nbsp; © <?= date('Y') ?> ASOVERIFY Admin Panel.
    All rights reserved.
</footer>

<script>
(function () {
    'use strict';

    const searchInput = document.getElementById('serviceSearch');
    const cards = Array.from(
        document.querySelectorAll('.service-card')
    );
    const noResults = document.getElementById('noResults');

    if (!searchInput) {
        return;
    }

    searchInput.addEventListener('input', function () {
        const query = this.value.toLowerCase().trim();
        let visible = 0;

        cards.forEach(function (card) {
            const searchable = (
                card.getAttribute('data-search') || ''
            ).toLowerCase();

            const match = searchable.includes(query);

            card.style.display = match ? '' : 'none';

            if (match) {
                visible++;
            }
        });

        if (noResults) {
            noResults.style.display = visible === 0 ? 'block' : 'none';
        }
    });
})();
</script>

</body>
</html>