<?php include "header.php";

// Self-healing auto-expiry - keep this in sync with auth/transactions.php
$conn->query("
    UPDATE orders o
    JOIN payment_links pl ON pl.order_id = o.order_id
    SET o.status = 'FAILURE'
    WHERE o.status = 'PENDING'
      AND pl.created_at < (NOW() - INTERVAL 5 MINUTE)
");

// ============================================================
// REAL DATA QUERIES (replaces all fake/static numbers)
// Uses the same `orders` table + $userdata that header.php loads
// ============================================================

$userId    = (int)($userdata['id'] ?? 0);
$today     = date('Y-m-d');
$yesterday = date('Y-m-d', strtotime('-1 day'));

function safeAmt($res) {
    if ($res === false) return 0.0;
    $row = $res->fetch_assoc();
    return (float)($row['amt'] ?? 0);
}
function safeCnt($res) {
    if ($res === false) return 0;
    $row = $res->fetch_assoc();
    return (int)($row['cnt'] ?? 0);
}
function pctChange($now, $prev) {
    if ($prev == 0) return $now > 0 ? 100.0 : 0.0;
    return round((($now - $prev) / $prev) * 100, 1);
}

// ---- Today vs Yesterday (for real % change badges) ----
$ySuccessAmt = safeAmt($conn->query("SELECT SUM(amount) as amt FROM orders WHERE user_id='$userId' AND is_test=0 AND status='SUCCESS' AND DATE(create_date)='$yesterday'"));
$ySuccessCnt = safeCnt($conn->query("SELECT COUNT(id) as cnt FROM orders WHERE user_id='$userId' AND is_test=0 AND status='SUCCESS' AND DATE(create_date)='$yesterday'"));
$yPendingAmt = safeAmt($conn->query("SELECT SUM(amount) as amt FROM orders WHERE user_id='$userId' AND is_test=0 AND status='PENDING' AND DATE(create_date)='$yesterday'"));
$yFailAmt    = safeAmt($conn->query("SELECT SUM(amount) as amt FROM orders WHERE user_id='$userId' AND is_test=0 AND status='FAILURE' AND DATE(create_date)='$yesterday'"));

$tSuccessAmt = (float)($todaysuccesspayment['amt'] ?? 0);
$tSuccessCnt = (int)($todayallpayment['amt'] ?? 0);
$tPendingAmt = (float)($todaypendingpayment['amt'] ?? 0);
$tFailAmt    = (float)($todayfail['amt'] ?? 0);

$successAmtChange = pctChange($tSuccessAmt, $ySuccessAmt);
$successCntChange = pctChange($tSuccessCnt, $ySuccessCnt);
$pendingChange     = pctChange($tPendingAmt, $yPendingAmt);
$failChange        = pctChange($tFailAmt, $yFailAmt);

// ---- All-time totals for this user ----
$totalTxnAll     = safeCnt($conn->query("SELECT COUNT(id) as cnt FROM orders WHERE user_id='$userId' AND is_test=0"));
$totalSuccessAll = safeCnt($conn->query("SELECT COUNT(id) as cnt FROM orders WHERE user_id='$userId' AND is_test=0 AND status='SUCCESS'"));
$totalPendingAll = safeCnt($conn->query("SELECT COUNT(id) as cnt FROM orders WHERE user_id='$userId' AND is_test=0 AND status='PENDING'"));
$totalFailAll    = safeCnt($conn->query("SELECT COUNT(id) as cnt FROM orders WHERE user_id='$userId' AND is_test=0 AND status='FAILURE'"));
$successRate     = $totalTxnAll > 0 ? round(($totalSuccessAll / $totalTxnAll) * 100, 1) : 0;

// ---- Account status ----
$expiryDate = $userdata['expiry'] ?? null;
$status = ($expiryDate && strtotime($expiryDate) >= strtotime($today)) ? "Active" : "Expired";
$daysLeft = $expiryDate ? (int)ceil((strtotime($expiryDate) - strtotime($today)) / 86400) : 0;

// ---- Last 7 days trend (real, grouped in one query) ----
$weekStart = date('Y-m-d', strtotime('-6 day'));
$weekRes = $conn->query("SELECT DATE(create_date) as d,
    SUM(CASE WHEN status='SUCCESS' THEN amount ELSE 0 END) as s,
    SUM(CASE WHEN status='FAILURE' THEN amount ELSE 0 END) as f
    FROM orders WHERE user_id='$userId' AND is_test=0 AND DATE(create_date) >= '$weekStart'
    GROUP BY DATE(create_date)");

$weekMap = [];
if ($weekRes) {
    while ($r = $weekRes->fetch_assoc()) { $weekMap[$r['d']] = $r; }
}

$chartLabels = [];
$chartSuccess = [];
$chartFailed = [];
for ($i = 6; $i >= 0; $i--) {
    $d = date('Y-m-d', strtotime("-$i day"));
    $chartLabels[]  = date('D', strtotime($d));
    $chartSuccess[] = isset($weekMap[$d]) ? (float)$weekMap[$d]['s'] : 0;
    $chartFailed[]  = isset($weekMap[$d]) ? (float)$weekMap[$d]['f'] : 0;
}

// ---- Real status distribution for doughnut (all-time) ----
$distTotal = max($totalTxnAll, 1);
$successPct = round(($totalSuccessAll / $distTotal) * 100, 1);
$pendingPct = round(($totalPendingAll / $distTotal) * 100, 1);
$failPct    = round(($totalFailAll / $distTotal) * 100, 1);

// ---- Payment method / gateway breakdown (successful revenue, all-time) ----
$methodLabels = [];
$methodAmounts = [];
$methodRes = $conn->query("SELECT method, SUM(amount) as amt FROM orders
    WHERE user_id='$userId' AND is_test=0 AND status='SUCCESS' AND method IS NOT NULL AND method != ''
    GROUP BY method ORDER BY amt DESC LIMIT 6");
if ($methodRes) {
    while ($r = $methodRes->fetch_assoc()) {
        $methodLabels[]  = ucfirst($r['method']);
        $methodAmounts[] = (float)$r['amt'];
    }
}

// ---- Today's hourly activity (successful transaction count per hour) ----
$hourlyRes = $conn->query("SELECT HOUR(create_date) as h, COUNT(id) as cnt FROM orders
    WHERE user_id='$userId' AND is_test=0 AND status='SUCCESS' AND DATE(create_date)='$today'
    GROUP BY HOUR(create_date)");
$hourlyMap = [];
if ($hourlyRes) {
    while ($r = $hourlyRes->fetch_assoc()) { $hourlyMap[(int)$r['h']] = (int)$r['cnt']; }
}
$hourlyLabels = [];
$hourlyCounts = [];
foreach ([0,2,4,6,8,10,12,14,16,18,20,22] as $h) {
    $hourlyLabels[] = date('ga', strtotime(sprintf('%02d:00', $h)));
    $sum = 0;
    for ($i = 0; $i < 2; $i++) { $sum += $hourlyMap[$h + $i] ?? 0; }
    $hourlyCounts[] = $sum;
}

// Reset a stuck "collapse sidebar" preference (sidebar_layout=1 in DB) that
// was causing the brand to always show as the short "AC" mini-logo instead
// of the full name — this was a saved user preference, not a bug in the
// page itself, but it's confusing here so we clear it going forward.
if (($userdata['sidebar_layout'] ?? 0) == 1) {
    $conn->query("UPDATE users SET sidebar_layout = 0 WHERE id = '$userId'");
}

$recentRes = $conn->query("SELECT * FROM orders WHERE user_id='$userId' AND is_test=0 ORDER BY create_date DESC LIMIT 10");
$recentRows = [];
if ($recentRes) {
    while ($r = $recentRes->fetch_assoc()) { $recentRows[] = $r; }
}

// ============================================================
// Lightweight real-time endpoint: same file, ?ajax=stats
// The page polls this every few seconds via fetch() so the
// dashboard updates live without a full reload.
// ============================================================
if (isset($_GET['ajax']) && $_GET['ajax'] === 'stats') {
    header('Content-Type: application/json');
    $recentOut = [];
    foreach ($recentRows as $row) {
        $st = strtoupper($row['status'] ?? '');
        $recentOut[] = [
            'id'     => $row['order_id'] ?? $row['txn_id'] ?? $row['id'] ?? '-',
            'date'   => date('d M Y, h:i A', strtotime($row['create_date'])),
            'amount' => (float)$row['amount'],
            'status' => $st,
        ];
    }
    echo json_encode([
        'todayReceived'     => round($tSuccessAmt, 2),
        'todaySuccessCnt'   => $tSuccessCnt,
        'todayPending'      => round($tPendingAmt, 2),
        'todayFailed'       => round($tFailAmt, 2),
        'successAmtChange'  => $successAmtChange,
        'successCntChange'  => $successCntChange,
        'pendingChange'     => $pendingChange,
        'failChange'        => $failChange,
        'totalTxnAll'       => $totalTxnAll,
        'totalSuccessAll'   => $totalSuccessAll,
        'successRate'       => $successRate,
        'chartLabels'       => $chartLabels,
        'chartSuccess'      => $chartSuccess,
        'chartFailed'       => $chartFailed,
        'successPct'        => $successPct,
        'pendingPct'        => $pendingPct,
        'failPct'           => $failPct,
        'methodLabels'      => $methodLabels,
        'methodAmounts'     => $methodAmounts,
        'hourlyLabels'      => $hourlyLabels,
        'hourlyCounts'      => $hourlyCounts,
        'recent'            => $recentOut,
    ]);
    exit;
}
?>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root{
            --p:#6c63ff; --p2:#e040fb;
            --g: linear-gradient(135deg,#6c63ff,#e040fb);
            --success:#43e97b; --danger:#ff6584; --warning:#f5b93b; --info:#3ea6ff;
        }
        *{box-sizing:border-box}

        /* header.php's admin theme has a higher-specificity background rule
           (e.g. body.fixed-navbar / .content-wrapper) that beats a plain
           body{} rule, which is why the page was showing washed-out on a
           light background. Forcing it here with !important + targeting
           the real wrapper element fixes it regardless of theme specificity. */
        html, body, .content-wrapper{
            background:#0a0a12 !important;
        }
        body{
            font-family:'Inter',sans-serif;
            color:#fff;
            min-height:100vh;
        }
        .content-wrapper{min-height:100vh}
        .container-fluid{padding:20px;max-width:1400px;margin:0 auto}

        /* ---- Stat Cards ---- */
        .stat-card{
            background:rgba(255,255,255,.04);
            backdrop-filter:blur(20px);
            border:1px solid rgba(255,255,255,.08);
            border-radius:20px;
            padding:22px;
            margin-bottom:20px;
            position:relative;
            overflow:hidden;
            transition:.3s;
        }
        .stat-card:hover{
            transform:translateY(-6px);
            border-color:rgba(108,99,255,.35);
            box-shadow:0 20px 40px rgba(0,0,0,.35);
        }
        .stat-icon-wrap{
            width:46px;height:46px;border-radius:14px;
            display:flex;align-items:center;justify-content:center;
            font-size:19px;margin-bottom:16px;color:#fff;
        }
        .ic-success{background:linear-gradient(135deg,#0f5132,#43e97b)}
        .ic-info{background:linear-gradient(135deg,#1e3a8a,#3ea6ff)}
        .ic-warning{background:linear-gradient(135deg,#7c4a03,#f5b93b)}
        .ic-danger{background:linear-gradient(135deg,#7f1d3a,#ff6584)}
        .ic-primary{background:var(--g)}

        .stat-value{font-size:1.65rem;font-weight:800;color:#fff;margin-bottom:2px}
        .stat-label{font-size:.82rem;color:rgba(255,255,255,.45);margin-bottom:12px;font-weight:500}
        .stat-change{font-size:.78rem;font-weight:600;display:flex;align-items:center;gap:5px}
        .stat-change.up{color:var(--success)}
        .stat-change.down{color:var(--danger)}
        .stat-change.flat{color:rgba(255,255,255,.4)}

        /* ---- Dashboard Cards ---- */
        .dashboard-card{
            background:rgba(255,255,255,.04);
            backdrop-filter:blur(20px);
            border:1px solid rgba(255,255,255,.08);
            border-radius:20px;
            margin-bottom:20px;
            overflow:hidden;
        }
        .card-header{
            padding:18px 22px;
            border-bottom:1px solid rgba(255,255,255,.07);
            display:flex;justify-content:space-between;align-items:center;
            flex-wrap:wrap;gap:10px;
        }
        .card-header h3{font-size:1.05rem;font-weight:700;margin:0;color:#fff}
        .card-body{padding:22px}
        .badge-outline{
            font-size:.72rem;padding:5px 12px;border-radius:50px;
            background:rgba(108,99,255,.12);border:1px solid rgba(108,99,255,.3);color:#a396ff;
            display:inline-flex;align-items:center;gap:6px;
        }
        .live-dot{width:7px;height:7px;border-radius:50%;background:#43e97b;display:inline-block;
            animation:livePulse 1.6s ease-in-out infinite}
        @keyframes livePulse{
            0%,100%{box-shadow:0 0 0 0 rgba(67,233,123,.6)}
            50%{box-shadow:0 0 0 6px rgba(67,233,123,0)}
        }
        @keyframes flashUpdate{
            0%{background:rgba(108,99,255,.25)}
            100%{background:transparent}
        }
        .flash-update{animation:flashUpdate 1s ease}

        /* ---- Legend rows for doughnut ---- */
        .legend-row{display:flex;align-items:center;margin-bottom:12px;font-size:.85rem;color:rgba(255,255,255,.7)}
        .legend-dot{width:11px;height:11px;border-radius:50%;margin-right:10px;flex-shrink:0}
        .legend-row .val{margin-left:auto;font-weight:700;color:#fff}

        /* ---- Table ---- */
        .table{width:100%;color:rgba(255,255,255,.75);border-collapse:collapse}
        .table th{
            font-size:.72rem;text-transform:uppercase;letter-spacing:.5px;
            color:rgba(255,255,255,.4);font-weight:600;padding:10px 14px;
            border-bottom:1px solid rgba(255,255,255,.08);text-align:left;
        }
        .table td{padding:13px 14px;border-bottom:1px solid rgba(255,255,255,.05);font-size:.86rem}
        .table tr:hover td{background:rgba(255,255,255,.02)}
        .badge-status{padding:4px 12px;border-radius:50px;font-size:.72rem;font-weight:700;letter-spacing:.3px}
        .badge-success-s{background:rgba(67,233,123,.12);color:var(--success);border:1px solid rgba(67,233,123,.3)}
        .badge-warning-s{background:rgba(245,185,59,.12);color:var(--warning);border:1px solid rgba(245,185,59,.3)}
        .badge-danger-s{background:rgba(255,101,132,.12);color:var(--danger);border:1px solid rgba(255,101,132,.3)}
        .empty-state{text-align:center;padding:40px 20px;color:rgba(255,255,255,.35);font-size:.9rem}

        .dropdown-toggle-dash{
            background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);
            color:#fff;padding:7px 14px;border-radius:10px;font-size:.8rem;
        }

        .table-responsive{overflow-x:auto;-webkit-overflow-scrolling:touch}

        /* Top search bar (header.php) isn't used — hide it */
        .navbar-search{display:none !important}

        /* ---- Mobile tightening ---- */
        @media (max-width:768px){
            .container-fluid{padding:12px}
            .row{margin-left:-6px;margin-right:-6px}
            .row>[class^="col-"]{padding-left:6px;padding-right:6px}
            .stat-card{padding:14px;border-radius:16px;margin-bottom:12px;min-height:150px;display:flex;flex-direction:column;justify-content:space-between}
            .stat-icon-wrap{width:38px;height:38px;font-size:15px;margin-bottom:10px;border-radius:11px}
            .stat-value{font-size:1.15rem}
            .stat-label{font-size:.72rem;margin-bottom:8px;line-height:1.3}
            .stat-change{font-size:.68rem}
            .dashboard-card{border-radius:16px;margin-bottom:12px}
            .card-header{padding:14px 16px}
            .card-header h3{font-size:.95rem}
            .card-body{padding:14px}
            .table th, .table td{padding:10px 8px;font-size:.78rem}

            /* Sidebar drawer polish when opened on mobile (header.php provides
               the toggle behaviour via app.min.js; this just makes the panel
               itself look sharper — solid dark bg, real shadow, smooth slide) */
            .page-sidebar{
                box-shadow:0 0 50px rgba(0,0,0,.65) !important;
                z-index:1500 !important;
            }
        }

        /* ---- Entrance animations ---- */
        @keyframes fadeInUp{
            from{opacity:0;transform:translateY(18px)}
            to{opacity:1;transform:translateY(0)}
        }
        .stat-card, .dashboard-card{
            animation:fadeInUp .5s ease both;
        }
        .row .col-6:nth-child(1) .stat-card, .row .col-lg-3:nth-child(1) .stat-card{animation-delay:.02s}
        .row .col-6:nth-child(2) .stat-card, .row .col-lg-3:nth-child(2) .stat-card{animation-delay:.08s}
        .row .col-6:nth-child(3) .stat-card, .row .col-lg-3:nth-child(3) .stat-card{animation-delay:.14s}
        .row .col-6:nth-child(4) .stat-card, .row .col-lg-3:nth-child(4) .stat-card{animation-delay:.2s}
        .row .col-6:nth-child(5) .stat-card, .row .col-lg-3:nth-child(5) .stat-card{animation-delay:.26s}
        .row .col-6:nth-child(6) .stat-card, .row .col-lg-3:nth-child(6) .stat-card{animation-delay:.32s}
        .row .col-6:nth-child(7) .stat-card, .row .col-lg-3:nth-child(7) .stat-card{animation-delay:.38s}
        .row .col-6:nth-child(8) .stat-card, .row .col-lg-3:nth-child(8) .stat-card{animation-delay:.44s}
        .col-lg-8 .dashboard-card{animation-delay:.15s}
        .col-lg-4 .dashboard-card{animation-delay:.25s}

        /* ---- Mobile off-canvas sidebar drawer (overrides the theme's
           own "collapse to mini icon strip" behaviour, which looked broken
           on phones) ---- */
        .mob-sidebar-backdrop{
            position:fixed;inset:0;background:rgba(0,0,0,.65);
            z-index:1900;opacity:0;visibility:hidden;backdrop-filter:blur(3px);
            transition:opacity .3s ease, visibility .3s ease;
        }
        body.mob-sidebar-open .mob-sidebar-backdrop{opacity:1;visibility:visible}
        @media (max-width:768px){
            .page-sidebar{
                position:fixed !important;
                top:0 !important;left:0 !important;bottom:0 !important;
                width:270px !important;
                height:100vh !important;
                transform:translateX(-100%);
                transition:transform .32s cubic-bezier(.4,0,.2,1);
                z-index:2000 !important;
                overflow-y:auto !important;
                box-shadow:0 0 60px rgba(0,0,0,.7);
            }
            body.mob-sidebar-open .page-sidebar{transform:translateX(0) !important}
            .content-wrapper, .page-wrapper{margin-left:0 !important}

            @keyframes fadeInLeft{from{opacity:0;transform:translateX(-16px)}to{opacity:1;transform:translateX(0)}}
            body.mob-sidebar-open .side-menu.metismenu > li{animation:fadeInLeft .4s ease both}
            body.mob-sidebar-open .side-menu.metismenu > li:nth-child(1){animation-delay:.03s}
            body.mob-sidebar-open .side-menu.metismenu > li:nth-child(2){animation-delay:.06s}
            body.mob-sidebar-open .side-menu.metismenu > li:nth-child(3){animation-delay:.09s}
            body.mob-sidebar-open .side-menu.metismenu > li:nth-child(4){animation-delay:.12s}
            body.mob-sidebar-open .side-menu.metismenu > li:nth-child(5){animation-delay:.15s}
            body.mob-sidebar-open .side-menu.metismenu > li:nth-child(6){animation-delay:.18s}
            body.mob-sidebar-open .side-menu.metismenu > li:nth-child(7){animation-delay:.21s}
            body.mob-sidebar-open .side-menu.metismenu > li:nth-child(8){animation-delay:.24s}
            body.mob-sidebar-open .side-menu.metismenu > li:nth-child(9){animation-delay:.27s}
            body.mob-sidebar-open .side-menu.metismenu > li:nth-child(10){animation-delay:.3s}
            body.mob-sidebar-open .side-menu.metismenu > li:nth-child(11){animation-delay:.33s}
            body.mob-sidebar-open .side-menu.metismenu > li:nth-child(12){animation-delay:.36s}

            /* Hide the theme's original hamburger — its own JS was
               intercepting clicks and blocking our drawer logic */
            .navbar-toolbar .sidebar-toggler{display:none !important}
        }

        /* Independent hamburger button, fully under our own control —
           sits inline in the toolbar where the original one was */
        .my-mobile-toggle{
            display:none;
            background:transparent;border:none;outline:none;
            color:rgba(255,255,255,.8);
            font-size:19px;
            width:44px;height:100%;min-height:50px;
            align-items:center;justify-content:center;
            cursor:pointer;transition:.2s;
        }
        .my-mobile-toggle:active{color:#fff;transform:scale(.9)}
        @media (max-width:768px){
            .my-mobile-toggle{display:flex}
        }

        /* ---- Floating theme-config gear panel: not useful here, and
           toggling it is what caused the stuck sidebar-mini bug — hide it
           completely instead of just repositioning it ---- */
        .theme-config{display:none !important}

        /* ============================================================
           HEADER + SIDEBAR — restyled to match the dark glass look used
           on the Login / Register / Landing pages (was the theme's
           original white/light admin skin before).
           ============================================================ */
        .page-wrapper > header.header{
            background:rgba(10,10,18,.92) !important;
            backdrop-filter:blur(20px);
            border-bottom:1px solid rgba(255,255,255,.08) !important;
            box-shadow:none !important;
        }
        .page-brand{background:transparent !important}
        .page-brand .link{color:#fff !important}
        .page-brand .brand{
            display:inline-block !important;
            background:var(--g);
            -webkit-background-clip:text;
            background-clip:text;
            -webkit-text-fill-color:transparent;
            color:transparent !important;
            font-weight:800;
            font-size:1.1rem;
            letter-spacing:.3px;
        }
        .page-brand .brand-mini{display:none !important}

        .navbar-toolbar > li > a.nav-link{color:rgba(255,255,255,.7) !important}
        .navbar-toolbar > li > a.nav-link:hover{color:#fff !important}
        .navbar-toolbar .dropdown-user .nav-link span{color:rgba(255,255,255,.85) !important}
        .navbar-toolbar img{border-radius:50% !important;border:2px solid rgba(108,99,255,.45)}

        .dropdown-menu{
            background:#12121c !important;
            border:1px solid rgba(255,255,255,.08) !important;
            box-shadow:0 20px 45px rgba(0,0,0,.55) !important;
        }
        .dropdown-menu .dropdown-item, .dropdown-menu a{color:rgba(255,255,255,.75) !important}
        .dropdown-menu .dropdown-item:hover{background:rgba(108,99,255,.15) !important;color:#fff !important}
        .dropdown-menu-header{color:rgba(255,255,255,.5) !important;border-color:rgba(255,255,255,.08) !important}
        .dropdown-divider{border-color:rgba(255,255,255,.08) !important}

        .page-sidebar{background:#0d0d16 !important;border-right:1px solid rgba(255,255,255,.08) !important}
        #sidebar-collapse{background:transparent !important}
        .admin-block{
            padding:20px 18px !important;
            border-bottom:1px solid rgba(255,255,255,.08);
            background:transparent !important;
        }
        .admin-block img{border-radius:50% !important;border:2px solid rgba(108,99,255,.45)}
        .admin-info .font-strong{color:#fff !important;font-weight:700}
        .admin-info small{color:rgba(255,255,255,.45) !important}

        .side-menu.metismenu{padding:12px 8px !important;background:transparent !important}
        .side-menu.metismenu li.heading{
            color:rgba(255,255,255,.35) !important;
            font-size:.68rem;text-transform:uppercase;letter-spacing:.6px;
            padding:16px 12px 6px !important;font-weight:700;background:transparent !important;
        }
        .side-menu.metismenu li a{
            color:rgba(255,255,255,.68) !important;
            border-radius:12px !important;
            margin:2px 4px !important;
            padding:11px 14px !important;
            display:flex !important;align-items:center;gap:12px;
            transition:.25s;background:transparent !important;
        }
        .side-menu.metismenu li a:hover{background:rgba(108,99,255,.14) !important;color:#fff !important}
        .side-menu.metismenu li a.active{
            background:var(--g) !important;
            color:#fff !important;
            box-shadow:0 8px 20px rgba(108,99,255,.35);
        }
        .side-menu.metismenu .sidebar-item-icon{
            font-size:15px;width:20px;text-align:center;color:inherit !important;flex-shrink:0;
        }
        .side-menu.metismenu svg{fill:currentColor !important}
        .side-menu.metismenu .nav-label{font-size:.87rem;font-weight:500;display:inline-block !important;opacity:1 !important;visibility:visible !important;width:auto !important}
        .page-sidebar .admin-info{display:block !important;opacity:1 !important;visibility:visible !important}
        .page-sidebar li.heading{display:block !important;opacity:1 !important;visibility:visible !important}
        .admin-block{display:flex !important;align-items:center;gap:12px}
    </style>
    <div class="container-fluid py-3">
        <div class="row">
            <!-- Today Received Payment -->
            <div class="col-6 col-lg-3">
                <div class="stat-card">
                    <div class="stat-icon-wrap ic-success"><i class="fas fa-wallet"></i></div>
                    <div class="stat-value" id="s-received">₹<?php echo number_format($tSuccessAmt, 2); ?></div>
                    <div class="stat-label">Today Received Payment</div>
                    <div class="stat-change <?php echo $successAmtChange > 0 ? 'up' : ($successAmtChange < 0 ? 'down' : 'flat'); ?>" id="s-received-change">
                        <i class="fas fa-arrow-<?php echo $successAmtChange >= 0 ? 'up' : 'down'; ?>"></i>
                        <?php echo abs($successAmtChange); ?>% vs yesterday
                    </div>
                </div>
            </div>

            <!-- Today Success Transactions -->
            <div class="col-6 col-lg-3">
                <div class="stat-card">
                    <div class="stat-icon-wrap ic-info"><i class="fas fa-check-double"></i></div>
                    <div class="stat-value" id="s-success-cnt"><?php echo number_format($tSuccessCnt); ?></div>
                    <div class="stat-label">Today Success Transactions</div>
                    <div class="stat-change <?php echo $successCntChange > 0 ? 'up' : ($successCntChange < 0 ? 'down' : 'flat'); ?>" id="s-success-cnt-change">
                        <i class="fas fa-arrow-<?php echo $successCntChange >= 0 ? 'up' : 'down'; ?>"></i>
                        <?php echo abs($successCntChange); ?>% vs yesterday
                    </div>
                </div>
            </div>

            <!-- Today Pending Payment -->
            <div class="col-6 col-lg-3">
                <div class="stat-card">
                    <div class="stat-icon-wrap ic-warning"><i class="fas fa-hourglass-half"></i></div>
                    <div class="stat-value" id="s-pending">₹<?php echo number_format($tPendingAmt, 2); ?></div>
                    <div class="stat-label">Today Pending Payment</div>
                    <div class="stat-change <?php echo $pendingChange > 0 ? 'up' : ($pendingChange < 0 ? 'down' : 'flat'); ?>" id="s-pending-change">
                        <i class="fas fa-arrow-<?php echo $pendingChange >= 0 ? 'up' : 'down'; ?>"></i>
                        <?php echo abs($pendingChange); ?>% vs yesterday
                    </div>
                </div>
            </div>

            <!-- Today Failed Payment -->
            <div class="col-6 col-lg-3">
                <div class="stat-card">
                    <div class="stat-icon-wrap ic-danger"><i class="fas fa-circle-xmark"></i></div>
                    <div class="stat-value" id="s-failed">₹<?php echo number_format($tFailAmt, 2); ?></div>
                    <div class="stat-label">Today Failed Payment</div>
                    <div class="stat-change <?php echo $failChange > 0 ? 'down' : ($failChange < 0 ? 'up' : 'flat'); ?>" id="s-failed-change">
                        <i class="fas fa-arrow-<?php echo $failChange >= 0 ? 'up' : 'down'; ?>"></i>
                        <?php echo abs($failChange); ?>% vs yesterday
                    </div>
                </div>
            </div>

            <!-- Total Transactions (all time) -->
            <div class="col-6 col-lg-3">
                <div class="stat-card">
                    <div class="stat-icon-wrap ic-primary"><i class="fas fa-layer-group"></i></div>
                    <div class="stat-value" id="s-total-txn"><?php echo number_format($totalTxnAll); ?></div>
                    <div class="stat-label">Total Transactions</div>
                    <div class="stat-change flat"><i class="fas fa-infinity"></i> All time</div>
                </div>
            </div>

            <!-- Success Rate -->
            <div class="col-6 col-lg-3">
                <div class="stat-card">
                    <div class="stat-icon-wrap ic-info"><i class="fas fa-chart-line"></i></div>
                    <div class="stat-value" id="s-success-rate"><?php echo $successRate; ?>%</div>
                    <div class="stat-label">Success Rate</div>
                    <div class="stat-change flat" id="s-success-rate-sub"><i class="fas fa-database"></i> <?php echo $totalSuccessAll; ?> of <?php echo $totalTxnAll; ?> orders</div>
                </div>
            </div>

            <!-- Plan Expire Date -->
            <div class="col-6 col-lg-3">
                <div class="stat-card">
                    <div class="stat-icon-wrap ic-primary"><i class="fas fa-calendar-check"></i></div>
                    <div class="stat-value" style="font-size:1.15rem"><?php echo $expiryDate ? htmlspecialchars(date('d M Y', strtotime($expiryDate)), ENT_QUOTES, 'UTF-8') : 'N/A'; ?></div>
                    <div class="stat-label">Plan Expire Date</div>
                    <div class="stat-change <?php echo $daysLeft >= 0 ? 'up' : 'down'; ?>">
                        <i class="fas fa-clock"></i>
                        <?php echo $daysLeft >= 0 ? "$daysLeft days left" : abs($daysLeft) . " days overdue"; ?>
                    </div>
                </div>
            </div>

            <!-- Account Status -->
            <div class="col-6 col-lg-3">
                <div class="stat-card">
                    <div class="stat-icon-wrap <?php echo $status === 'Active' ? 'ic-success' : 'ic-danger'; ?>">
                        <i class="fas fa-shield-halved"></i>
                    </div>
                    <div class="stat-value"><?php echo htmlspecialchars($status, ENT_QUOTES, 'UTF-8'); ?></div>
                    <div class="stat-label">Account Status</div>
                    <div class="stat-change <?php echo $status === 'Active' ? 'up' : 'down'; ?>">
                        <i class="fas fa-circle" style="font-size:8px"></i>
                        <?php echo $status === 'Active' ? 'Plan is active' : 'Renewal needed'; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Charts Section -->
        <div class="row mt-2">
            <div class="col-lg-8 col-md-12">
                <div class="dashboard-card">
                    <div class="card-header">
                        <h3>Transaction Trend</h3>
                        <span class="badge-outline"><span class="live-dot" id="live-dot"></span> Last 7 Days</span>
                    </div>
                    <div class="card-body">
                        <div style="position:relative;height:300px;">
                            <canvas id="trend_chart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4 col-md-12">
                <div class="dashboard-card">
                    <div class="card-header">
                        <h3>Transaction Distribution</h3>
                    </div>
                    <div class="card-body">
                        <div style="position:relative;height:190px;">
                            <canvas id="doughnut_chart"></canvas>
                        </div>
                        <div class="mt-4">
                            <div class="legend-row">
                                <div class="legend-dot" style="background:var(--success)"></div>
                                <div>Successful</div>
                                <div class="val" id="dist-success-pct"><?php echo $successPct; ?>%</div>
                            </div>
                            <div class="legend-row">
                                <div class="legend-dot" style="background:var(--warning)"></div>
                                <div>Pending</div>
                                <div class="val" id="dist-pending-pct"><?php echo $pendingPct; ?>%</div>
                            </div>
                            <div class="legend-row" style="margin-bottom:0">
                                <div class="legend-dot" style="background:var(--danger)"></div>
                                <div>Failed</div>
                                <div class="val" id="dist-fail-pct"><?php echo $failPct; ?>%</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- More Charts: payment methods + hourly activity -->
        <div class="row mt-2">
            <div class="col-lg-5 col-md-12">
                <div class="dashboard-card">
                    <div class="card-header">
                        <h3>Top Payment Methods</h3>
                        <span class="badge-outline">Revenue</span>
                    </div>
                    <div class="card-body">
                        <?php if (count($methodLabels) > 0): ?>
                        <div style="position:relative;height:230px;">
                            <canvas id="method_chart"></canvas>
                        </div>
                        <?php else: ?>
                            <div class="empty-state"><i class="fas fa-chart-simple mb-2" style="font-size:28px;display:block"></i>No successful transactions yet.</div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <div class="col-lg-7 col-md-12">
                <div class="dashboard-card">
                    <div class="card-header">
                        <h3>Today's Activity</h3>
                        <span class="badge-outline"><span class="live-dot"></span> By Hour</span>
                    </div>
                    <div class="card-body">
                        <div style="position:relative;height:230px;">
                            <canvas id="hourly_chart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Recent Transactions -->
        <div class="row mt-2">
            <div class="col-12">
                <div class="dashboard-card">
                    <div class="card-header">
                        <h3>Recent Transactions</h3>
                        <a href="reports" class="badge-outline" style="text-decoration:none">View All</a>
                    </div>
                    <div class="card-body" id="recent-tx-container">
                        <?php if (count($recentRows) > 0): ?>
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Order ID</th>
                                        <th>Date</th>
                                        <th>Amount</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody id="recent-tx-tbody">
                                <?php foreach ($recentRows as $row): ?>
                                    <?php
                                        $st = strtoupper($row['status'] ?? '');
                                        $badgeClass = $st === 'SUCCESS' ? 'badge-success-s' : ($st === 'PENDING' ? 'badge-warning-s' : 'badge-danger-s');
                                        $displayId = $row['order_id'] ?? $row['txn_id'] ?? $row['id'] ?? '-';
                                    ?>
                                    <tr>
                                        <td>#<?php echo htmlspecialchars($displayId, ENT_QUOTES, 'UTF-8'); ?></td>
                                        <td><?php echo htmlspecialchars(date('d M Y, h:i A', strtotime($row['create_date'])), ENT_QUOTES, 'UTF-8'); ?></td>
                                        <td>₹<?php echo number_format((float)$row['amount'], 2); ?></td>
                                        <td><span class="badge-status <?php echo $badgeClass; ?>"><?php echo htmlspecialchars($st, ENT_QUOTES, 'UTF-8'); ?></span></td>
                                    </tr>
                                <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <?php else: ?>
                            <div class="empty-state"><i class="fas fa-inbox mb-2" style="font-size:28px;display:block"></i>No transactions yet.</div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="./assets/vendors/jquery/dist/jquery.min.js"></script>
    <!-- Loading Chart.js straight from CDN — the local vendor copy on this
         server appears to be missing/corrupt (loads with no error but never
         defines window.Chart), which is why the graphs stayed blank. -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.4/dist/chart.umd.min.js"></script>
    <script src="./assets/vendors/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="./assets/js/app.min.js"></script>

    <script>
    // (Mobile drawer button + force-hide-loader scripts moved to header.php
    // so every page gets them, not just this one.)

    // (forceHideLoader moved to header.php - runs on every page now)

    var __chartsInitDone = false;
    var trendChartInstance = null;
    var doughnutChartInstance = null;
    var methodChartInstance = null;
    var hourlyChartInstance = null;

    window.initDashboardCharts = function () {
        if (__chartsInitDone) return;
        if (typeof Chart === 'undefined') return;
        var trendEl = document.getElementById('trend_chart');
        var doughnutEl = document.getElementById('doughnut_chart');
        if (!trendEl || !doughnutEl) return;
        __chartsInitDone = true;

        Chart.defaults.color = 'rgba(255,255,255,.55)';
        Chart.defaults.font.family = "'Inter', sans-serif";

        const labels = <?php echo json_encode($chartLabels); ?>;
        const successData = <?php echo json_encode($chartSuccess); ?>;
        const failedData = <?php echo json_encode($chartFailed); ?>;

        const trendCtx = trendEl.getContext('2d');
        const successGrad = trendCtx.createLinearGradient(0, 0, 0, 300);
        successGrad.addColorStop(0, 'rgba(67,233,123,.35)');
        successGrad.addColorStop(1, 'rgba(67,233,123,0)');
        const failGrad = trendCtx.createLinearGradient(0, 0, 0, 300);
        failGrad.addColorStop(0, 'rgba(255,101,132,.3)');
        failGrad.addColorStop(1, 'rgba(255,101,132,0)');

        trendChartInstance = new Chart(trendCtx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [
                    { label: 'Successful (₹)', data: successData, borderColor: '#43e97b', backgroundColor: successGrad, fill: true, tension: 0.4, pointBackgroundColor: '#43e97b', pointRadius: 4, borderWidth: 2 },
                    { label: 'Failed (₹)', data: failedData, borderColor: '#ff6584', backgroundColor: failGrad, fill: true, tension: 0.4, pointBackgroundColor: '#ff6584', pointRadius: 4, borderWidth: 2 }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: { beginAtZero: true, grid: { color: 'rgba(255,255,255,.06)' }, ticks: { callback: v => '₹' + v } },
                    x: { grid: { display: false } }
                },
                plugins: {
                    legend: { position: 'top', labels: { usePointStyle: true, boxWidth: 8 } },
                    tooltip: { backgroundColor: '#15151f', padding: 12, cornerRadius: 10, displayColors: true, intersect: false, mode: 'index' }
                }
            }
        });

        const doughnutCtx = doughnutEl.getContext('2d');
        doughnutChartInstance = new Chart(doughnutCtx, {
            type: 'doughnut',
            data: {
                labels: ['Successful', 'Pending', 'Failed'],
                datasets: [{
                    data: [<?php echo $successPct; ?>, <?php echo $pendingPct; ?>, <?php echo $failPct; ?>],
                    backgroundColor: ['#43e97b', '#f5b93b', '#ff6584'],
                    borderWidth: 0,
                    hoverOffset: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '72%',
                plugins: {
                    legend: { display: false },
                    tooltip: { backgroundColor: '#15151f', padding: 12, cornerRadius: 10 }
                }
            }
        });

        // ---- Top Payment Methods (horizontal bar) ----
        var methodEl = document.getElementById('method_chart');
        if (methodEl) {
            const methodLabels = <?php echo json_encode($methodLabels); ?>;
            const methodAmounts = <?php echo json_encode($methodAmounts); ?>;
            const methodColors = ['#6c63ff', '#e040fb', '#3ea6ff', '#43e97b', '#f5b93b', '#ff6584'];
            methodChartInstance = new Chart(methodEl.getContext('2d'), {
                type: 'bar',
                data: {
                    labels: methodLabels,
                    datasets: [{
                        data: methodAmounts,
                        backgroundColor: methodColors,
                        borderRadius: 8,
                        barThickness: 18
                    }]
                },
                options: {
                    indexAxis: 'y',
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        x: { beginAtZero: true, grid: { color: 'rgba(255,255,255,.06)' }, ticks: { callback: v => '₹' + v } },
                        y: { grid: { display: false } }
                    },
                    plugins: {
                        legend: { display: false },
                        tooltip: { backgroundColor: '#15151f', padding: 12, cornerRadius: 10, callbacks: { label: (ctx) => '₹' + ctx.parsed.x.toLocaleString() } }
                    }
                }
            });
        }

        // ---- Today's Activity (smooth area, by 2-hour block) ----
        var hourlyEl = document.getElementById('hourly_chart');
        if (hourlyEl) {
            const hourlyLabels = <?php echo json_encode($hourlyLabels); ?>;
            const hourlyCounts = <?php echo json_encode($hourlyCounts); ?>;
            const hourlyCtx = hourlyEl.getContext('2d');
            const hourlyGrad = hourlyCtx.createLinearGradient(0, 0, 0, 230);
            hourlyGrad.addColorStop(0, 'rgba(108,99,255,.4)');
            hourlyGrad.addColorStop(1, 'rgba(224,64,251,.02)');
            hourlyChartInstance = new Chart(hourlyCtx, {
                type: 'line',
                data: {
                    labels: hourlyLabels,
                    datasets: [{
                        label: 'Transactions',
                        data: hourlyCounts,
                        borderColor: '#a99bff',
                        backgroundColor: hourlyGrad,
                        fill: true,
                        tension: 0.45,
                        pointBackgroundColor: '#6c63ff',
                        pointRadius: 3,
                        borderWidth: 2.5
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: { beginAtZero: true, ticks: { precision: 0 }, grid: { color: 'rgba(255,255,255,.06)' } },
                        x: { grid: { display: false } }
                    },
                    plugins: {
                        legend: { display: false },
                        tooltip: { backgroundColor: '#15151f', padding: 12, cornerRadius: 10 }
                    }
                }
            });
        }
    };

    document.addEventListener('DOMContentLoaded', function () {
        window.initDashboardCharts();
        // Keep retrying briefly in case Chart.js (local vendor file or CDN
        // fallback) is still downloading when the DOM is ready — covers
        // slow/broken local script paths without needing the onerror hook.
        var tries = 0;
        var poll = setInterval(function () {
            tries++;
            window.initDashboardCharts();
            if (__chartsInitDone || tries > 20) clearInterval(poll);
        }, 300);
    });

    // ============================================================
    // REAL-TIME POLLING — pulls ?ajax=stats from this same page every
    // few seconds and updates numbers, charts and the recent-transactions
    // table live, without a full page reload.
    // ============================================================
    (function realtime() {
        function fmtMoney(n) {
            return '₹' + Number(n).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        }
        function setChanged(el, newText) {
            if (!el) return;
            if (el.textContent.trim() === String(newText).trim()) return;
            el.textContent = newText;
            el.classList.remove('flash-update');
            void el.offsetWidth; // restart animation
            el.classList.add('flash-update');
        }
        function changeArrowHTML(val, invert) {
            var up = invert ? val <= 0 : val >= 0;
            return '<i class="fas fa-arrow-' + (up ? 'up' : 'down') + '"></i> ' + Math.abs(val) + '% vs yesterday';
        }
        function badgeClassFor(status) {
            if (status === 'SUCCESS') return 'badge-success-s';
            if (status === 'PENDING') return 'badge-warning-s';
            return 'badge-danger-s';
        }

        function applyData(d) {
            setChanged(document.getElementById('s-received'), fmtMoney(d.todayReceived));
            setChanged(document.getElementById('s-success-cnt'), Number(d.todaySuccessCnt).toLocaleString('en-IN'));
            setChanged(document.getElementById('s-pending'), fmtMoney(d.todayPending));
            setChanged(document.getElementById('s-failed'), fmtMoney(d.todayFailed));
            setChanged(document.getElementById('s-total-txn'), Number(d.totalTxnAll).toLocaleString('en-IN'));
            setChanged(document.getElementById('s-success-rate'), d.successRate + '%');

            var recEl = document.getElementById('s-received-change');
            if (recEl) recEl.innerHTML = changeArrowHTML(d.successAmtChange, false);
            var succCntEl = document.getElementById('s-success-cnt-change');
            if (succCntEl) succCntEl.innerHTML = changeArrowHTML(d.successCntChange, false);
            var pendEl = document.getElementById('s-pending-change');
            if (pendEl) pendEl.innerHTML = changeArrowHTML(d.pendingChange, false);
            var failEl = document.getElementById('s-failed-change');
            if (failEl) failEl.innerHTML = changeArrowHTML(d.failChange, true);
            var rateSubEl = document.getElementById('s-success-rate-sub');
            if (rateSubEl) rateSubEl.innerHTML = '<i class="fas fa-database"></i> ' + d.totalSuccessAll + ' of ' + d.totalTxnAll + ' orders';

            setChanged(document.getElementById('dist-success-pct'), d.successPct + '%');
            setChanged(document.getElementById('dist-pending-pct'), d.pendingPct + '%');
            setChanged(document.getElementById('dist-fail-pct'), d.failPct + '%');

            if (trendChartInstance) {
                trendChartInstance.data.labels = d.chartLabels;
                trendChartInstance.data.datasets[0].data = d.chartSuccess;
                trendChartInstance.data.datasets[1].data = d.chartFailed;
                trendChartInstance.update();
            }
            if (doughnutChartInstance) {
                doughnutChartInstance.data.datasets[0].data = [d.successPct, d.pendingPct, d.failPct];
                doughnutChartInstance.update();
            }
            if (methodChartInstance && d.methodLabels) {
                methodChartInstance.data.labels = d.methodLabels;
                methodChartInstance.data.datasets[0].data = d.methodAmounts;
                methodChartInstance.update();
            }
            if (hourlyChartInstance && d.hourlyLabels) {
                hourlyChartInstance.data.labels = d.hourlyLabels;
                hourlyChartInstance.data.datasets[0].data = d.hourlyCounts;
                hourlyChartInstance.update();
            }

            var tbody = document.getElementById('recent-tx-tbody');
            var container = document.getElementById('recent-tx-container');
            if (d.recent && d.recent.length > 0) {
                var rowsHtml = d.recent.map(function (row) {
                    return '<tr><td>#' + row.id + '</td><td>' + row.date + '</td><td>' +
                        fmtMoney(row.amount) + '</td><td><span class="badge-status ' +
                        badgeClassFor(row.status) + '">' + row.status + '</span></td></tr>';
                }).join('');
                if (tbody) {
                    tbody.innerHTML = rowsHtml;
                } else if (container) {
                    container.innerHTML =
                        '<div class="table-responsive"><table class="table"><thead><tr>' +
                        '<th>Order ID</th><th>Date</th><th>Amount</th><th>Status</th>' +
                        '</tr></thead><tbody id="recent-tx-tbody">' + rowsHtml + '</tbody></table></div>';
                }
            } else if (container) {
                container.innerHTML = '<div class="empty-state"><i class="fas fa-inbox mb-2" style="font-size:28px;display:block"></i>No transactions yet.</div>';
            }
        }

        function poll() {
            fetch(window.location.pathname + '?ajax=stats', { cache: 'no-store' })
                .then(function (res) { return res.ok ? res.json() : null; })
                .then(function (d) { if (d) applyData(d); })
                .catch(function () { /* silent — keep last known good data on screen */ });
        }

        // First poll shortly after load (data is already server-rendered,
        // this just keeps things fresh), then every 10 seconds.
        setTimeout(poll, 4000);
        setInterval(poll, 10000);

        // Also refresh immediately whenever the tab becomes visible again
        document.addEventListener('visibilitychange', function () {
            if (document.visibilityState === 'visible') poll();
        });
    })();
    </script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
    (function () {
        var params = new URLSearchParams(window.location.search);
        if (params.get('plan_activated') === '1') {
            Swal.fire({
                icon: 'success',
                title: 'Plan Activated Successfully!',
                text: 'Your new subscription plan is now active on your account.',
                confirmButtonText: 'Great!'
            });
            var url = new URL(window.location.href);
            url.searchParams.delete('plan_activated');
            window.history.replaceState({}, document.title, url.toString());
        } else if (params.get('plan_activated') === '0') {
            Swal.fire({
                icon: 'warning',
                title: 'Payment Received, Activation Pending',
                text: 'Your payment was successful but we could not activate the plan automatically. Please contact support.',
                confirmButtonText: 'OK'
            });
            var url2 = new URL(window.location.href);
            url2.searchParams.delete('plan_activated');
            url2.searchParams.delete('reason');
            window.history.replaceState({}, document.title, url2.toString());
        }
    })();
    </script>
</body>
</html>
