<?php
include 'config.php';
checkLogin();

$page_title = "Closing & Audit System";
$active_page = "closing";
include 'layout.php';

// --- LOGIKA FILTER ---
$start_date    = $_GET['start_date']   ?? date('Y-m-d');
$end_date      = $_GET['end_date']     ?? date('Y-m-d');
$user_filter   = $_GET['user_id']      ?? 'all';
$action_filter = $_GET['action_type']  ?? 'all';

// ============================================================
// [OPT] AUTO-CREATE INDEX — jalankan sekali, skip kalau sudah ada
// ============================================================
foreach ([
    "ALTER TABLE transactions  ADD INDEX IF NOT EXISTS idx_end_status (end_time, status)",
    "ALTER TABLE orders_fnb    ADD INDEX IF NOT EXISTS idx_created    (created_at)",
    "ALTER TABLE activity_logs ADD INDEX IF NOT EXISTS idx_created    (created_at)",
    "ALTER TABLE member_topups ADD INDEX IF NOT EXISTS idx_created    (created_at)",
] as $idx_sql) {
    @$conn->query($idx_sql);
}

// ============================================================
// [OPT] 1. BILLING + COUNT — 1 query (tadinya 2)
// ============================================================
$stmt_bill = $conn->prepare("
    SELECT SUM(total_bayar) as total, COUNT(*) as cnt
    FROM transactions
    WHERE DATE(end_time) BETWEEN ? AND ? AND status = 'completed'
");
$stmt_bill->bind_param("ss", $start_date, $end_date);
$stmt_bill->execute();
$res_bill   = $stmt_bill->get_result()->fetch_assoc();
$total_bill = $res_bill['total'] ?? 0;
$count_bill = $res_bill['cnt']   ?? 0;
$stmt_bill->close();

// ============================================================
// [OPT] 2. FNB + COUNT — 1 query (tadinya 2)
// ============================================================
$stmt_fnb = $conn->prepare("
    SELECT SUM(total_harga) as total, COUNT(*) as cnt
    FROM orders_fnb
    WHERE DATE(created_at) BETWEEN ? AND ?
");
$stmt_fnb->bind_param("ss", $start_date, $end_date);
$stmt_fnb->execute();
$res_fnb   = $stmt_fnb->get_result()->fetch_assoc();
$total_fnb = $res_fnb['total'] ?? 0;
$count_fnb = $res_fnb['cnt']   ?? 0;
$stmt_fnb->close();

// ============================================================
// [OPT] 3. TOPUP + COUNT — 1 query (tadinya 2)
// ============================================================
$stmt_topup = $conn->prepare("
    SELECT SUM(amount) as total, COUNT(*) as cnt
    FROM member_topups
    WHERE DATE(created_at) BETWEEN ? AND ?
");
$stmt_topup->bind_param("ss", $start_date, $end_date);
$stmt_topup->execute();
$res_topup   = $stmt_topup->get_result()->fetch_assoc();
$total_topup = $res_topup['total'] ?? 0;
$count_topup = $res_topup['cnt']   ?? 0;
$stmt_topup->close();

$grand_total = $total_bill + $total_fnb + $total_topup;

// ============================================================
// 4. QUERY LOG AKTIVITAS — dengan filter + LIMIT 300
// ============================================================
$log_where  = "DATE(created_at) BETWEEN ? AND ?";
$log_params = [$start_date, $end_date];
$log_types  = "ss";

if ($user_filter !== 'all') {
    $log_where   .= " AND user_id = ?";
    $log_params[] = $user_filter;
    $log_types   .= "i";
}
if ($action_filter !== 'all') {
    $log_where   .= " AND action LIKE ?";
    $log_params[] = "%$action_filter%";
    $log_types   .= "s";
}

// [OPT] Tambah LIMIT agar tidak load semua baris sekaligus
$stmt_log = $conn->prepare("
    SELECT * FROM activity_logs
    WHERE $log_where
    ORDER BY created_at DESC
    LIMIT 300
");
$stmt_log->bind_param($log_types, ...$log_params);
$stmt_log->execute();
$logs = $stmt_log->get_result();

// ============================================================
// [OPT] 5. LOG STATS — 1 query (sudah 1, tidak berubah)
// ============================================================
$stmt_log_stats = $conn->prepare("
    SELECT
        SUM(CASE WHEN action LIKE '%START%'                          THEN 1 ELSE 0 END) as cnt_start,
        SUM(CASE WHEN action LIKE '%STOP%'                           THEN 1 ELSE 0 END) as cnt_stop,
        SUM(CASE WHEN action LIKE '%FNB%' OR action LIKE '%ORDER%'   THEN 1 ELSE 0 END) as cnt_fnb,
        SUM(CASE WHEN action LIKE '%REMOTE%' OR action LIKE '%ADB%'  THEN 1 ELSE 0 END) as cnt_remote,
        SUM(CASE WHEN action LIKE '%LOGIN%'                          THEN 1 ELSE 0 END) as cnt_login,
        SUM(CASE WHEN action LIKE '%ADD_TIME%'                       THEN 1 ELSE 0 END) as cnt_addtime,
        SUM(CASE WHEN action LIKE '%BYPASS%' OR details LIKE '%BYPASS%' THEN 1 ELSE 0 END) as cnt_bypass,
        SUM(CASE WHEN action LIKE '%CANCEL%' OR action LIKE '%DELETE%' THEN 1 ELSE 0 END) as cnt_cancel,
        COUNT(*) as cnt_total
    FROM activity_logs
    WHERE DATE(created_at) BETWEEN ? AND ?
");
$stmt_log_stats->bind_param("ss", $start_date, $end_date);
$stmt_log_stats->execute();
$log_stats = $stmt_log_stats->get_result()->fetch_assoc();
$stmt_log_stats->close();

// ============================================================
// 6. ANOMALI — transaksi < 2 menit, LIMIT 20
// ============================================================
$stmt_anomali = $conn->prepare("
    SELECT t.id, t.tv_id, tv.nama_tv,
        t.start_time, t.end_time, t.total_bayar, t.jenis_paket, t.status,
        m.nama_member,
        TIMESTAMPDIFF(SECOND, t.start_time, IFNULL(t.end_time, NOW())) as durasi_detik
    FROM transactions t
    LEFT JOIN tvs tv ON t.tv_id = tv.id
    LEFT JOIN members m ON t.member_id = m.id
    WHERE DATE(IFNULL(t.end_time, t.start_time)) BETWEEN ? AND ?
    AND t.status = 'completed'
    AND TIMESTAMPDIFF(SECOND, t.start_time, t.end_time) < 120
    ORDER BY t.end_time DESC
    LIMIT 20
");
$stmt_anomali->bind_param("ss", $start_date, $end_date);
$stmt_anomali->execute();
$anomali_list = $stmt_anomali->get_result();
$stmt_anomali->close();

// ============================================================
// 7. STATISTIK PER OPERATOR
// ============================================================
$stmt_op_stats = $conn->prepare("
    SELECT username,
        COUNT(*) as total_log,
        SUM(CASE WHEN action LIKE '%START%'           THEN 1 ELSE 0 END) as cnt_start,
        SUM(CASE WHEN action LIKE '%STOP%'            THEN 1 ELSE 0 END) as cnt_stop,
        SUM(CASE WHEN details LIKE '%BYPASS%'         THEN 1 ELSE 0 END) as cnt_bypass,
        MIN(created_at) as first_action,
        MAX(created_at) as last_action
    FROM activity_logs
    WHERE DATE(created_at) BETWEEN ? AND ?
    GROUP BY username
    ORDER BY total_log DESC
");
$stmt_op_stats->bind_param("ss", $start_date, $end_date);
$stmt_op_stats->execute();
$op_stats_list = $stmt_op_stats->get_result();
$stmt_op_stats->close();

// ============================================================
// [OPT] 8. TRANSAKSI DETAIL — hapus LEFT JOIN activity_logs
//          yang sangat lambat karena pakai LIKE '%Trx #N%'
//          Ganti: stopped_by diambil terpisah hanya kalau diperlukan
// ============================================================
$stmt_trx_detail = $conn->prepare("
    SELECT t.id, t.tv_id, tv.nama_tv, t.start_time, t.end_time,
        t.total_bayar, t.jenis_paket, t.stik_info,
        m.nama_member,
        IFNULL(fnb.fnb_total, 0) as fnb_total,
        TIMESTAMPDIFF(MINUTE, t.start_time, IFNULL(t.end_time, NOW())) as durasi_menit
    FROM transactions t
    LEFT JOIN tvs tv ON t.tv_id = tv.id
    LEFT JOIN members m ON t.member_id = m.id
    LEFT JOIN (
        SELECT trx_id, SUM(total_harga) as fnb_total
        FROM orders_fnb
        GROUP BY trx_id
    ) fnb ON t.id = fnb.trx_id
    WHERE DATE(IFNULL(t.end_time, t.start_time)) BETWEEN ? AND ?
    AND t.status = 'completed'
    ORDER BY t.end_time DESC
    LIMIT 500
");
$stmt_trx_detail->bind_param("ss", $start_date, $end_date);
$stmt_trx_detail->execute();
$trx_detail_list = $stmt_trx_detail->get_result();
$stmt_trx_detail->close();
?>

<link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>
<link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@700;900&family=JetBrains+Mono:wght@400;500;600;700&family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">

<style>
:root {
    --glass: rgba(15, 23, 42, 0.7);
    --border: rgba(255, 255, 255, 0.07);
    --primary: #06b6d4;
    --primary-glow: rgba(6,182,212,0.25);
    --success: #10b981;
    --warning: #f59e0b;
    --danger: #ef4444;
    --purple: #a855f7;
    --bg: #030712;
}
* { box-sizing: border-box; }
body { font-family: 'Plus Jakarta Sans', sans-serif; background: var(--bg); color: #e2e8f0; }

.filter-bar { display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-end;
    background: var(--glass); border: 1px solid var(--border); border-radius: 18px;
    padding: 20px; margin-bottom: 24px; backdrop-filter: blur(12px); }
.filter-bar label { display: block; font-size: 0.7rem; color: #64748b; font-weight: 700;
    text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 5px; }
.filter-bar input, .filter-bar select {
    background: rgba(0,0,0,0.4); border: 1px solid var(--border);
    padding: 10px 14px; border-radius: 10px; color: #fff; font-size: 0.85rem;
    outline: none; transition: 0.3s; min-width: 150px; }
.filter-bar input:focus, .filter-bar select:focus { border-color: var(--primary); }
.filter-bar button { background: linear-gradient(135deg, var(--primary), #0891b2);
    border: none; padding: 11px 22px; border-radius: 10px; color: #000;
    font-weight: 800; cursor: pointer; transition: 0.3s; font-size: 0.85rem; }
.filter-bar button:hover { transform: translateY(-2px); box-shadow: 0 5px 20px var(--primary-glow); }

.summary-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px; margin-bottom: 24px; }
.sum-card { background: var(--glass); border: 1px solid var(--border); border-radius: 18px;
    padding: 22px; position: relative; overflow: hidden; transition: 0.3s; backdrop-filter: blur(12px); }
.sum-card:hover { transform: translateY(-4px); border-color: var(--primary); }
.sum-card::after { content: ''; position: absolute; bottom: 0; left: 0; right: 0; height: 3px;
    background: var(--primary); opacity: 0.4; }
.sum-card.highlight { border-color: rgba(6,182,212,0.4); background: rgba(6,182,212,0.06); }
.sum-card.highlight::after { opacity: 1; }
.sum-card.danger-card { border-color: rgba(239,68,68,0.3); background: rgba(239,68,68,0.05); }
.sum-card.danger-card::after { background: var(--danger); opacity: 0.8; }
.sum-icon { width: 44px; height: 44px; border-radius: 11px; display: flex; align-items: center;
    justify-content: center; font-size: 1.3rem; margin-bottom: 12px; }
.sum-icon.cyan   { background: rgba(6,182,212,0.12);  color: var(--primary); }
.sum-icon.amber  { background: rgba(245,158,11,0.12); color: var(--warning); }
.sum-icon.green  { background: rgba(16,185,129,0.12); color: var(--success); }
.sum-icon.purple { background: rgba(168,85,247,0.12); color: var(--purple); }
.sum-icon.red    { background: rgba(239,68,68,0.12);  color: var(--danger); }
.sum-label { color: #64748b; font-size: 0.72rem; font-weight: 700; text-transform: uppercase;
    letter-spacing: 0.5px; margin-bottom: 5px; }
.sum-value { color: #fff; font-size: 1.6rem; font-weight: 800;
    font-family: 'JetBrains Mono', monospace; }
.sum-card.highlight .sum-value { color: var(--primary); }
.sum-card.danger-card .sum-value { color: var(--danger); }
.sum-sub { font-size: 0.7rem; color: #475569; margin-top: 4px; }

.tabs-wrapper { background: var(--glass); border: 1px solid var(--border);
    border-radius: 22px; overflow: hidden; backdrop-filter: blur(12px); }
.tabs-header { display: flex; gap: 8px; background: rgba(0,0,0,0.3); padding: 10px; flex-wrap: wrap; }
.tab-btn { padding: 11px 20px; border-radius: 11px; border: none; background: transparent;
    color: #64748b; cursor: pointer; font-weight: 700; font-size: 0.78rem; transition: 0.3s;
    display: flex; align-items: center; gap: 7px; white-space: nowrap; }
.tab-btn:hover { background: rgba(255,255,255,0.05); color: #fff; }
.tab-btn.active { background: var(--primary); color: #000; }
.tab-btn.danger-tab.active { background: var(--danger); color: #fff; }
.tab-cnt { background: rgba(0,0,0,0.3); padding: 1px 7px; border-radius: 6px; font-size: 0.68rem; }
.tab-pane { padding: 24px; display: none; }
.tab-pane.active { display: block; }

.data-table { width: 100%; border-collapse: collapse; }
.data-table th { text-align: left; padding: 13px 14px; color: #475569; font-size: 0.7rem;
    text-transform: uppercase; letter-spacing: 0.5px; border-bottom: 1px solid var(--border);
    background: rgba(0,0,0,0.25); white-space: nowrap; }
.data-table td { padding: 13px 14px; border-bottom: 1px solid rgba(255,255,255,0.03);
    font-size: 0.85rem; color: #cbd5e1; vertical-align: middle; }
.data-table tr:hover { background: rgba(6,182,212,0.04); }
.data-table tfoot th { background: rgba(6,182,212,0.1); color: #fff; }
.scroll-wrap { overflow-x: auto; max-height: 580px; overflow-y: auto; }
.scroll-wrap thead { position: sticky; top: 0; z-index: 2; }

.badge { display: inline-flex; align-items: center; gap: 4px; padding: 4px 9px;
    border-radius: 7px; font-size: 0.68rem; font-weight: 800; text-transform: uppercase;
    letter-spacing: 0.3px; white-space: nowrap; }
.b-start   { background: rgba(16,185,129,0.15);  color: #10b981; }
.b-stop    { background: rgba(239,68,68,0.15);   color: #ef4444; }
.b-pause   { background: rgba(245,158,11,0.15);  color: #f59e0b; }
.b-resume  { background: rgba(34,211,238,0.15);  color: #22d3ee; }
.b-fnb     { background: rgba(245,158,11,0.15);  color: #f59e0b; }
.b-addtime { background: rgba(59,130,246,0.15);  color: #3b82f6; }
.b-move    { background: rgba(59,130,246,0.15);  color: #3b82f6; }
.b-topup   { background: rgba(168,85,247,0.15);  color: #a855f7; }
.b-remote  { background: rgba(139,92,246,0.15);  color: #8b5cf6; }
.b-login   { background: rgba(16,185,129,0.15);  color: #10b981; }
.b-logout  { background: rgba(100,116,139,0.15); color: #94a3b8; }
.b-bypass  { background: rgba(239,68,68,0.25);   color: #fca5a5; border: 1px solid rgba(239,68,68,0.4); }
.b-cancel  { background: rgba(239,68,68,0.15);   color: #ef4444; }
.b-default { background: rgba(71,85,105,0.2);    color: #64748b; }
.b-warn    { background: rgba(239,68,68,0.15);   color: #ef4444; }

.redflag-row { background: rgba(239,68,68,0.06) !important; border-left: 3px solid var(--danger); }
.redflag-icon { color: var(--danger); font-size: 1rem; vertical-align: middle; }

.op-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
    gap: 14px; margin-bottom: 20px; }
.op-card { background: rgba(0,0,0,0.3); border: 1px solid var(--border); border-radius: 16px;
    padding: 18px; transition: 0.3s; }
.op-card:hover { border-color: var(--primary); }
.op-card.has-bypass { border-color: rgba(239,68,68,0.5); background: rgba(239,68,68,0.05); }
.op-name { font-weight: 800; font-size: 1rem; color: #fff; margin-bottom: 12px;
    display: flex; align-items: center; gap: 8px; }
.op-stat-row { display: flex; justify-content: space-between; font-size: 0.8rem;
    color: #64748b; padding: 5px 0; border-bottom: 1px solid rgba(255,255,255,0.04); }
.op-stat-row:last-child { border-bottom: none; }
.op-stat-val { font-weight: 700; color: #e2e8f0; font-family: 'JetBrains Mono', monospace; }
.op-stat-val.red  { color: var(--danger); }
.op-stat-val.cyan { color: var(--primary); }

.log-chips { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 18px; }
.chip { background: rgba(0,0,0,0.3); border: 1px solid var(--border); padding: 7px 14px;
    border-radius: 8px; font-size: 0.75rem; font-weight: 700; display: flex; align-items: center;
    gap: 7px; color: #64748b; cursor: pointer; transition: 0.3s; }
.chip:hover, .chip.active { border-color: var(--primary); color: var(--primary);
    background: rgba(6,182,212,0.08); }
.chip-num { background: rgba(6,182,212,0.15); color: var(--primary); padding: 1px 7px;
    border-radius: 5px; font-family: 'JetBrains Mono'; font-size: 0.7rem; }
.chip-num.red { background: rgba(239,68,68,0.2); color: #f87171; }

.hl-tv     { color: var(--primary); font-weight: 700; }
.hl-rp     { color: var(--success); font-family: 'JetBrains Mono'; font-weight: 700; }
.hl-dur    { color: #fbbf24; font-weight: 700; }
.hl-user   { color: #a78bfa; font-weight: 700; }
.hl-sep    { color: #334155; }
.hl-bypass { color: var(--danger); font-weight: 800; background: rgba(239,68,68,0.1);
    padding: 1px 6px; border-radius: 4px; }
.hl-cash   { color: #fbbf24; font-weight: 700; }
.hl-saldo  { color: var(--success); font-weight: 700; }

.warn-box { background: rgba(239,68,68,0.08); border: 1px solid rgba(239,68,68,0.2);
    border-radius: 14px; padding: 16px 18px; display: flex; gap: 12px; align-items: flex-start;
    margin-top: 20px; }
.warn-box i { font-size: 1.4rem; color: var(--danger); flex-shrink: 0; margin-top: 2px; }
.warn-box p { margin: 0; color: #fca5a5; font-size: 0.85rem; line-height: 1.6; }

.anom-dur { font-family: 'JetBrains Mono'; }

.sec-title { font-size: 0.85rem; font-weight: 800; color: #94a3b8;
    text-transform: uppercase; letter-spacing: 1px; margin-bottom: 16px;
    display: flex; align-items: center; gap: 8px; }
.sec-title i { color: var(--primary); }

.empty-state { text-align: center; padding: 48px 20px; color: #334155; }
.empty-state i { font-size: 3.5rem; margin-bottom: 12px; opacity: 0.25; }

.limit-notice { font-size: 0.72rem; color: #334155; text-align: right;
    padding: 6px 0; margin-bottom: 8px; }

@media (max-width: 768px) {
    .filter-bar { flex-direction: column; }
    .summary-grid { grid-template-columns: 1fr 1fr; }
    .sum-value { font-size: 1.2rem; }
    .tabs-header { gap: 4px; }
    .tab-btn { padding: 9px 12px; font-size: 0.72rem; }
}
</style>

<!-- ══════════════════════════════════════════
     FILTER BAR
══════════════════════════════════════════ -->
<form method="GET" class="filter-bar">
    <div>
        <label>Dari Tanggal</label>
        <input type="date" name="start_date" value="<?= htmlspecialchars($start_date) ?>">
    </div>
    <div>
        <label>Sampai Tanggal</label>
        <input type="date" name="end_date" value="<?= htmlspecialchars($end_date) ?>">
    </div>
    <?php if ($_SESSION['role'] == 'admin'): ?>
    <div>
        <label>Operator</label>
        <select name="user_id">
            <option value="all">Semua Operator</option>
            <?php
            $us = $conn->query("SELECT id, username FROM users ORDER BY username");
            while ($u = $us->fetch_assoc()) {
                $sel = ($user_filter == $u['id']) ? 'selected' : '';
                echo "<option value='{$u['id']}' $sel>" . htmlspecialchars($u['username']) . "</option>";
            } ?>
        </select>
    </div>
    <?php endif; ?>
    <div>
        <label>Jenis Aktivitas</label>
        <select name="action_type">
            <option value="all"      <?= $action_filter=='all'      ?'selected':'' ?>>Semua Aksi</option>
            <option value="START"    <?= $action_filter=='START'    ?'selected':'' ?>>▶ Start Session</option>
            <option value="STOP"     <?= $action_filter=='STOP'     ?'selected':'' ?>>⏹ Stop Session</option>
            <option value="FNB"      <?= $action_filter=='FNB'      ?'selected':'' ?>>🍔 Order FnB</option>
            <option value="ADD_TIME" <?= $action_filter=='ADD_TIME' ?'selected':'' ?>>⏱ Tambah Waktu</option>
            <option value="PAUSE"    <?= $action_filter=='PAUSE'    ?'selected':'' ?>>⏸ Pause</option>
            <option value="RESUME"   <?= $action_filter=='RESUME'   ?'selected':'' ?>>▶ Resume</option>
            <option value="BYPASS"   <?= $action_filter=='BYPASS'   ?'selected':'' ?>>⚠ Bypass Saldo</option>
            <option value="MOVE"     <?= $action_filter=='MOVE'     ?'selected':'' ?>>↔ Pindah TV</option>
            <option value="TOPUP"    <?= $action_filter=='TOPUP'    ?'selected':'' ?>>💰 Top Up</option>
            <option value="REMOTE"   <?= $action_filter=='REMOTE'   ?'selected':'' ?>>🎮 Remote</option>
            <option value="LOGIN"    <?= $action_filter=='LOGIN'    ?'selected':'' ?>>🔑 Login</option>
        </select>
    </div>
    <button type="submit"><i class='bx bx-filter-alt'></i> FILTER</button>
</form>

<!-- ══════════════════════════════════════════
     SUMMARY CARDS
══════════════════════════════════════════ -->
<div class="summary-grid">
    <div class="sum-card">
        <div class="sum-icon cyan"><i class='bx bx-tv'></i></div>
        <div class="sum-label">Billing Rental</div>
        <div class="sum-value">Rp <?= number_format($total_bill) ?></div>
        <div class="sum-sub"><?= $count_bill ?> transaksi selesai</div>
    </div>
    <div class="sum-card">
        <div class="sum-icon amber"><i class='bx bx-food-menu'></i></div>
        <div class="sum-label">Penjualan F&B</div>
        <div class="sum-value">Rp <?= number_format($total_fnb) ?></div>
        <div class="sum-sub"><?= $count_fnb ?> item terjual</div>
    </div>
    <div class="sum-card">
        <div class="sum-icon purple"><i class='bx bx-wallet'></i></div>
        <div class="sum-label">Top Up Member</div>
        <div class="sum-value">Rp <?= number_format($total_topup) ?></div>
        <div class="sum-sub"><?= $count_topup ?> transaksi top-up</div>
    </div>
    <div class="sum-card highlight">
        <div class="sum-icon cyan"><i class='bx bx-money'></i></div>
        <div class="sum-label" style="color:var(--primary)">Total Cash di Laci</div>
        <div class="sum-value">Rp <?= number_format($grand_total) ?></div>
        <div class="sum-sub" style="color:rgba(6,182,212,0.6)">Wajib cocok dengan fisik</div>
    </div>
    <?php if (($log_stats['cnt_bypass'] ?? 0) > 0): ?>
    <div class="sum-card danger-card">
        <div class="sum-icon red"><i class='bx bxs-error'></i></div>
        <div class="sum-label">⚠ Bypass Saldo</div>
        <div class="sum-value"><?= $log_stats['cnt_bypass'] ?> kali</div>
        <div class="sum-sub" style="color:rgba(239,68,68,0.7)">Perlu verifikasi admin</div>
    </div>
    <?php endif; ?>
</div>

<!-- ══════════════════════════════════════════
     TABS
══════════════════════════════════════════ -->
<div class="tabs-wrapper">
    <div class="tabs-header">
        <button class="tab-btn active" onclick="openTab(event,'income')">
            <i class='bx bx-money'></i> Pendapatan
        </button>
        <button class="tab-btn" onclick="openTab(event,'trx')">
            <i class='bx bx-receipt'></i> Semua Transaksi
            <span class="tab-cnt"><?= $count_bill ?></span>
        </button>
        <button class="tab-btn" onclick="openTab(event,'audit')">
            <i class='bx bx-fingerprint'></i> Log Aktivitas
            <span class="tab-cnt"><?= $log_stats['cnt_total'] ?? 0 ?></span>
        </button>
        <button class="tab-btn" onclick="openTab(event,'operator')">
            <i class='bx bx-user-check'></i> Per Operator
        </button>
        <?php if ($anomali_list->num_rows > 0): ?>
        <button class="tab-btn danger-tab" onclick="openTab(event,'anomali')">
            <i class='bx bxs-error-alt'></i> Red Flags
            <span class="tab-cnt" style="background:rgba(239,68,68,0.3);color:#fca5a5;"><?= $anomali_list->num_rows ?></span>
        </button>
        <?php endif; ?>
    </div>

    <!-- ─── TAB 1: PENDAPATAN ─── -->
    <div id="income" class="tab-pane active">
        <div class="sec-title"><i class='bx bx-bar-chart-alt-2'></i> Breakdown Keuangan</div>
        <div class="scroll-wrap">
            <table class="data-table">
                <thead><tr>
                    <th>Kategori</th>
                    <th>Jumlah Transaksi</th>
                    <th style="text-align:right">Subtotal</th>
                </tr></thead>
                <tbody>
                    <tr>
                        <td><i class='bx bx-tv' style="color:var(--primary);font-size:1.1rem;vertical-align:middle;margin-right:8px;"></i> Sewa PlayStation (Billing)</td>
                        <td><?= $count_bill ?> transaksi</td>
                        <td style="text-align:right;font-weight:700;font-family:'JetBrains Mono',monospace;color:#fff">Rp <?= number_format($total_bill) ?></td>
                    </tr>
                    <tr>
                        <td><i class='bx bx-food-menu' style="color:#f59e0b;font-size:1.1rem;vertical-align:middle;margin-right:8px;"></i> Penjualan Snacks & Drinks</td>
                        <td><?= $count_fnb ?> item</td>
                        <td style="text-align:right;font-weight:700;font-family:'JetBrains Mono',monospace;color:#fff">Rp <?= number_format($total_fnb) ?></td>
                    </tr>
                    <tr>
                        <td><i class='bx bx-wallet' style="color:#a855f7;font-size:1.1rem;vertical-align:middle;margin-right:8px;"></i> Deposit Saldo Member (Top Up)</td>
                        <td><?= $count_topup ?> transaksi</td>
                        <td style="text-align:right;font-weight:700;font-family:'JetBrains Mono',monospace;color:#fff">Rp <?= number_format($total_topup) ?></td>
                    </tr>
                </tbody>
                <tfoot><tr>
                    <th colspan="2"><i class='bx bx-check-shield'></i> GRAND TOTAL — WAJIB ADA DI LACI</th>
                    <th style="text-align:right;font-size:1.2rem;color:var(--primary);font-family:'JetBrains Mono',monospace">Rp <?= number_format($grand_total) ?></th>
                </tr></tfoot>
            </table>
        </div>
        <div class="warn-box">
            <i class='bx bx-error-circle'></i>
            <p><strong>Perhatian Operator:</strong> Hitung fisik uang di laci dan cocokkan dengan angka di atas. Selisih minus adalah tanggung jawab operator shift yang bertugas. Semua transaksi bypass saldo wajib dikonfirmasi admin.</p>
        </div>
    </div>

    <!-- ─── TAB 2: SEMUA TRANSAKSI ─── -->
    <div id="trx" class="tab-pane">
        <div class="sec-title"><i class='bx bx-receipt'></i> Detail Semua Transaksi Selesai</div>
        <?php if ($trx_detail_list->num_rows >= 500): ?>
        <div class="limit-notice"><i class='bx bx-info-circle'></i> Menampilkan 500 transaksi terbaru. Filter tanggal untuk mempersempit data.</div>
        <?php endif; ?>
        <div class="scroll-wrap">
            <table class="data-table">
                <thead><tr>
                    <th>#Trx</th><th>TV</th><th>Customer</th><th>Tipe</th>
                    <th>Durasi</th><th>Billing</th><th>FnB</th><th>Grand Total</th>
                    <th>Stik</th><th>Waktu Selesai</th>
                </tr></thead>
                <tbody>
                <?php
                if ($trx_detail_list->num_rows > 0):
                    while ($td = $trx_detail_list->fetch_assoc()):
                        $is_short = ($td['durasi_menit'] < 2);
                        $gt = $td['total_bayar'] + $td['fnb_total'];
                ?>
                <tr class="<?= $is_short ? 'redflag-row' : '' ?>">
                    <td>
                        <span style="font-family:'JetBrains Mono';color:var(--primary);font-weight:700">#<?= $td['id'] ?></span>
                        <?php if ($is_short): ?><i class='bx bxs-error redflag-icon' title="Durasi sangat pendek!"></i><?php endif; ?>
                    </td>
                    <td><span class="hl-tv"><?= htmlspecialchars($td['nama_tv']) ?></span></td>
                    <td><?= $td['nama_member'] ? htmlspecialchars($td['nama_member']) : '<span style="color:#475569">Tamu</span>' ?></td>
                    <td>
                        <?php if ($td['jenis_paket'] == 'fixed'): ?>
                            <span class="badge b-start">PAKET</span>
                        <?php else: ?>
                            <span class="badge b-resume">OPEN</span>
                        <?php endif; ?>
                    </td>
                    <td class="anom-dur" style="color:<?= $is_short ? 'var(--danger)' : '#fbbf24' ?>;font-weight:700"><?= $td['durasi_menit'] ?>m</td>
                    <td style="font-family:'JetBrains Mono';color:var(--success);font-weight:700">Rp <?= number_format($td['total_bayar']) ?></td>
                    <td style="font-family:'JetBrains Mono';color:<?= $td['fnb_total'] > 0 ? '#f59e0b' : '#334155' ?>;font-weight:700">
                        <?= $td['fnb_total'] > 0 ? 'Rp '.number_format($td['fnb_total']) : '-' ?>
                    </td>
                    <td style="font-family:'JetBrains Mono';color:#fff;font-weight:800">Rp <?= number_format($gt) ?></td>
                    <td style="color:#64748b;font-size:0.78rem"><?= htmlspecialchars($td['stik_info'] ?? '-') ?></td>
                    <td style="font-size:0.78rem;color:#64748b;white-space:nowrap">
                        <?= date('H:i:s', strtotime($td['end_time'])) ?><br>
                        <small><?= date('d M Y', strtotime($td['end_time'])) ?></small>
                    </td>
                </tr>
                <?php endwhile; else: ?>
                <tr><td colspan="10"><div class="empty-state"><i class='bx bx-receipt'></i><div>Tidak ada transaksi</div></div></td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- ─── TAB 3: AUDIT LOG ─── -->
    <div id="audit" class="tab-pane">
        <div class="sec-title"><i class='bx bx-history'></i> Audit Trail Lengkap</div>

        <div class="log-chips">
            <div class="chip"><i class='bx bx-list-ul'></i> Total <span class="chip-num"><?= $log_stats['cnt_total'] ?? 0 ?></span></div>
            <div class="chip"><i class='bx bx-play' style="color:var(--success)"></i> Start <span class="chip-num"><?= $log_stats['cnt_start'] ?? 0 ?></span></div>
            <div class="chip"><i class='bx bx-stop' style="color:var(--danger)"></i> Stop <span class="chip-num"><?= $log_stats['cnt_stop'] ?? 0 ?></span></div>
            <div class="chip"><i class='bx bx-food-menu' style="color:#f59e0b"></i> FnB <span class="chip-num"><?= $log_stats['cnt_fnb'] ?? 0 ?></span></div>
            <div class="chip"><i class='bx bx-time-five' style="color:#3b82f6"></i> +Waktu <span class="chip-num"><?= $log_stats['cnt_addtime'] ?? 0 ?></span></div>
            <?php if (($log_stats['cnt_bypass'] ?? 0) > 0): ?>
            <div class="chip" style="border-color:rgba(239,68,68,0.5);color:var(--danger)">
                <i class='bx bxs-error-alt'></i> BYPASS
                <span class="chip-num red"><?= $log_stats['cnt_bypass'] ?></span>
            </div>
            <?php endif; ?>
        </div>

        <?php if (($log_stats['cnt_total'] ?? 0) > 300): ?>
        <div class="limit-notice"><i class='bx bx-info-circle'></i> Menampilkan 300 log terbaru dari total <?= $log_stats['cnt_total'] ?>. Filter operator atau jenis aktivitas untuk mempersempit.</div>
        <?php endif; ?>

        <div class="scroll-wrap">
            <table class="data-table">
                <thead><tr>
                    <th style="width:110px">Waktu</th>
                    <th style="width:110px">Operator</th>
                    <th style="width:140px">Aksi</th>
                    <th>Detail Lengkap</th>
                </tr></thead>
                <tbody>
                <?php if ($logs->num_rows > 0):
                    while ($l = $logs->fetch_assoc()):
                        $au = strtoupper($l['action']);
                        $ad = $l['details'];
                        $bc = 'b-default'; $bi = 'bx-circle';
                        if      (strpos($au,'START_OPEN') !== false)                              { $bc='b-resume';  $bi='bx-timer'; }
                        elseif  (strpos($au,'START')      !== false)                              { $bc='b-start';   $bi='bx-play'; }
                        elseif  (strpos($au,'STOP')       !== false)                              { $bc='b-stop';    $bi='bx-stop'; }
                        elseif  (strpos($au,'PAUSE')      !== false)                              { $bc='b-pause';   $bi='bx-pause'; }
                        elseif  (strpos($au,'RESUME')     !== false)                              { $bc='b-resume';  $bi='bx-play'; }
                        elseif  (strpos($au,'ADD_TIME')   !== false)                              { $bc='b-addtime'; $bi='bx-time-five'; }
                        elseif  (strpos($au,'MOVE')       !== false)                              { $bc='b-move';    $bi='bx-transfer'; }
                        elseif  (strpos($au,'TOPUP')      !== false)                              { $bc='b-topup';   $bi='bx-wallet'; }
                        elseif  (strpos($au,'ORDER_FNB')  !== false || strpos($au,'FNB') !== false){ $bc='b-fnb';    $bi='bx-food-menu'; }
                        elseif  (strpos($au,'REMOTE')     !== false || strpos($au,'ADB') !== false){ $bc='b-remote'; $bi='bx-joystick'; }
                        elseif  (strpos($au,'LOGIN')      !== false)                              { $bc='b-login';   $bi='bx-log-in'; }
                        elseif  (strpos($au,'LOGOUT')     !== false)                              { $bc='b-logout';  $bi='bx-log-out'; }
                        $is_bypass = (strpos($ad, 'BYPASS') !== false || strpos($ad, 'bypass') !== false);
                        $d = htmlspecialchars($ad);
                        $d = preg_replace('/(TV\s*\d+|Unit\s*\d+)/i',         '<span class="hl-tv">$1</span>',   $d);
                        $d = preg_replace('/(Rp\s*[\d\.,]+)/i',               '<span class="hl-rp">$1</span>',   $d);
                        $d = preg_replace('/(\d+j\s*\d+m\s*\d+d|\d+m\s*\d+d)/i','<span class="hl-dur">$1</span>',$d);
                        $d = preg_replace('/Trx\s*#(\d+)/i',                  'Trx <span style="color:#a78bfa;font-weight:700">#$1</span>', $d);
                        $d = str_replace('[BYPASS_SALDO]', '<span class="hl-bypass">⚠ BYPASS SALDO</span>', $d);
                        $d = str_replace('[CASH]',         '<span class="hl-cash">💵 CASH</span>',          $d);
                        $d = preg_replace('/Bayar:\s*saldo/i',   'Bayar: <span class="hl-saldo">SALDO</span>',  $d);
                        $d = preg_replace('/Bayar:\s*cash/i',    'Bayar: <span class="hl-cash">CASH</span>',   $d);
                        $d = preg_replace('/Bayar:\s*partial/i', 'Bayar: <span style="color:#f59e0b;font-weight:700">PARTIAL</span>', $d);
                        $d = str_replace(' | ', ' <span class="hl-sep">│</span> ', $d);
                ?>
                <tr class="<?= $is_bypass ? 'redflag-row' : '' ?>">
                    <td style="white-space:nowrap">
                        <div style="font-weight:700;color:#fff;font-family:'JetBrains Mono';font-size:0.82rem"><?= date('H:i:s', strtotime($l['created_at'])) ?></div>
                        <small style="color:#475569"><?= date('d/m/Y', strtotime($l['created_at'])) ?></small>
                    </td>
                    <td>
                        <div style="display:flex;align-items:center;gap:7px">
                            <div style="width:28px;height:28px;background:rgba(6,182,212,0.1);border-radius:7px;display:flex;align-items:center;justify-content:center;flex-shrink:0">
                                <i class='bx bx-user' style="color:var(--primary);font-size:0.9rem"></i>
                            </div>
                            <b style="color:#fff;font-size:0.82rem"><?= htmlspecialchars($l['username']) ?></b>
                        </div>
                    </td>
                    <td>
                        <span class="badge <?= $bc ?>"><i class='bx <?= $bi ?>'></i><?= htmlspecialchars($l['action']) ?></span>
                        <?php if ($is_bypass): ?><br><span class="badge b-bypass" style="margin-top:4px">⚠ BYPASS</span><?php endif; ?>
                    </td>
                    <td style="font-size:0.82rem;line-height:1.7"><?= $d ?></td>
                </tr>
                <?php endwhile; else: ?>
                <tr><td colspan="4"><div class="empty-state"><i class='bx bx-search-alt'></i><div>Tidak ada aktivitas</div></div></td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- ─── TAB 4: PER OPERATOR ─── -->
    <div id="operator" class="tab-pane">
        <div class="sec-title"><i class='bx bx-user-check'></i> Ringkasan Aktivitas Per Operator</div>
        <div class="op-cards">
        <?php
        while ($op = $op_stats_list->fetch_assoc()):
            $has_bypass = ($op['cnt_bypass'] > 0);
            $jam_kerja  = '';
            if ($op['first_action'] && $op['last_action']) {
                $menit    = round((strtotime($op['last_action']) - strtotime($op['first_action'])) / 60);
                $jam_kerja = floor($menit/60).'j '.($menit%60).'m';
            }
        ?>
        <div class="op-card <?= $has_bypass ? 'has-bypass' : '' ?>">
            <div class="op-name">
                <div style="width:36px;height:36px;background:rgba(6,182,212,0.12);border-radius:9px;display:flex;align-items:center;justify-content:center">
                    <i class='bx bx-user' style="color:var(--primary)"></i>
                </div>
                <?= htmlspecialchars($op['username']) ?>
                <?php if ($has_bypass): ?><span class="badge b-bypass">⚠ BYPASS</span><?php endif; ?>
            </div>
            <div class="op-stat-row"><span>Total Aksi</span><span class="op-stat-val cyan"><?= $op['total_log'] ?></span></div>
            <div class="op-stat-row"><span>Start Session</span><span class="op-stat-val"><?= $op['cnt_start'] ?></span></div>
            <div class="op-stat-row"><span>Stop Session</span><span class="op-stat-val"><?= $op['cnt_stop'] ?></span></div>
            <div class="op-stat-row"><span>Bypass Saldo</span><span class="op-stat-val <?= $has_bypass ? 'red' : '' ?>"><?= $op['cnt_bypass'] ?> kali</span></div>
            <div class="op-stat-row"><span>Jam Aktif</span><span class="op-stat-val"><?= $jam_kerja ?: '-' ?></span></div>
            <div class="op-stat-row"><span>Mulai Kerja</span><span class="op-stat-val" style="font-size:0.72rem"><?= $op['first_action'] ? date('H:i', strtotime($op['first_action'])) : '-' ?></span></div>
            <div class="op-stat-row"><span>Aksi Terakhir</span><span class="op-stat-val" style="font-size:0.72rem"><?= $op['last_action'] ? date('H:i', strtotime($op['last_action'])) : '-' ?></span></div>
        </div>
        <?php endwhile; ?>
        </div>

        <div class="sec-title" style="margin-top:8px"><i class='bx bx-wallet'></i> Top Up yang Dilakukan</div>
        <div class="scroll-wrap">
            <table class="data-table">
                <thead><tr><th>Waktu</th><th>Member</th><th>Jumlah Top Up</th><th>Saldo Sekarang</th></tr></thead>
                <tbody>
                <?php
                $stmt_topup_detail = $conn->prepare("
                    SELECT mt.created_at, mt.amount, m.nama_member, m.saldo as saldo_now
                    FROM member_topups mt
                    JOIN members m ON mt.member_id = m.id
                    WHERE DATE(mt.created_at) BETWEEN ? AND ?
                    ORDER BY mt.created_at DESC
                    LIMIT 200
                ");
                $stmt_topup_detail->bind_param("ss", $start_date, $end_date);
                $stmt_topup_detail->execute();
                $topup_rows = $stmt_topup_detail->get_result();
                if ($topup_rows->num_rows > 0):
                    while ($tr = $topup_rows->fetch_assoc()):
                ?>
                <tr>
                    <td style="font-family:'JetBrains Mono';font-size:0.8rem;color:#64748b">
                        <?= date('H:i:s', strtotime($tr['created_at'])) ?><br>
                        <small><?= date('d/m/Y', strtotime($tr['created_at'])) ?></small>
                    </td>
                    <td><b style="color:#a78bfa"><?= htmlspecialchars($tr['nama_member']) ?></b></td>
                    <td style="color:var(--success);font-family:'JetBrains Mono';font-weight:700">+Rp <?= number_format($tr['amount']) ?></td>
                    <td style="color:#67e8f9;font-family:'JetBrains Mono'">Rp <?= number_format($tr['saldo_now']) ?></td>
                </tr>
                <?php endwhile; else: ?>
                <tr><td colspan="4" style="text-align:center;color:#334155;padding:24px">Tidak ada top-up pada periode ini</td></tr>
                <?php endif;
                $stmt_topup_detail->close(); ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- ─── TAB 5: RED FLAGS ─── -->
    <?php if ($anomali_list->num_rows > 0): ?>
    <div id="anomali" class="tab-pane">
        <div style="background:rgba(239,68,68,0.08);border:1px solid rgba(239,68,68,0.3);border-radius:14px;padding:16px 18px;margin-bottom:20px;display:flex;gap:12px;align-items:flex-start">
            <i class='bx bxs-error-alt' style="font-size:1.6rem;color:var(--danger);flex-shrink:0;margin-top:2px"></i>
            <div>
                <div style="font-weight:800;color:#f87171;font-size:0.95rem;margin-bottom:4px">⚠ Transaksi Mencurigakan Terdeteksi</div>
                <div style="color:#94a3b8;font-size:0.82rem;line-height:1.6">
                    Berikut adalah sesi yang berakhir kurang dari <b style="color:#fff">2 menit</b> setelah dimulai.
                    Ini bisa berarti operator membatalkan sesi tanpa alasan, atau terjadi manipulasi.
                    Konfirmasi langsung dengan operator yang bersangkutan.
                </div>
            </div>
        </div>
        <div class="scroll-wrap">
            <table class="data-table">
                <thead><tr>
                    <th>#Trx</th><th>TV</th><th>Customer</th><th>Tipe</th>
                    <th>Durasi</th><th>Billing</th><th>Waktu Mulai</th><th>Waktu Selesai</th>
                </tr></thead>
                <tbody>
                <?php
                $anomali_list->data_seek(0);
                while ($an = $anomali_list->fetch_assoc()):
                    $dur_s   = (int)$an['durasi_detik'];
                    $dur_str = floor($dur_s/60).'m '.($dur_s%60).'d';
                ?>
                <tr class="redflag-row">
                    <td><span style="font-family:'JetBrains Mono';color:var(--danger);font-weight:700">#<?= $an['id'] ?></span> <i class='bx bxs-error redflag-icon'></i></td>
                    <td><span class="hl-tv"><?= htmlspecialchars($an['nama_tv']) ?></span></td>
                    <td><?= $an['nama_member'] ? htmlspecialchars($an['nama_member']) : '<span style="color:#475569">Tamu</span>' ?></td>
                    <td><span class="badge <?= $an['jenis_paket']=='fixed' ? 'b-start' : 'b-resume' ?>"><?= strtoupper($an['jenis_paket']) ?></span></td>
                    <td><span style="color:var(--danger);font-weight:800;font-family:'JetBrains Mono'"><?= $dur_str ?></span></td>
                    <td style="font-family:'JetBrains Mono';color:var(--success)">Rp <?= number_format($an['total_bayar']) ?></td>
                    <td style="font-size:0.78rem;color:#64748b"><?= date('H:i:s', strtotime($an['start_time'])) ?></td>
                    <td style="font-size:0.78rem;color:#64748b"><?= $an['end_time'] ? date('H:i:s', strtotime($an['end_time'])) : '-' ?></td>
                </tr>
                <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

</div><!-- end tabs-wrapper -->

<script>
function openTab(evt, name) {
    document.querySelectorAll('.tab-pane').forEach(p => { p.style.display='none'; p.classList.remove('active'); });
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    const pane = document.getElementById(name);
    if (pane) { pane.style.display='block'; pane.classList.add('active'); }
    evt.currentTarget.classList.add('active');
}
</script>

<?php
$stmt_log->close();
ob_end_flush();
?>