<?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';

// --- 1. QUERY PENDAPATAN DETAIL ---
$stmt_bill = $conn->prepare("SELECT SUM(total_bayar) as total FROM transactions 
    WHERE DATE(end_time) BETWEEN ? AND ? AND status='completed'");
$stmt_bill->bind_param("ss", $start_date, $end_date);
$stmt_bill->execute();
$total_bill = $stmt_bill->get_result()->fetch_assoc()['total'] ?? 0;
$stmt_bill->close();

$stmt_fnb = $conn->prepare("SELECT SUM(total_harga) as total FROM orders_fnb 
    WHERE DATE(created_at) BETWEEN ? AND ?");
$stmt_fnb->bind_param("ss", $start_date, $end_date);
$stmt_fnb->execute();
$total_fnb = $stmt_fnb->get_result()->fetch_assoc()['total'] ?? 0;
$stmt_fnb->close();

$stmt_topup = $conn->prepare("SELECT SUM(amount) as total FROM member_topups 
    WHERE DATE(created_at) BETWEEN ? AND ?");
$stmt_topup->bind_param("ss", $start_date, $end_date);
$stmt_topup->execute();
$total_topup = $stmt_topup->get_result()->fetch_assoc()['total'] ?? 0;
$stmt_topup->close();

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

// --- 2. QUERY LOG AKTIVITAS (dengan filter action) ---
$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";
}

$stmt_log = $conn->prepare("SELECT * FROM activity_logs WHERE $log_where ORDER BY created_at DESC");
$stmt_log->bind_param($log_types, ...$log_params);
$stmt_log->execute();
$logs = $stmt_log->get_result();

// --- Count untuk tabel detail ---
$stmt_count_bill = $conn->prepare("SELECT COUNT(*) as cnt FROM transactions WHERE DATE(end_time) BETWEEN ? AND ? AND status='completed'");
$stmt_count_bill->bind_param("ss", $start_date, $end_date);
$stmt_count_bill->execute();
$count_bill = $stmt_count_bill->get_result()->fetch_assoc()['cnt'];
$stmt_count_bill->close();

$stmt_count_fnb = $conn->prepare("SELECT COUNT(*) as cnt FROM orders_fnb WHERE DATE(created_at) BETWEEN ? AND ?");
$stmt_count_fnb->bind_param("ss", $start_date, $end_date);
$stmt_count_fnb->execute();
$count_fnb = $stmt_count_fnb->get_result()->fetch_assoc()['cnt'];
$stmt_count_fnb->close();

$stmt_count_topup = $conn->prepare("SELECT COUNT(*) as cnt FROM member_topups WHERE DATE(created_at) BETWEEN ? AND ?");
$stmt_count_topup->bind_param("ss", $start_date, $end_date);
$stmt_count_topup->execute();
$count_topup = $stmt_count_topup->get_result()->fetch_assoc()['cnt'];
$stmt_count_topup->close();

// --- Count log per kategori (untuk statistik) ---
$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,
    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();
?>

<link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>

<style>
    @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&family=Chakra+Petch:wght@700&display=swap');
    @import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@500;700&display=swap');

    :root {
        --glass: rgba(30, 41, 59, 0.7);
        --border: rgba(255, 255, 255, 0.08);
        --primary: #06b6d4;
        --primary-glow: rgba(6, 182, 212, 0.3);
        --accent-red: #ef4444;
        --accent-green: #10b981;
    }

    body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: #0f172a; }

    .settings-header { margin-bottom: 30px; padding-left: 10px; }
    .settings-header h2 { font-family: 'Chakra Petch', sans-serif; font-size: 1.8rem; color: #fff; display: flex; align-items: center; gap: 15px; text-transform: uppercase; letter-spacing: 1px; }
    .settings-header h2 i { color: var(--primary); filter: drop-shadow(0 0 8px var(--primary-glow)); }

    /* Filter Bar */
    .filter-card { background: var(--glass); backdrop-filter: blur(10px); border: 1px solid var(--border); padding: 20px; border-radius: 16px; margin-bottom: 25px; display: flex; flex-wrap: wrap; gap: 15px; align-items: flex-end; }
    .filter-card label { display: block; font-size: 0.75rem; color: #94a3b8; margin-bottom: 6px; font-weight: 600; }
    .filter-card input, .filter-card select { background: rgba(0,0,0,0.3); border: 1px solid var(--border); padding: 12px 15px; border-radius: 10px; color: #fff; font-size: 0.9rem; outline: none; transition: 0.3s; }
    .filter-card input:focus, .filter-card select:focus { border-color: var(--primary); }
    .filter-card button { background: linear-gradient(135deg, var(--primary), #0891b2); border: none; padding: 12px 25px; border-radius: 10px; color: #000; font-weight: 700; cursor: pointer; transition: 0.3s; }
    .filter-card button:hover { transform: translateY(-2px); box-shadow: 0 5px 20px rgba(6, 182, 212, 0.3); }

    /* Summary Grid */
    .summary-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 20px; margin-bottom: 30px; }
    .sum-card { background: var(--glass); backdrop-filter: blur(10px); border: 1px solid var(--border); padding: 25px; border-radius: 20px; position: relative; overflow: hidden; transition: 0.3s; }
    .sum-card:hover { transform: translateY(-5px); border-color: var(--primary); }
    .sum-card::after { content: ''; position: absolute; bottom: 0; left: 0; width: 100%; height: 4px; background: var(--primary); opacity: 0.5; }
    .sum-card.highlight { background: linear-gradient(135deg, rgba(6,182,212,0.15), transparent); border-color: rgba(6, 182, 212, 0.3); }
    .sum-card.highlight::after { opacity: 1; }
    .sum-icon { width: 50px; height: 50px; background: rgba(6, 182, 212, 0.1); border-radius: 12px; display: flex; align-items: center; justify-content: center; margin-bottom: 15px; font-size: 1.5rem; color: var(--primary); }
    .sum-label { color: #94a3b8; font-size: 0.8rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; }
    .sum-value { color: #fff; font-size: 1.8rem; font-weight: 800; margin-top: 8px; font-family: 'JetBrains Mono', monospace; }
    .sum-card.highlight .sum-value { color: var(--primary); }

    /* Tabs */
    .tab-wrapper { background: var(--glass); backdrop-filter: blur(10px); border: 1px solid var(--border); border-radius: 24px; overflow: hidden; }
    .tab-header { display: flex; background: rgba(0,0,0,0.2); padding: 10px; gap: 10px; }
    .tab-btn { padding: 14px 25px; border-radius: 12px; border: none; background: none; color: #94a3b8; cursor: pointer; font-weight: 700; transition: 0.3s; display: flex; align-items: center; gap: 8px; }
    .tab-btn:hover { background: rgba(255,255,255,0.05); color: #fff; }
    .tab-btn.active { background: var(--primary); color: #000; }
    .tab-content { padding: 25px; display: none; }
    .tab-content.active { display: block; }

    /* Table */
    .log-table { width: 100%; border-collapse: collapse; }
    .log-table th { text-align: left; padding: 15px; color: #64748b; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.5px; border-bottom: 1px solid var(--border); background: rgba(0,0,0,0.2); }
    .log-table td { padding: 15px; border-bottom: 1px solid rgba(255,255,255,0.03); color: #cbd5e1; font-size: 0.9rem; }
    .log-table tr:hover { background: rgba(6, 182, 212, 0.05); }
    .log-table tfoot th { background: rgba(6, 182, 212, 0.1); color: #fff; }

    /* Action Badges - EXTENDED */
    .badge-action { padding: 5px 10px; border-radius: 8px; font-size: 0.7rem; font-weight: 800; text-transform: uppercase; letter-spacing: 0.5px; display: inline-flex; align-items: center; gap: 5px; }
    .bg-start    { background: rgba(16, 185, 129, 0.2); color: #10b981; }
    .bg-stop     { background: rgba(239, 68, 68, 0.2); color: #ef4444; }
    .bg-move     { background: rgba(59, 130, 246, 0.2); color: #3b82f6; }
    .bg-topup    { background: rgba(168, 85, 247, 0.2); color: #a855f7; }
    .bg-fnb      { background: rgba(245, 158, 11, 0.2); color: #f59e0b; }
    .bg-pause    { background: rgba(251, 191, 36, 0.2); color: #fbbf24; }
    .bg-resume   { background: rgba(34, 211, 238, 0.2); color: #22d3ee; }
    .bg-remote   { background: rgba(139, 92, 246, 0.2); color: #8b5cf6; }
    .bg-login    { background: rgba(16, 185, 129, 0.2); color: #10b981; }
    .bg-logout   { background: rgba(100, 116, 139, 0.2); color: #94a3b8; }
    .bg-settings { background: rgba(6, 182, 212, 0.2); color: #06b6d4; }
    .bg-addtime  { background: rgba(59, 130, 246, 0.2); color: #3b82f6; }
    .bg-page     { background: rgba(71, 85, 105, 0.2); color: #64748b; }
    .bg-default  { background: rgba(100, 116, 139, 0.15); color: #94a3b8; }

    /* Log Stats Mini Cards */
    .log-stats { display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 20px; }
    .log-stat-chip { background: rgba(0,0,0,0.3); border: 1px solid var(--border); padding: 8px 16px; border-radius: 10px; font-size: 0.8rem; font-weight: 700; display: flex; align-items: center; gap: 8px; color: #94a3b8; cursor: pointer; transition: 0.3s; }
    .log-stat-chip:hover { border-color: var(--primary); color: #fff; }
    .log-stat-chip.active { border-color: var(--primary); background: rgba(6,182,212,0.1); color: var(--primary); }
    .log-stat-num { background: rgba(6,182,212,0.2); color: var(--primary); padding: 2px 8px; border-radius: 6px; font-family: 'JetBrains Mono', monospace; font-size: 0.75rem; }

    .warning-box { margin-top: 30px; padding: 20px; background: rgba(239,68,68,0.1); border: 1px solid rgba(239,68,68,0.2); border-radius: 16px; color: #f87171; font-size: 0.85rem; display: flex; align-items: flex-start; gap: 12px; }
    .warning-box i { font-size: 1.5rem; }

    .empty-state { text-align: center; padding: 60px 20px; color: #64748b; }
    .empty-state i { font-size: 4rem; margin-bottom: 15px; opacity: 0.3; }

    /* Detail expand */
    .log-detail { font-size: 0.85rem; line-height: 1.6; color: #94a3b8; }
    .log-detail-highlight { color: #fff; font-weight: 600; }
    .log-detail-money { color: var(--accent-green); font-family: 'JetBrains Mono', monospace; font-weight: 700; }
    .log-detail-tv { color: var(--primary); font-weight: 700; }

    @media (max-width: 768px) { 
        .filter-card { flex-direction: column; align-items: stretch; }
        .filter-card > div { width: 100%; }
        .sum-value { font-size: 1.4rem; }
        .tab-header { flex-wrap: wrap; }
    }
</style>

<!-- FILTER SECTION -->
<form method="GET" class="filter-card">
    <div style="flex: 1; min-width: 150px;">
        <label>Dari Tanggal</label>
        <input type="date" name="start_date" value="<?= htmlspecialchars($start_date) ?>" style="width:100%">
    </div>
    <div style="flex: 1; min-width: 150px;">
        <label>Sampai Tanggal</label>
        <input type="date" name="end_date" value="<?= htmlspecialchars($end_date) ?>" style="width:100%">
    </div>
    <?php if($_SESSION['role'] == 'admin'): ?>
    <div style="flex: 1; min-width: 150px;">
        <label>Operator</label>
        <select name="user_id" style="width:100%">
            <option value="all">Semua Operator</option>
            <?php 
            $us = mysqli_query($conn, "SELECT id, username FROM users ORDER BY username");
            while($u = mysqli_fetch_assoc($us)) {
                $selected = ($user_filter == $u['id']) ? 'selected' : '';
                echo "<option value='{$u['id']}' {$selected}>{$u['username']}</option>";
            }
            ?>
        </select>
    </div>
    <?php endif; ?>
    <div style="flex: 1; min-width: 150px;">
        <label>Jenis Aktivitas</label>
        <select name="action_type" style="width:100%">
            <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="REMOTE" <?= $action_filter=='REMOTE'?'selected':'' ?>>🎮 Remote Control</option>
            <option value="ADB" <?= $action_filter=='ADB'?'selected':'' ?>>🔗 ADB Connect</option>
            <option value="LOGIN" <?= $action_filter=='LOGIN'?'selected':'' ?>>🔑 Login</option>
            <option value="LOGOUT" <?= $action_filter=='LOGOUT'?'selected':'' ?>>🚪 Logout</option>
            <option value="UPDATE" <?= $action_filter=='UPDATE'?'selected':'' ?>>⚙ Settings</option>
            <option value="PAGE" <?= $action_filter=='PAGE'?'selected':'' ?>>📄 Buka Halaman</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"><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>
    <div class="sum-card">
        <div class="sum-icon"><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>
    <div class="sum-card">
        <div class="sum-icon"><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>
    <div class="sum-card highlight">
        <div class="sum-icon" style="background:rgba(6,182,212,0.2);"><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>
</div>

<!-- TABS SYSTEM -->
<div class="tab-wrapper">
    <div class="tab-header">
        <button class="tab-btn active" onclick="openTab(event, 'income')">
            <i class='bx bx-money'></i> Detail Pendapatan
        </button>
        <button class="tab-btn" onclick="openTab(event, 'audit')">
            <i class='bx bx-fingerprint'></i> Log Aktivitas
            <span style="background:rgba(0,0,0,0.3); padding:2px 8px; border-radius:6px; font-size:0.7rem;"><?= $log_stats['cnt_total'] ?? 0 ?></span>
        </button>
    </div>

    <!-- TAB 1: DETAIL PENDAPATAN -->
    <div id="income" class="tab-content active">
        <h3 style="margin-bottom: 20px; display:flex; align-items:center; gap:10px;">
            <i class='bx bx-bar-chart-alt-2' style="color:var(--primary);"></i>
            Breakdown Keuangan
        </h3>
        <div style="overflow-x: auto;">
            <table class="log-table">
                <thead>
                    <tr>
                        <th>Kategori</th>
                        <th>Jumlah Transaksi</th>
                        <th style="text-align:right;">Subtotal</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><div style="display:flex; align-items:center; gap:10px;"><i class='bx bx-tv' style="color:var(--primary); font-size:1.2rem;"></i> Sewa PlayStation (Billing)</div></td>
                        <td><?= $count_bill ?> transaksi</td>
                        <td style="text-align:right; font-weight:700; font-family:'JetBrains Mono',monospace;">Rp <?= number_format($total_bill) ?></td>
                    </tr>
                    <tr>
                        <td><div style="display:flex; align-items:center; gap:10px;"><i class='bx bx-food-menu' style="color:#f59e0b; font-size:1.2rem;"></i> Penjualan Snacks & Drinks</div></td>
                        <td><?= $count_fnb ?> item</td>
                        <td style="text-align:right; font-weight:700; font-family:'JetBrains Mono',monospace;">Rp <?= number_format($total_fnb) ?></td>
                    </tr>
                    <tr>
                        <td><div style="display:flex; align-items:center; gap:10px;"><i class='bx bx-wallet' style="color:#a855f7; font-size:1.2rem;"></i> Deposit Saldo Member (Top Up)</div></td>
                        <td><?= $count_topup ?> transaksi</td>
                        <td style="text-align:right; font-weight:700; font-family:'JetBrains Mono',monospace;">Rp <?= number_format($total_topup) ?></td>
                    </tr>
                </tbody>
                <tfoot>
                    <tr>
                        <th colspan="2" style="font-size: 1rem;"><i class='bx bx-check-shield'></i> GRAND TOTAL (WAJIB ADA DI LACI)</th>
                        <th style="text-align:right; font-size: 1.3rem; color:var(--primary); font-family:'JetBrains Mono',monospace;">Rp <?= number_format($grand_total) ?></th>
                    </tr>
                </tfoot>
            </table>
        </div>
        <div class="warning-box">
            <i class='bx bx-error-circle'></i>
            <div><strong>Perhatian Operator:</strong><br>Pastikan Anda menghitung fisik uang di laci. Selisih minus menjadi tanggung jawab operator yang bertugas.</div>
        </div>
    </div>

    <!-- TAB 2: AUDIT LOG (ENHANCED) -->
    <div id="audit" class="tab-content">
        <h3 style="margin-bottom: 15px; display:flex; align-items:center; gap:10px;">
            <i class='bx bx-history' style="color:var(--primary);"></i>
            Audit Trail Operator
        </h3>

        <!-- Log Stats Chips -->
        <div class="log-stats">
            <div class="log-stat-chip">
                <i class='bx bx-list-ul'></i> Total <span class="log-stat-num"><?= $log_stats['cnt_total'] ?? 0 ?></span>
            </div>
            <div class="log-stat-chip">
                <i class='bx bx-play' style="color:#10b981;"></i> Start <span class="log-stat-num"><?= $log_stats['cnt_start'] ?? 0 ?></span>
            </div>
            <div class="log-stat-chip">
                <i class='bx bx-stop' style="color:#ef4444;"></i> Stop <span class="log-stat-num"><?= $log_stats['cnt_stop'] ?? 0 ?></span>
            </div>
            <div class="log-stat-chip">
                <i class='bx bx-food-menu' style="color:#f59e0b;"></i> FnB <span class="log-stat-num"><?= $log_stats['cnt_fnb'] ?? 0 ?></span>
            </div>
            <div class="log-stat-chip">
                <i class='bx bx-time-five' style="color:#3b82f6;"></i> +Waktu <span class="log-stat-num"><?= $log_stats['cnt_addtime'] ?? 0 ?></span>
            </div>
            <div class="log-stat-chip">
                <i class='bx bx-joystick' style="color:#8b5cf6;"></i> Remote <span class="log-stat-num"><?= $log_stats['cnt_remote'] ?? 0 ?></span>
            </div>
            <div class="log-stat-chip">
                <i class='bx bx-log-in' style="color:#10b981;"></i> Login <span class="log-stat-num"><?= $log_stats['cnt_login'] ?? 0 ?></span>
            </div>
        </div>

        <div style="overflow-x: auto; max-height: 600px; overflow-y: auto;">
            <table class="log-table">
                <thead style="position: sticky; top: 0; z-index: 2;">
                    <tr>
                        <th style="width:130px;">Waktu</th>
                        <th style="width:120px;">Operator</th>
                        <th style="width:160px;">Aksi</th>
                        <th>Detail Aktivitas</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if($logs->num_rows > 0): ?>
                        <?php while($l = $logs->fetch_assoc()): 
                            $action_upper = strtoupper($l['action']);
                            
                            // Determine badge class and icon
                            $bg_class = 'bg-default';
                            $badge_icon = 'bx-circle';
                            
                            if (strpos($action_upper, 'START_OPEN') !== false) {
                                $bg_class = 'bg-start'; $badge_icon = 'bx-timer';
                            } elseif (strpos($action_upper, 'START') !== false) {
                                $bg_class = 'bg-start'; $badge_icon = 'bx-play';
                            } elseif (strpos($action_upper, 'STOP') !== false) {
                                $bg_class = 'bg-stop'; $badge_icon = 'bx-stop';
                            } elseif (strpos($action_upper, 'PAUSE') !== false) {
                                $bg_class = 'bg-pause'; $badge_icon = 'bx-pause';
                            } elseif (strpos($action_upper, 'RESUME') !== false) {
                                $bg_class = 'bg-resume'; $badge_icon = 'bx-play';
                            } elseif (strpos($action_upper, 'ADD_TIME') !== false) {
                                $bg_class = 'bg-addtime'; $badge_icon = 'bx-time-five';
                            } elseif (strpos($action_upper, 'MOVE') !== false) {
                                $bg_class = 'bg-move'; $badge_icon = 'bx-transfer';
                            } elseif (strpos($action_upper, 'TOPUP') !== false || strpos($action_upper, 'TOP_UP') !== false) {
                                $bg_class = 'bg-topup'; $badge_icon = 'bx-wallet';
                            } elseif (strpos($action_upper, 'FNB') !== false || strpos($action_upper, 'ORDER') !== false) {
                                $bg_class = 'bg-fnb'; $badge_icon = 'bx-food-menu';
                            } elseif (strpos($action_upper, 'REMOTE') !== false) {
                                $bg_class = 'bg-remote'; $badge_icon = 'bx-joystick';
                            } elseif (strpos($action_upper, 'ADB') !== false || strpos($action_upper, 'CONNECT') !== false) {
                                $bg_class = 'bg-remote'; $badge_icon = 'bx-link';
                            } elseif (strpos($action_upper, 'LOGIN') !== false) {
                                $bg_class = 'bg-login'; $badge_icon = 'bx-log-in';
                            } elseif (strpos($action_upper, 'LOGOUT') !== false) {
                                $bg_class = 'bg-logout'; $badge_icon = 'bx-log-out';
                            } elseif (strpos($action_upper, 'UPDATE') !== false || strpos($action_upper, 'SETTING') !== false) {
                                $bg_class = 'bg-settings'; $badge_icon = 'bx-cog';
                            } elseif (strpos($action_upper, 'PAGE') !== false || strpos($action_upper, 'VIEW') !== false) {
                                $bg_class = 'bg-page'; $badge_icon = 'bx-file';
                            }
                            
                            // Format detail with highlighting
                            $detail = htmlspecialchars($l['details']);
                            // Highlight TV names (TV 1, TV 2, etc)
                            $detail = preg_replace('/(TV\s*\d+|Unit\s*\d+)/i', '<span class="log-detail-tv">$1</span>', $detail);
                            // Highlight money amounts
                            $detail = preg_replace('/(Rp\s*[\d\.,]+)/i', '<span class="log-detail-money">$1</span>', $detail);
                            // Highlight pipe separators for readability
                            $detail = str_replace(' | ', ' <span style="color:#334155;">│</span> ', $detail);
                        ?>
                        <tr>
                            <td style="white-space:nowrap;">
                                <div style="font-weight:600; color:#fff; font-family:'JetBrains Mono',monospace; font-size:0.85rem;">
                                    <?= date('H:i:s', strtotime($l['created_at'])) ?>
                                </div>
                                <small style="color:#64748b;"><?= date('d M Y', strtotime($l['created_at'])) ?></small>
                            </td>
                            <td>
                                <div style="display:flex; align-items:center; gap:8px;">
                                    <div style="width:32px; height:32px; background:rgba(6,182,212,0.1); border-radius:8px; display:flex; align-items:center; justify-content:center;">
                                        <i class='bx bx-user' style="color:var(--primary);"></i>
                                    </div>
                                    <b style="color: #fff; font-size:0.85rem;"><?= htmlspecialchars($l['username']) ?></b>
                                </div>
                            </td>
                            <td>
                                <span class="badge-action <?= $bg_class ?>">
                                    <i class='bx <?= $badge_icon ?>'></i>
                                    <?= htmlspecialchars($l['action']) ?>
                                </span>
                            </td>
                            <td class="log-detail"><?= $detail ?></td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="4">
                                <div class="empty-state">
                                    <i class='bx bx-search-alt'></i>
                                    <div style="font-size:1.1rem; font-weight:600; margin-bottom:5px;">Tidak ada aktivitas tercatat</div>
                                    <div>Coba ubah filter tanggal, operator, atau jenis aksi</div>
                                </div>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
function openTab(evt, tabName) {
    document.querySelectorAll(".tab-content").forEach(tc => { tc.style.display = "none"; tc.classList.remove("active"); });
    document.querySelectorAll(".tab-btn").forEach(tb => { tb.classList.remove("active"); });
    document.getElementById(tabName).style.display = "block";
    document.getElementById(tabName).classList.add("active");
    evt.currentTarget.classList.add("active");
}
</script>

<?php 
$stmt_log->close();
echo "</div></body></html>";
ob_end_flush();
?>