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

// Ganti onlyAdmin() dengan ini:
if (($_SESSION['role'] ?? '') !== 'admin' && !has_access($conn, 'perm_view_history')) {
    header("Location: index.php?status=restricted");
    exit;
}

$page_title  = "Financial Report";
$active_page = "history";
include 'layout.php';

// ═══════════════════════════════════════════════════
// HANDLE DELETE ACTIONS
// ═══════════════════════════════════════════════════

if (isset($_GET['delete_trx']) && is_numeric($_GET['delete_trx'])) {
    $del_id = (int)$_GET['delete_trx'];
    // FIX: Gunakan prepared statement
    $s1 = $conn->prepare("DELETE FROM orders_fnb WHERE trx_id = ?");
    $s1->bind_param("i", $del_id); $s1->execute(); $s1->close();
    $s2 = $conn->prepare("DELETE FROM transactions WHERE id = ? AND status = 'completed'");
    $s2->bind_param("i", $del_id); $s2->execute(); $s2->close();
    write_log($conn, 'DELETE_TRX', "Hapus transaksi #$del_id beserta FnB terkait");
    header("Location: history.php?" . http_build_query(array_diff_key($_GET, ['delete_trx' => ''])));
    exit;
}

if (isset($_GET['delete_fnb']) && is_numeric($_GET['delete_fnb'])) {
    $del_id = (int)$_GET['delete_fnb'];
    // FIX: Gunakan prepared statement
    $s1 = $conn->prepare("DELETE FROM orders_fnb WHERE id = ?");
    $s1->bind_param("i", $del_id); $s1->execute(); $s1->close();
    $s2 = $conn->prepare("DELETE FROM snack_sales WHERE id = ?");
    $s2->bind_param("i", $del_id); $s2->execute(); $s2->close();
    write_log($conn, 'DELETE_FNB', "Hapus record FnB #$del_id");
    header("Location: history.php?" . http_build_query(array_diff_key($_GET, ['delete_fnb' => ''])));
    exit;
}

if (isset($_GET['delete_topup']) && is_numeric($_GET['delete_topup'])) {
    $del_id = (int)$_GET['delete_topup'];
    // FIX: Gunakan prepared statement untuk baca data topup
    $s_get = $conn->prepare("SELECT member_id, amount FROM member_topups WHERE id = ?");
    $s_get->bind_param("i", $del_id); $s_get->execute();
    $tu_row = $s_get->get_result()->fetch_assoc(); $s_get->close();
    if ($tu_row) {
        // FIX: Cegah saldo negatif — pastikan saldo tidak turun di bawah 0
        $s_upd = $conn->prepare("UPDATE members SET saldo = GREATEST(0, saldo - ?) WHERE id = ?");
        $s_upd->bind_param("ii", $tu_row['amount'], $tu_row['member_id']);
        $s_upd->execute(); $s_upd->close();
    }
    $s_del = $conn->prepare("DELETE FROM member_topups WHERE id = ?");
    $s_del->bind_param("i", $del_id); $s_del->execute(); $s_del->close();
    write_log($conn, 'DELETE_TOPUP', "Hapus topup #$del_id | Saldo dikembalikan");
    header("Location: history.php?" . http_build_query(array_diff_key($_GET, ['delete_topup' => ''])));
    exit;
}

if (isset($_POST['bulk_delete'])) {
    // FIX: Validasi & sanitasi input — cegah SQL injection
    $bd_start_raw = $_POST['bd_start'] ?? date('Y-m-d');
    $bd_end_raw   = $_POST['bd_end']   ?? date('Y-m-d');
    $bd_start = date('Y-m-d', strtotime($bd_start_raw)) ?: date('Y-m-d');
    $bd_end   = date('Y-m-d', strtotime($bd_end_raw))   ?: date('Y-m-d');
    // Pastikan urutan tanggal benar
    if ($bd_start > $bd_end) { $tmp = $bd_start; $bd_start = $bd_end; $bd_end = $tmp; }
    // Whitelist tipe — cegah nilai arbitrary
    $allowed_types = ['all', 'ps', 'fnb', 'topup'];
    $bd_type = in_array($_POST['bd_type'] ?? '', $allowed_types) ? $_POST['bd_type'] : 'all';
    $deleted_count = 0;

    if ($bd_type === 'all' || $bd_type === 'ps') {
        // FIX: Gunakan prepared statement dengan parameter tanggal
        $s_ids = $conn->prepare("SELECT id FROM transactions WHERE DATE(end_time) BETWEEN ? AND ? AND status='completed'");
        $s_ids->bind_param("ss", $bd_start, $bd_end); $s_ids->execute();
        $res_ids = $s_ids->get_result(); $s_ids->close();
        while ($r = $res_ids->fetch_assoc()) {
            $s_fnb = $conn->prepare("DELETE FROM orders_fnb WHERE trx_id = ?");
            $s_fnb->bind_param("i", $r['id']); $s_fnb->execute(); $s_fnb->close();
        }
        $s_del = $conn->prepare("DELETE FROM transactions WHERE DATE(end_time) BETWEEN ? AND ? AND status='completed'");
        $s_del->bind_param("ss", $bd_start, $bd_end); $s_del->execute();
        $deleted_count += $s_del->affected_rows; $s_del->close();
    }
    if ($bd_type === 'all' || $bd_type === 'fnb') {
        $s1 = $conn->prepare("DELETE FROM orders_fnb WHERE DATE(created_at) BETWEEN ? AND ?");
        $s1->bind_param("ss", $bd_start, $bd_end); $s1->execute();
        $deleted_count += $s1->affected_rows; $s1->close();
        $s2 = $conn->prepare("DELETE FROM snack_sales WHERE DATE(created_at) BETWEEN ? AND ?");
        $s2->bind_param("ss", $bd_start, $bd_end); $s2->execute();
        $deleted_count += $s2->affected_rows; $s2->close();
    }
    if ($bd_type === 'all' || $bd_type === 'topup') {
        $s3 = $conn->prepare("DELETE FROM member_topups WHERE DATE(created_at) BETWEEN ? AND ?");
        $s3->bind_param("ss", $bd_start, $bd_end); $s3->execute();
        $deleted_count += $s3->affected_rows; $s3->close();
    }

    write_log($conn, 'BULK_DELETE', "Hapus massal [$bd_type] dari $bd_start s/d $bd_end | $deleted_count records");
    // FIX: Gunakan urlencode untuk nilai yang aman di URL redirect
    header("Location: history.php?start_date=" . urlencode($bd_start) . "&end_date=" . urlencode($bd_end) . "&view_type=" . urlencode($bd_type) . "&deleted=$deleted_count");
    exit;
}

// ═══════════════════════════════════════════════════
// HANDLE TOP-UP POST (dari modal di halaman ini)
// ═══════════════════════════════════════════════════
if (isset($_POST['action']) && $_POST['action'] === 'manual_topup') {
    $tu_member_id = (int)($_POST['tu_member_id'] ?? 0);
    $tu_amount    = (int)($_POST['tu_amount']    ?? 0);
    $tu_note      = trim($_POST['tu_note'] ?? '');

    if ($tu_member_id > 0 && $tu_amount > 0) {
        // Cek apakah tabel member_topups ada kolom note
        $has_note_col = (mysqli_num_rows(mysqli_query($conn, "SHOW COLUMNS FROM member_topups LIKE 'note'")) > 0);

        if ($has_note_col) {
            $stmt = $conn->prepare("INSERT INTO member_topups (member_id, amount, note, created_at) VALUES (?, ?, ?, NOW())");
            $stmt->bind_param("iis", $tu_member_id, $tu_amount, $tu_note);
        } else {
            $stmt = $conn->prepare("INSERT INTO member_topups (member_id, amount, created_at) VALUES (?, ?, NOW())");
            $stmt->bind_param("ii", $tu_member_id, $tu_amount);
        }
        $stmt->execute();
        $stmt->close();

        // Update saldo member
        $stmt2 = $conn->prepare("UPDATE members SET saldo = saldo + ? WHERE id = ?");
        $stmt2->bind_param("ii", $tu_amount, $tu_member_id);
        $stmt2->execute();
        $stmt2->close();

        // Ambil nama member untuk log — FIX: Gunakan prepared statement
        $s_nm = $conn->prepare("SELECT nama_member, saldo FROM members WHERE id = ?");
        $s_nm->bind_param("i", $tu_member_id); $s_nm->execute();
        $nm_row = $s_nm->get_result()->fetch_assoc(); $s_nm->close();
        write_log($conn, 'MANUAL_TOPUP', "Member #{$tu_member_id} ({$nm_row['nama_member']}) +Rp ".number_format($tu_amount)." | Saldo baru: Rp ".number_format($nm_row['saldo']));

        header("Location: history.php?" . http_build_query(array_merge($_GET, ['topup_success' => 1, 'topup_nama' => $nm_row['nama_member'], 'topup_amount' => $tu_amount])));
        exit;
    }
}

$deleted_msg     = isset($_GET['deleted'])       ? (int)$_GET['deleted']                    : null;
$topup_success   = isset($_GET['topup_success']) ? true                                      : false;
$topup_nama      = isset($_GET['topup_nama'])    ? htmlspecialchars($_GET['topup_nama'])      : '';
$topup_amount    = isset($_GET['topup_amount'])  ? (int)$_GET['topup_amount']                : 0;

// --- KONFIGURASI TANGGAL & FILTER ---
$start_date = $_GET['start_date'] ?? date('Y-m-d');
$end_date   = $_GET['end_date']   ?? date('Y-m-d');
$view_type  = $_GET['view_type']  ?? 'all';

// --- CEK STRUKTUR DATABASE ---
$has_packages_table   = (mysqli_num_rows(mysqli_query($conn, "SHOW TABLES LIKE 'packages'")) > 0);
$has_topup_table      = (mysqli_num_rows(mysqli_query($conn, "SHOW TABLES LIKE 'member_topups'")) > 0);
$has_paket_column     = (mysqli_num_rows(mysqli_query($conn, "SHOW COLUMNS FROM transactions LIKE 'paket_id'")) > 0);
$has_member_column    = (mysqli_num_rows(mysqli_query($conn, "SHOW COLUMNS FROM transactions LIKE 'member_id'")) > 0);
$has_stik_column      = (mysqli_num_rows(mysqli_query($conn, "SHOW COLUMNS FROM transactions LIKE 'stik_info'")) > 0);
$has_payment_column   = (mysqli_num_rows(mysqli_query($conn, "SHOW COLUMNS FROM transactions LIKE 'payment_method'")) > 0);

// ═══════════════════════════════════════════════════
// [VOUCHER] CEK KOLOM DISKON & VOUCHER_ID
// ═══════════════════════════════════════════════════
$has_diskon_column   = (mysqli_num_rows(mysqli_query($conn, "SHOW COLUMNS FROM transactions LIKE 'diskon'")) > 0);
$has_voucher_column  = (mysqli_num_rows(mysqli_query($conn, "SHOW COLUMNS FROM transactions LIKE 'voucher_id'")) > 0);

// --- 1. QUERY BILLING ---
$select_fields = "t.*, tv.nama_tv";
$joins = "JOIN tvs tv ON t.tv_id = tv.id";
if ($has_packages_table && $has_paket_column) { $select_fields .= ", p.nama_paket"; $joins .= " LEFT JOIN packages p ON t.paket_id = p.id"; }
if ($has_member_column)  { $select_fields .= ", m.nama_member, m.saldo as member_saldo_now"; $joins .= " LEFT JOIN members m ON t.member_id = m.id"; }
else                     { $select_fields .= ", NULL as nama_member, NULL as member_saldo_now"; }
if ($has_stik_column)    { $select_fields .= ", t.stik_info"; }
else                     { $select_fields .= ", '-' as stik_info"; }
if ($has_payment_column) { $select_fields .= ", t.payment_method"; }
else                     { $select_fields .= ", NULL as payment_method"; }

// [VOUCHER] Tambahkan kolom diskon & voucher_id
if ($has_diskon_column)  { $select_fields .= ", t.diskon"; }
else                     { $select_fields .= ", 0 as diskon"; }
if ($has_voucher_column) { $select_fields .= ", t.voucher_id"; }
else                     { $select_fields .= ", NULL as voucher_id"; }

$q_trans = $conn->prepare("SELECT $select_fields FROM transactions t $joins WHERE DATE(t.end_time) BETWEEN ? AND ? AND t.status='completed' ORDER BY t.end_time DESC");
$q_trans->bind_param("ss", $start_date, $end_date);
$q_trans->execute();
$q_trans = $q_trans->get_result();

// [VOUCHER] Hitung total billing dengan memperhitungkan diskon
// total_bayar sudah menyimpan nilai bersih setelah diskon
$s_totbill = $conn->prepare("SELECT SUM(total_bayar) as total FROM transactions WHERE DATE(end_time) BETWEEN ? AND ? AND status='completed'");
$s_totbill->bind_param("ss", $start_date, $end_date); $s_totbill->execute();
$total_bill = (float)($s_totbill->get_result()->fetch_assoc()['total'] ?? 0); $s_totbill->close();

// [VOUCHER] Hitung breakdown metode bayar (dengan diskon)
if ($has_payment_column) {
    $s_cash = $conn->prepare(
        "SELECT SUM(total_bayar) as t FROM transactions 
         WHERE DATE(end_time) BETWEEN ? AND ? AND status='completed' 
         AND (LOWER(COALESCE(payment_method,'Cash')) NOT IN ('saldo','partial','member saldo','partial saldo+cash')
              AND LOWER(COALESCE(payment_method,'')) NOT LIKE '%transfer%'
              AND LOWER(COALESCE(payment_method,'')) NOT LIKE '%qris%'
              AND LOWER(COALESCE(payment_method,'')) NOT LIKE '%saldo%'
              AND LOWER(COALESCE(payment_method,'')) NOT LIKE '%pending%')");
    $s_cash->bind_param("ss", $start_date, $end_date); $s_cash->execute();
    $pay_cash = (float)($s_cash->get_result()->fetch_assoc()['t'] ?? 0); $s_cash->close();

    $s_saldo = $conn->prepare(
        "SELECT SUM(total_bayar) as t FROM transactions 
         WHERE DATE(end_time) BETWEEN ? AND ? AND status='completed' AND payment_method='saldo'");
    $s_saldo->bind_param("ss", $start_date, $end_date); $s_saldo->execute();
    $pay_saldo = (float)($s_saldo->get_result()->fetch_assoc()['t'] ?? 0); $s_saldo->close();

    $s_part = $conn->prepare(
        "SELECT SUM(total_bayar) as t FROM transactions 
         WHERE DATE(end_time) BETWEEN ? AND ? AND status='completed' AND payment_method='partial'");
    $s_part->bind_param("ss", $start_date, $end_date); $s_part->execute();
    $pay_partial = (float)($s_part->get_result()->fetch_assoc()['t'] ?? 0); $s_part->close();
} else {
    $pay_cash    = $total_bill;
    $pay_saldo   = 0;
    $pay_partial = 0;
}

// --- 2. QUERY F&B ---
$s_fnb = $conn->prepare("
    SELECT o.id, o.created_at, o.nama_barang, o.qty, o.total_harga as total, tv.nama_tv as sumber, 'order' as type
    FROM orders_fnb o JOIN tvs tv ON o.tv_id = tv.id WHERE DATE(o.created_at) BETWEEN ? AND ?
    UNION ALL
    SELECT s.id, s.created_at, sk.nama_barang, s.qty, s.total, 'KASIR' as sumber, 'direct' as type
    FROM snack_sales s JOIN snacks sk ON s.snack_id = sk.id WHERE DATE(s.created_at) BETWEEN ? AND ?
    ORDER BY created_at DESC");
$s_fnb->bind_param("ssss", $start_date, $end_date, $start_date, $end_date);
$s_fnb->execute();
$q_fnb = $s_fnb->get_result();

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

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

$total_fnb = $t_fnb1 + $t_fnb2;

// --- 3. QUERY TOP UP ---
$total_topup = 0; $q_topup = false;
if ($has_topup_table) {
    $has_note_col = ($conn->query("SHOW COLUMNS FROM member_topups LIKE 'note'")->num_rows > 0);
    $topup_fields = $has_note_col ? "mt.id, mt.member_id, mt.amount, mt.note, mt.created_at, m.nama_member, m.saldo as saldo_now" : "mt.id, mt.member_id, mt.amount, mt.created_at, m.nama_member, m.saldo as saldo_now, '' as note";
    $s_topup = $conn->prepare("SELECT $topup_fields 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");
    $s_topup->bind_param("ss", $start_date, $end_date); $s_topup->execute();
    $q_topup = $s_topup->get_result();

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

// --- Ambil daftar member untuk dropdown topup ---
$all_members = [];
$qm = mysqli_query($conn, "SELECT id, nama_member, saldo FROM members ORDER BY nama_member ASC");
while ($mm = mysqli_fetch_assoc($qm)) $all_members[] = $mm;

$grand_total  = $total_bill + $total_fnb + $total_topup;
$count_trx    = $q_trans ? mysqli_num_rows($q_trans) : 0;
$count_fnb    = $q_fnb   ? mysqli_num_rows($q_fnb)   : 0;
$count_topup  = $q_topup ? mysqli_num_rows($q_topup) : 0;
$count_all    = $count_trx + $count_fnb + $count_topup;

if ($q_trans && $count_trx > 0)   mysqli_data_seek($q_trans, 0);
if ($q_fnb   && $count_fnb > 0)   mysqli_data_seek($q_fnb, 0);
if ($q_topup && $count_topup > 0) mysqli_data_seek($q_topup, 0);

// Helper: badge metode bayar
function paymentBadge($method, $member_id) {
    $method = trim($method ?? '');
    if (empty($method)) $method = 'Cash';
    
    $m_lower = strtolower($method);

    // QRIS
    if (str_contains($m_lower, 'qris')) {
        return '<span class="pay-badge" style="background:rgba(139,92,246,.15);color:#c084fc;border:1px solid rgba(139,92,246,.25);">
            <i class="bx bx-qr"></i> QRIS</span>';
    }
    // Transfer
    if (str_contains($m_lower, 'transfer')) {
        return '<span class="pay-badge" style="background:rgba(6,182,212,.15);color:#67e8f9;border:1px solid rgba(6,182,212,.25);">
            <i class="bx bx-transfer"></i> Transfer Bank</span>';
    }
    // Member Saldo
    if (str_contains($m_lower, 'saldo') && !str_contains($m_lower, 'partial') && !str_contains($m_lower, '+')) {
        return '<span class="pay-badge pay-saldo"><i class="bx bx-wallet"></i> Member Saldo</span>';
    }
    // Partial Saldo+Cash
    if (str_contains($m_lower, 'partial') || str_contains($m_lower, 'saldo+') || str_contains($m_lower, '+cash')) {
        return '<span class="pay-badge pay-partial"><i class="bx bx-wallet-alt"></i> Saldo+Cash</span>';
    }
    // Debit
    if (str_contains($m_lower, 'debit')) {
        return '<span class="pay-badge" style="background:rgba(245,158,11,.15);color:#fbbf24;border:1px solid rgba(245,158,11,.25);">
            <i class="bx bx-credit-card"></i> Debit</span>';
    }
    // Voucher
    if (str_contains($m_lower, 'voucher')) {
        return '<span class="pay-badge" style="background:rgba(99,102,241,.15);color:#a5b4fc;border:1px solid rgba(99,102,241,.25);">
            <i class="bx bx-gift"></i> Voucher</span>';
    }
    // Pending
    if (str_contains($m_lower, 'pending')) {
        return '<span class="pay-badge" style="background:rgba(245,158,11,.15);color:#fbbf24;border:1px solid rgba(245,158,11,.25);">
            <i class="bx bx-time-five"></i> Pending</span>';
    }
    // Default: Cash atau metode lain
    return '<span class="pay-badge pay-cash"><i class="bx bx-money"></i> ' . htmlspecialchars($method) . '</span>';
}
?>

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

<style>
    :root {
        --glass-bg: rgba(30, 41, 59, 0.75);
        --glass-border: rgba(255, 255, 255, 0.08);
        --gradient-primary: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
        --text-muted: #94a3b8;
        --success: #22c55e;
        --danger: #ef4444;
        --primary: #06b6d4;
    }

    .dashboard-container { display: flex; flex-direction: column; gap: 30px; padding-bottom: 50px; }

    /* ── FILTER BAR ── */
    .filter-bar { background: var(--glass-bg); border: 1px solid var(--glass-border); padding: 20px; border-radius: 16px; display: flex; flex-wrap: wrap; gap: 14px; align-items: flex-end; backdrop-filter: blur(10px); }
    .filter-item { display: flex; flex-direction: column; gap: 8px; flex: 1; min-width: 150px; }
    .filter-label { font-size: 0.75rem; color: var(--text-muted); font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; }
    .custom-input { background: rgba(0,0,0,0.2); border: 1px solid var(--glass-border); color: #fff; padding: 12px 15px; border-radius: 10px; font-family: inherit; width: 100%; outline: none; color-scheme: dark; font-size: .88rem; transition: border-color .2s; }
    .custom-input:focus { border-color: var(--primary); }
    .btn-filter { background: var(--gradient-primary); border: none; color: #fff; padding: 12px 25px; border-radius: 10px; font-weight: 700; cursor: pointer; height: 45px; white-space: nowrap; font-size: .85rem; }
    .btn-topup-new { background: linear-gradient(135deg, #10b981, #059669); border: none; color: #fff; padding: 12px 20px; border-radius: 10px; font-weight: 800; cursor: pointer; height: 45px; display: flex; align-items: center; gap: 8px; white-space: nowrap; font-size: .85rem; transition: all .2s; }
    .btn-topup-new:hover { filter: brightness(1.1); transform: translateY(-1px); box-shadow: 0 6px 20px rgba(16,185,129,.3); }
    .btn-export-pdf { background: linear-gradient(135deg, #0891b2, #06b6d4); border: none; color: #000; padding: 12px 20px; border-radius: 10px; font-weight: 800; cursor: pointer; height: 45px; display: flex; align-items: center; gap: 8px; white-space: nowrap; font-size: .85rem; transition: all .2s; }
    .btn-export-pdf:hover { filter: brightness(1.1); transform: translateY(-1px); box-shadow: 0 6px 20px rgba(6,182,212,.3); }

    /* ── STATS ── */
    .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 16px; }
    .stat-card { background: var(--glass-bg); border: 1px solid var(--glass-border); padding: 22px; border-radius: 20px; }
    .stat-card.purple { border-left: 4px solid #d946ef; } .stat-card.blue   { border-left: 4px solid #6366f1; }
    .stat-card.orange { border-left: 4px solid #f59e0b; } .stat-card.green  { border-left: 4px solid #10b981; }
    .stat-card.cyan   { border-left: 4px solid #06b6d4; } .stat-card.pink   { border-left: 4px solid #ec4899; }
    .stat-value { font-size: 1.55rem; font-weight: 800; color: #fff; margin-top: 4px; }
    .stat-title { color: var(--text-muted); font-size: .8rem; font-weight: 600; }
    .stat-sub   { font-size: .7rem; color: #64748b; margin-top: 3px; }

    /* ── PAYMENT BADGE ── */
    .pay-badge { padding: 4px 10px; border-radius: 8px; font-size: .72rem; font-weight: 700; display: inline-flex; align-items: center; gap: 5px; white-space: nowrap; }
    .pay-cash    { background: rgba(100,116,139,.15); color: #94a3b8; border: 1px solid rgba(100,116,139,.2); }
    .pay-saldo   { background: rgba(16,185,129,.15);  color: #34d399;  border: 1px solid rgba(16,185,129,.25); }
    .pay-partial { background: rgba(245,158,11,.15);  color: #fbbf24;  border: 1px solid rgba(245,158,11,.25); }

    /* ── [VOUCHER] DISCOUNT BADGE ── */
    .discount-badge { 
        display: inline-flex; 
        align-items: center; 
        gap: 4px; 
        padding: 3px 8px; 
        border-radius: 6px; 
        font-size: .68rem; 
        font-weight: 700; 
        background: rgba(16,185,129,.12); 
        color: #34d399; 
        border: 1px solid rgba(16,185,129,.25); 
        margin-top: 2px;
    }

    /* ── TABLE ── */
    .report-section { background: var(--glass-bg); border: 1px solid var(--glass-border); border-radius: 24px; overflow: hidden; backdrop-filter: blur(12px); }
    .section-header { padding: 22px 25px; border-bottom: 1px solid var(--glass-border); background: rgba(255,255,255,.02); display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 12px; }
    .section-title { font-size: 1rem; color: #fff; font-weight: 700; display: flex; align-items: center; gap: 10px; }
    .table-container { max-height: 520px; overflow-y: auto; }
    table { width: 100%; border-collapse: collapse; }
    th { text-align: left; padding: 13px 20px; color: var(--text-muted); font-size: .72rem; text-transform: uppercase; background: rgba(15,23,42,.6); position: sticky; top: 0; white-space: nowrap; z-index: 2; }
    td { padding: 15px 20px; border-bottom: 1px solid rgba(255,255,255,.04); color: #e2e8f0; font-size: .88rem; vertical-align: middle; }
    tr:hover td { background: rgba(255,255,255,.02); }
    .money { font-family: 'JetBrains Mono', monospace; font-weight: 700; }
    .badge { padding: 4px 10px; border-radius: 6px; font-size: .72rem; font-weight: 700; }
    .badge-vip { background: rgba(139,92,246,.2); color: #c084fc; }
    .btn-del { background: rgba(239,68,68,.1); border: 1px solid rgba(239,68,68,.2); color: #f87171; padding: 6px 10px; border-radius: 8px; cursor: pointer; font-size: 1rem; transition: all .2s; display: inline-flex; align-items: center; justify-content: center; }
    .btn-del:hover { background: rgba(239,68,68,.25); border-color: rgba(239,68,68,.5); transform: scale(1.05); }
    .record-count { font-size: .72rem; color: var(--text-muted); background: rgba(0,0,0,.2); padding: 4px 10px; border-radius: 8px; font-weight: 600; }
    .btn-bulk-delete { background: rgba(239,68,68,.1); border: 1px solid rgba(239,68,68,.25); color: #f87171; padding: 10px 18px; border-radius: 12px; cursor: pointer; font-weight: 700; font-size: .8rem; transition: all .3s; display: inline-flex; align-items: center; gap: 8px; text-transform: uppercase; letter-spacing: .5px; }
    .btn-bulk-delete:hover { background: rgba(239,68,68,.2); box-shadow: 0 0 20px rgba(239,68,68,.15); transform: translateY(-1px); }

    /* ── [VOUCHER] PRICE STRIKETHROUGH ── */
    .price-original { 
        font-size: .72rem; 
        color: #94a3b8; 
        text-decoration: line-through; 
        font-weight: 400;
    }
    .price-discounted { 
        color: #10b981; 
        font-weight: 800; 
        font-size: .95rem;
    }

    /* ── ALERTS ── */
    .alert-box { padding: 16px 22px; border-radius: 14px; display: flex; align-items: center; gap: 12px; font-weight: 600; animation: fadeSlideIn .4s ease; }
    .alert-deleted { background: rgba(239,68,68,.1); border: 1px solid rgba(239,68,68,.2); color: #f87171; }
    .alert-success { background: rgba(16,185,129,.1); border: 1px solid rgba(16,185,129,.25); color: #34d399; }
    .alert-box i { font-size: 1.4rem; }
    @keyframes fadeSlideIn { from { opacity:0; transform:translateY(-8px); } to { opacity:1; transform:translateY(0); } }

    /* ── MODAL TOPUP ── */
    .modal-backdrop { position: fixed; inset: 0; z-index: 9999; background: rgba(0,0,0,.8); backdrop-filter: blur(8px); display: none; align-items: center; justify-content: center; }
    .modal-backdrop.active { display: flex; }
    .modal-box { background: #1e293b; border: 1px solid rgba(255,255,255,.1); border-radius: 24px; padding: 34px; width: 100%; max-width: 460px; box-shadow: 0 25px 60px rgba(0,0,0,.6); animation: modalPop .25s ease; }
    @keyframes modalPop { from { opacity:0; transform:scale(.94) translateY(12px); } to { opacity:1; transform:scale(1) translateY(0); } }
    .modal-header { display: flex; align-items: center; gap: 14px; margin-bottom: 26px; }
    .modal-icon { width: 48px; height: 48px; background: rgba(16,185,129,.12); border-radius: 14px; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; flex-shrink: 0; }
    .modal-title { font-size: 1.1rem; font-weight: 800; color: #fff; }
    .modal-sub   { font-size: .73rem; color: #64748b; margin-top: 2px; }
    .modal-close { margin-left: auto; background: rgba(255,255,255,.06); border: none; color: #94a3b8; width: 34px; height: 34px; border-radius: 10px; cursor: pointer; font-size: 1rem; transition: all .2s; }
    .modal-close:hover { background: rgba(255,255,255,.12); color: #fff; }
    .field-group { margin-bottom: 16px; }
    .field-label { font-size: .72rem; color: #94a3b8; text-transform: uppercase; letter-spacing: 1px; font-weight: 700; display: block; margin-bottom: 7px; }
    .field-input { width: 100%; background: rgba(0,0,0,.3); border: 1px solid rgba(255,255,255,.08); color: #fff; padding: 12px 16px; border-radius: 12px; font-size: .9rem; outline: none; box-sizing: border-box; font-family: inherit; transition: border-color .2s; -webkit-appearance: none; appearance: none; color-scheme: dark; }
    .field-input:focus { border-color: #10b981; }
    .field-input option { background: #1e293b; }
    .quick-btns { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 16px; }
    .quick-btn { background: rgba(16,185,129,.1); border: 1px solid rgba(16,185,129,.2); color: #34d399; padding: 7px 14px; border-radius: 9px; cursor: pointer; font-size: .75rem; font-weight: 700; transition: all .2s; }
    .quick-btn:hover { background: rgba(16,185,129,.2); border-color: #10b981; }
    .saldo-preview { background: rgba(6,182,212,.07); border: 1px solid rgba(6,182,212,.15); border-radius: 12px; padding: 12px 16px; margin-bottom: 18px; font-size: .8rem; display: none; }
    .saldo-preview.show { display: block; }
    .saldo-row { display: flex; justify-content: space-between; margin-bottom: 5px; }
    .saldo-row:last-child { margin-bottom: 0; border-top: 1px solid rgba(255,255,255,.06); padding-top: 8px; margin-top: 4px; font-weight: 800; }
    .btn-modal-row { display: grid; grid-template-columns: 1fr 1.5fr; gap: 12px; }
    .btn-cancel { padding: 13px; border-radius: 12px; border: 1px solid rgba(255,255,255,.1); background: transparent; color: #94a3b8; font-weight: 700; cursor: pointer; font-size: .88rem; transition: all .2s; }
    .btn-cancel:hover { background: rgba(255,255,255,.05); color: #fff; }
    .btn-submit { padding: 13px; border-radius: 12px; border: none; background: linear-gradient(135deg, #10b981, #059669); color: #fff; font-weight: 800; cursor: pointer; font-size: .88rem; display: flex; align-items: center; justify-content: center; gap: 8px; transition: all .2s; }
    .btn-submit:hover { filter: brightness(1.1); transform: translateY(-1px); }

    /* ── EXPORT MODAL ── */
    .export-modal-overlay { display: none; position: fixed; inset: 0; z-index: 9999; background: rgba(0,0,0,.75); backdrop-filter: blur(5px); align-items: center; justify-content: center; }
    .export-modal-overlay.active { display: flex; }
    .export-modal { background: #1e293b; border: 1px solid rgba(255,255,255,.1); border-radius: 24px; padding: 36px; width: 100%; max-width: 500px; box-shadow: 0 25px 60px rgba(0,0,0,.6); animation: modalPop .25s ease; }
    .export-modal-header { display: flex; align-items: center; gap: 14px; margin-bottom: 28px; }
    .export-modal-icon { width: 50px; height: 50px; background: rgba(6,182,212,.12); border-radius: 14px; display: flex; align-items: center; justify-content: center; font-size: 1.6rem; flex-shrink: 0; }
    .export-modal-title { font-size: 1.1rem; font-weight: 800; color: #fff; }
    .export-modal-sub { font-size: .73rem; color: #64748b; margin-top: 2px; }
    .export-modal-close { margin-left: auto; background: rgba(255,255,255,.06); border: none; color: #94a3b8; width: 36px; height: 36px; border-radius: 10px; cursor: pointer; font-size: 1rem; transition: all .2s; }
    .export-modal-close:hover { background: rgba(255,255,255,.12); color: #fff; }
    .exp-field { margin-bottom: 16px; }
    .exp-label { font-size: .72rem; color: #94a3b8; text-transform: uppercase; letter-spacing: 1px; font-weight: 700; display: block; margin-bottom: 7px; }
    .exp-input { width: 100%; background: rgba(0,0,0,.3); border: 1px solid rgba(255,255,255,.08); color: #fff; padding: 12px 16px; border-radius: 12px; font-size: .9rem; outline: none; color-scheme: dark; box-sizing: border-box; font-family: inherit; transition: border-color .2s; }
    .exp-input:focus { border-color: #06b6d4; }
    .exp-shortcut-row { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 16px; }
    .exp-shortcut { background: rgba(255,255,255,.05); border: 1px solid rgba(255,255,255,.08); color: #94a3b8; padding: 6px 14px; border-radius: 8px; cursor: pointer; font-size: .75rem; font-weight: 600; transition: all .2s; }
    .exp-shortcut:hover { background: rgba(6,182,212,.1); border-color: rgba(6,182,212,.3); color: #06b6d4; }
    .exp-info { background: rgba(6,182,212,.07); border: 1px solid rgba(6,182,212,.15); border-radius: 12px; padding: 12px 16px; font-size: .78rem; color: #67e8f9; margin-bottom: 20px; line-height: 1.6; }
    .exp-btn-row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
    .exp-btn-cancel { padding: 13px; border-radius: 12px; border: 1px solid rgba(255,255,255,.1); background: transparent; color: #94a3b8; font-weight: 700; cursor: pointer; font-size: .88rem; transition: all .2s; }
    .exp-btn-cancel:hover { background: rgba(255,255,255,.05); color: #fff; }
    .exp-btn-go { padding: 13px; border-radius: 12px; border: none; background: linear-gradient(135deg, #06b6d4, #0891b2); color: #000; font-weight: 800; cursor: pointer; font-size: .88rem; display: flex; align-items: center; justify-content: center; gap: 8px; transition: all .2s; }
    .exp-btn-go:hover { filter: brightness(1.1); transform: translateY(-1px); }

    ::-webkit-scrollbar { width: 6px; } ::-webkit-scrollbar-track { background: transparent; } ::-webkit-scrollbar-thumb { background: rgba(255,255,255,.1); border-radius: 3px; }
</style>

<div class="dashboard-container">

    <?php if ($deleted_msg !== null): ?>
    <div class="alert-box alert-deleted">
        <i class='bx bx-check-shield'></i>
        <span>Berhasil menghapus <b><?= $deleted_msg ?></b> data riwayat.</span>
    </div>
    <?php endif; ?>

    <?php if ($topup_success): ?>
    <div class="alert-box alert-success">
        <i class='bx bx-check-circle'></i>
        <span>Top-up <b>Rp <?= number_format($topup_amount) ?></b> untuk member <b><?= $topup_nama ?></b> berhasil dicatat!</span>
    </div>
    <?php endif; ?>

    <?php if (!$has_stik_column): ?>
    <div style="background:rgba(245,158,11,.15);border:1px solid rgba(245,158,11,.3);padding:15px;border-radius:12px;color:#f59e0b;display:flex;align-items:center;gap:15px;">
        <i class='bx bx-info-circle' style="font-size:1.5rem;"></i>
        <div><b>Mode Kompatibilitas:</b> Kolom <code>stik_info</code> tidak ditemukan. Laporan tetap berjalan, namun detail stik tidak tampil.</div>
    </div>
    <?php endif; ?>

    <!-- ── FILTER BAR ── -->
    <form method="GET" class="filter-bar">
        <div class="filter-item">
            <span class="filter-label">Mulai Tanggal</span>
            <input type="date" name="start_date" class="custom-input" value="<?= $start_date ?>">
        </div>
        <div class="filter-item">
            <span class="filter-label">Sampai Tanggal</span>
            <input type="date" name="end_date" class="custom-input" value="<?= $end_date ?>">
        </div>
        <div class="filter-item">
            <span class="filter-label">Tipe Laporan</span>
            <select name="view_type" class="custom-input">
                <option value="all"   <?= $view_type=='all'   ?'selected':'' ?>>Semua Data</option>
                <option value="ps"    <?= $view_type=='ps'    ?'selected':'' ?>>Rental & Billing</option>
                <option value="fnb"   <?= $view_type=='fnb'   ?'selected':'' ?>>Makanan & Minuman</option>
                <option value="topup" <?= $view_type=='topup' ?'selected':'' ?>>Top Up Member</option>
            </select>
        </div>
        <button type="submit" class="btn-filter"><i class='bx bx-search'></i> Tampilkan</button>
        <button type="button" class="btn-topup-new" onclick="openTopupModal()">
            <i class='bx bx-wallet-alt'></i> + Top Up Member
        </button>
        <button type="button" class="btn-export-pdf" onclick="openExportModal()">
            <i class='bx bx-file'></i> Export PDF
        </button>
    </form>

    <!-- ── STATS ── -->
    <div class="stats-grid">
        <div class="stat-card purple">
            <div class="stat-title">Total Pendapatan Bersih</div>
            <div class="stat-value">Rp <?= number_format($grand_total) ?></div>
            <div class="stat-sub"><?= $count_all ?> transaksi total</div>
        </div>
        <div class="stat-card blue">
            <div class="stat-title">Pendapatan Rental</div>
            <div class="stat-value">Rp <?= number_format($total_bill) ?></div>
            <div class="stat-sub"><?= $count_trx ?> sesi</div>
        </div>
        <div class="stat-card orange">
            <div class="stat-title">Penjualan F&B</div>
            <div class="stat-value">Rp <?= number_format($total_fnb) ?></div>
            <div class="stat-sub"><?= $count_fnb ?> item terjual</div>
        </div>
        <div class="stat-card green">
            <div class="stat-title">Deposit / Top Up</div>
            <div class="stat-value">Rp <?= number_format($total_topup) ?></div>
            <div class="stat-sub"><?= $count_topup ?> transaksi</div>
        </div>
        <div class="stat-card cyan">
            <div class="stat-title">Bayar via Saldo Member</div>
            <div class="stat-value">Rp <?= number_format($pay_saldo) ?></div>
            <div class="stat-sub">Lunas dari saldo</div>
        </div>
        <div class="stat-card pink">
            <div class="stat-title">Bayar Saldo + Cash</div>
            <div class="stat-value">Rp <?= number_format($pay_partial) ?></div>
            <div class="stat-sub">Saldo kurang → ditambah cash</div>
        </div>
    </div>

    <!-- ── BULK DELETE ── -->
    <?php if ($count_all > 0): ?>
    <div style="display:flex; justify-content:flex-end;">
        <button type="button" class="btn-bulk-delete" onclick="confirmBulkDelete()">
            <i class='bx bx-trash'></i> Hapus Semua Data (<?= $count_all ?> record)
        </button>
    </div>
    <?php endif; ?>

    <!-- ══════════════════════════════
         TABEL BILLING RENTAL
    ══════════════════════════════ -->
    <?php if ($view_type == 'all' || $view_type == 'ps'): ?>
    <div class="report-section">
        <div class="section-header">
            <div class="section-title"><i class='bx bx-time-five'></i> Riwayat Billing Rental</div>
            <span class="record-count"><?= $count_trx ?> data</span>
        </div>
        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>Waktu Sesi</th>
                        <th>Unit TV</th>
                        <th>User / Paket</th>
                        <th>Stik</th>
                        <th>Durasi</th>
                        <th>Metode Bayar</th>
                        <th style="text-align:right;">Total</th>
                        <th style="text-align:center;width:46px;">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                <?php if ($count_trx > 0): while ($row = mysqli_fetch_assoc($q_trans)):
                    $durasi = (new DateTime($row['start_time']))->diff(new DateTime($row['end_time']));
                    $nama_paket_display = $row['nama_paket'] ?? ("Rental " . ($durasi->h + ($durasi->days * 24)) . " Jam");
                    $del_params = $_GET; $del_params['delete_trx'] = $row['id'];
                    $is_pending = strtolower($row['payment_method'] ?? '') === 'pending' 
           || strtolower($row['payment_status'] ?? 'paid') === 'pending';
                    $jenis_label = ($row['jenis_paket'] ?? 'fixed') === 'open'
                        ? '<span style="font-size:.68rem;color:#f59e0b;font-weight:700;">OPEN BILL</span>'
                        : '<span style="font-size:.68rem;color:#60a5fa;font-weight:700;">PAKET</span>';
                    
                    // [VOUCHER] Hitung diskon
$diskon_row   = (int)($row['diskon'] ?? 0);
$total_bayar_db = (int)$row['total_bayar']; // sudah bersih setelah diskon
                    $total_asli_display = $total_bayar_db + $diskon_row;
                ?>
                    <tr>
                        <td>
                            <div style="display:flex;flex-direction:column;gap:3px;font-size:.78rem;white-space:nowrap;">
                                <span><i class='bx bx-log-in-circle' style="color:var(--success);"></i> <?= date('d/m H:i', strtotime($row['start_time'])) ?></span>
                                <span><i class='bx bx-log-out-circle' style="color:var(--danger);"></i> <?= date('d/m H:i', strtotime($row['end_time'])) ?></span>
                            </div>
                        </td>
                        <td style="font-weight:700;color:#fff;"><?= htmlspecialchars($row['nama_tv']) ?></td>
                        <td>
                            <div style="display:flex;flex-direction:column;gap:4px;">
                                <?php if (!empty($row['nama_member'])): ?>
                                    <span class="badge badge-vip"><i class='bx bxs-crown'></i> <?= htmlspecialchars($row['nama_member']) ?></span>
                                <?php else: ?>
                                    <span style="font-size:.78rem;color:var(--text-muted);">Tamu Reguler</span>
                                <?php endif; ?>
                                <div style="display:flex;align-items:center;gap:5px;"><?= $jenis_label ?> <span style="font-size:.73rem;color:var(--text-muted);"><?= htmlspecialchars($nama_paket_display) ?></span></div>
                            </div>
                        </td>
                        <td><span style="font-size:.75rem;color:var(--text-muted);line-height:1.6;"><?= !empty($row['stik_info']) ? str_replace(',', '<br>', htmlspecialchars($row['stik_info'])) : '-' ?></span></td>
                        <td style="font-size:.85rem;"><?= $durasi->h ?>j <?= $durasi->i ?>m</td>
                        <td>
    <?= paymentBadge($row['payment_method'] ?? null, $row['member_id'] ?? null) ?>
    <?php if ($is_pending): ?>
    <div style="margin-top:6px;">
        <button onclick="konfirmasiBayarHistory(<?= $row['id'] ?>, '<?= htmlspecialchars($row['nama_tv']) ?>')"
            style="background:rgba(16,185,129,.15);border:1px solid rgba(16,185,129,.3);color:#34d399;
                   padding:5px 10px;border-radius:8px;cursor:pointer;font-size:.72rem;font-weight:700;
                   display:inline-flex;align-items:center;gap:5px;transition:all .2s;"
            onmouseover="this.style.background='rgba(16,185,129,.3)'"
            onmouseout="this.style.background='rgba(16,185,129,.15)'">
            <i class='bx bx-check-circle'></i> Konfirmasi Bayar
        </button>
    </div>
    <?php endif; ?>
</td>
<td style="text-align:right;">
<?php if ($diskon_row > 0): ?>
    <div class="price-original">
        Rp <?= number_format($total_asli_display) ?>
    </div>
    <div class="money price-discounted">
        Rp <?= number_format($total_bayar_db) ?>
    </div>
<div class="discount-badge">
    <i class='bx bx-gift'></i> -<?= number_format($diskon_row) ?>
</div>
<?php
// Tampilkan kode voucher jika ada voucher_id
if (!empty($row['voucher_id'])):
    // Ambil kode voucher dari tabel vouchers
    $v_stmt = $conn->prepare("SELECT kode FROM vouchers WHERE id = ? LIMIT 1");
    $v_stmt->bind_param("i", $row['voucher_id']);
    $v_stmt->execute();
    $v_res  = $v_stmt->get_result()->fetch_assoc();
    $v_stmt->close();
    if ($v_res):
?>
<div style="
    display:inline-flex;align-items:center;gap:4px;
    padding:3px 8px;border-radius:6px;font-size:.65rem;
    font-weight:800;letter-spacing:.5px;margin-top:3px;
    background:rgba(99,102,241,.12);
    color:#a5b4fc;
    border:1px solid rgba(99,102,241,.25);
">
    <i class='bx bx-purchase-tag'></i>
    <?= htmlspecialchars($v_res['kode']) ?>
</div>
<?php endif; endif; ?>
<?php else: ?>
    <div class="money" style="color:#60a5fa;font-weight:700;">
        Rp <?= number_format($total_bayar_db) ?>
    </div>
<?php endif; ?>
</td>
                        <td style="text-align:center;">
                            <button class="btn-del" onclick="confirmDelete('history.php?<?= http_build_query($del_params) ?>', 'transaksi #<?= $row['id'] ?> (<?= htmlspecialchars($row['nama_tv']) ?>)')" title="Hapus">
                                <i class='bx bx-trash'></i>
                            </button>
                        </td>
                    </tr>
                <?php endwhile; else: ?>
                    <tr><td colspan="8" style="text-align:center;padding:30px;color:#64748b;"><i class='bx bx-inbox' style="font-size:2rem;display:block;margin-bottom:8px;"></i>Tidak ada data transaksi rental.</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <!-- ══════════════════════════════
         TABEL F&B
    ══════════════════════════════ -->
    <?php if ($view_type == 'all' || $view_type == 'fnb'): ?>
    <div class="report-section">
        <div class="section-header">
            <div class="section-title"><i class='bx bxs-food-menu'></i> Riwayat F&B</div>
            <span class="record-count"><?= $count_fnb ?> data</span>
        </div>
        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>Waktu</th><th>Item</th><th>Qty</th><th>Sumber</th>
                        <th style="text-align:right;">Subtotal</th>
                        <th style="text-align:center;width:46px;">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                <?php if ($count_fnb > 0): while ($sn = mysqli_fetch_assoc($q_fnb)):
                    $del_params_fnb = $_GET; $del_params_fnb['delete_fnb'] = $sn['id'];
                ?>
                    <tr>
                        <td style="font-size:.8rem;"><?= date('d/m H:i', strtotime($sn['created_at'])) ?></td>
                        <td style="color:#fff;font-weight:600;"><?= htmlspecialchars($sn['nama_barang']) ?></td>
                        <td><span style="background:rgba(6,182,212,.12);color:#67e8f9;padding:3px 10px;border-radius:6px;font-size:.78rem;font-weight:700;">×<?= $sn['qty'] ?></span></td>
                        <td style="font-size:.82rem;color:var(--text-muted);"><?= htmlspecialchars($sn['sumber']) ?></td>
                        <td class="money" style="text-align:right;color:#34d399;">Rp <?= number_format($sn['total']) ?></td>
                        <td style="text-align:center;">
                            <button class="btn-del" onclick="confirmDelete('history.php?<?= http_build_query($del_params_fnb) ?>', 'FnB: <?= htmlspecialchars($sn['nama_barang']) ?>')" title="Hapus">
                                <i class='bx bx-trash'></i>
                            </button>
                        </td>
                    </tr>
                <?php endwhile; else: ?>
                    <tr><td colspan="6" style="text-align:center;padding:30px;color:#64748b;"><i class='bx bx-inbox' style="font-size:2rem;display:block;margin-bottom:8px;"></i>Tidak ada penjualan F&B.</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <!-- ══════════════════════════════
         TABEL TOP UP
    ══════════════════════════════ -->
    <?php if ($view_type == 'all' || $view_type == 'topup'): ?>
    <div class="report-section">
        <div class="section-header">
            <div class="section-title"><i class='bx bx-trending-up'></i> Riwayat Top Up Member</div>
            <div style="display:flex;align-items:center;gap:12px;">
                <span class="record-count"><?= $count_topup ?> data</span>
                <button type="button" onclick="openTopupModal()" style="background:rgba(16,185,129,.12);border:1px solid rgba(16,185,129,.25);color:#34d399;padding:6px 14px;border-radius:9px;cursor:pointer;font-size:.78rem;font-weight:700;display:flex;align-items:center;gap:6px;">
                    <i class='bx bx-plus'></i> Tambah
                </button>
            </div>
        </div>
        <div class="table-container">
            <?php if (!$has_topup_table): ?>
                <div style="padding:30px;text-align:center;color:#ef4444;"><i class='bx bx-error-circle'></i> Tabel 'member_topups' belum dibuat.</div>
            <?php elseif ($count_topup == 0): ?>
                <div style="padding:30px;text-align:center;color:#64748b;">
                    <i class='bx bx-inbox' style="font-size:2rem;display:block;margin-bottom:8px;"></i>
                    Belum ada data topup periode ini.
                    <div style="margin-top:12px;"><button type="button" onclick="openTopupModal()" style="background:rgba(16,185,129,.12);border:1px solid rgba(16,185,129,.25);color:#34d399;padding:8px 18px;border-radius:10px;cursor:pointer;font-size:.8rem;font-weight:700;">+ Catat Top Up Baru</button></div>
                </div>
            <?php else: ?>
            <table>
                <thead>
                    <tr>
                        <th>Tanggal</th>
                        <th>Member</th>
                        <th>Saldo Sekarang</th>
                        <?php if ($has_note_col ?? false): ?><th>Keterangan</th><?php endif; ?>
                        <th style="text-align:right;">Nominal Top Up</th>
                        <th style="text-align:center;width:46px;">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                <?php while ($tu = mysqli_fetch_assoc($q_topup)):
                    $del_params_tu = $_GET; $del_params_tu['delete_topup'] = $tu['id'];
                ?>
                    <tr>
                        <td style="font-size:.8rem;white-space:nowrap;"><?= date('d/m/Y H:i', strtotime($tu['created_at'])) ?></td>
                        <td>
                            <span class="badge badge-vip"><i class='bx bxs-crown'></i> <?= htmlspecialchars($tu['nama_member']) ?></span>
                        </td>
                        <td>
                            <span style="font-family:'JetBrains Mono',monospace;font-size:.82rem;color:#67e8f9;">
                                Rp <?= number_format($tu['saldo_now']) ?>
                            </span>
                        </td>
                        <?php if ($has_note_col ?? false): ?>
                        <td style="font-size:.8rem;color:var(--text-muted);"><?= htmlspecialchars($tu['note'] ?? '-') ?></td>
                        <?php endif; ?>
                        <td class="money" style="text-align:right;color:var(--success);">+ Rp <?= number_format($tu['amount']) ?></td>
                        <td style="text-align:center;">
                            <button class="btn-del" onclick="confirmDeleteTopup('history.php?<?= http_build_query($del_params_tu) ?>', '<?= htmlspecialchars($tu['nama_member']) ?>', <?= $tu['amount'] ?>)" title="Hapus">
                                <i class='bx bx-trash'></i>
                            </button>
                        </td>
                    </tr>
                <?php endwhile; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

</div><!-- /dashboard-container -->

<!-- BULK DELETE FORM -->
<form id="bulkDeleteForm" method="POST" style="display:none;">
    <input type="hidden" name="bulk_delete" value="1">
    <input type="hidden" name="bd_start" value="<?= $start_date ?>">
    <input type="hidden" name="bd_end"   value="<?= $end_date ?>">
    <input type="hidden" name="bd_type"  value="<?= $view_type ?>">
</form>

<!-- ══════════════════════════════════════════════
     MODAL TOP UP MEMBER
══════════════════════════════════════════════ -->
<div class="modal-backdrop" id="modalTopup" onclick="handleTopupOverlay(event)">
    <div class="modal-box">
        <div class="modal-header">
            <div class="modal-icon">💳</div>
            <div>
                <div class="modal-title">Catat Top Up Saldo</div>
                <div class="modal-sub">Tambah saldo member & simpan ke riwayat</div>
            </div>
            <button class="modal-close" onclick="closeTopupModal()">✕</button>
        </div>

        <form method="POST" id="topupForm">
            <input type="hidden" name="action" value="manual_topup">
            <!-- Pertahankan filter saat redirect -->
            <input type="hidden" name="start_date_keep" value="<?= $start_date ?>">
            <input type="hidden" name="end_date_keep"   value="<?= $end_date ?>">

            <div class="field-group">
                <label class="field-label">Pilih Member</label>
                <select name="tu_member_id" id="tu_member_id" class="field-input" onchange="updateSaldoPreview()" required>
                    <option value="">-- Pilih Member --</option>
                    <?php foreach ($all_members as $mm): ?>
                        <option value="<?= $mm['id'] ?>" data-saldo="<?= $mm['saldo'] ?>">
                            <?= htmlspecialchars($mm['nama_member']) ?> — Rp <?= number_format($mm['saldo']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="field-group">
                <label class="field-label">Nominal Top Up (Rp)</label>
                <input type="number" name="tu_amount" id="tu_amount" class="field-input"
                       placeholder="0" min="1000" step="1000" oninput="updateSaldoPreview()" required>
            </div>

            <div class="quick-btns">
                <button type="button" class="quick-btn" onclick="setTuAmount(10000)">+10.000</button>
                <button type="button" class="quick-btn" onclick="setTuAmount(20000)">+20.000</button>
                <button type="button" class="quick-btn" onclick="setTuAmount(50000)">+50.000</button>
                <button type="button" class="quick-btn" onclick="setTuAmount(100000)">+100.000</button>
                <button type="button" class="quick-btn" onclick="setTuAmount(200000)">+200.000</button>
            </div>

            <!-- Preview saldo setelah topup -->
            <div class="saldo-preview" id="saldoPreview">
                <div class="saldo-row">
                    <span style="color:#94a3b8;">Saldo saat ini</span>
                    <span id="prev_current" style="color:#fff;font-weight:600;">Rp 0</span>
                </div>
                <div class="saldo-row">
                    <span style="color:#94a3b8;">Ditambah</span>
                    <span id="prev_add" style="color:#34d399;font-weight:700;">+ Rp 0</span>
                </div>
                <div class="saldo-row">
                    <span style="color:#67e8f9;">Saldo setelah top up</span>
                    <span id="prev_after" style="color:#67e8f9;font-size:1rem;">Rp 0</span>
                </div>
            </div>

            <div class="field-group">
                <label class="field-label">Keterangan (opsional)</label>
                <input type="text" name="tu_note" class="field-input" placeholder="Mis: Top up tunai, transfer BCA...">
            </div>

            <div class="btn-modal-row">
                <button type="button" class="btn-cancel" onclick="closeTopupModal()">Batal</button>
                <button type="submit" class="btn-submit" id="topupSubmitBtn">
                    <i class='bx bx-check'></i> SIMPAN TOP UP
                </button>
            </div>
        </form>
    </div>
</div>

<!-- ══════════════════════════════════════════════
     EXPORT PDF MODAL
══════════════════════════════════════════════ -->
<div class="export-modal-overlay" id="exportModal" onclick="handleExportOverlay(event)">
    <div class="export-modal">
        <div class="export-modal-header">
            <div class="export-modal-icon">📄</div>
            <div>
                <div class="export-modal-title">Export Laporan PDF</div>
                <div class="export-modal-sub">Pilih periode, operator, dan kategori laporan</div>
            </div>
            <button class="export-modal-close" onclick="closeExportModal()">✕</button>
        </div>

        <div class="exp-label">Shortcut Periode</div>
        <div class="exp-shortcut-row">
            <button type="button" class="exp-shortcut" onclick="setShortcut('today')">Hari Ini</button>
            <button type="button" class="exp-shortcut" onclick="setShortcut('yesterday')">Kemarin</button>
            <button type="button" class="exp-shortcut" onclick="setShortcut('week')">7 Hari Terakhir</button>
            <button type="button" class="exp-shortcut" onclick="setShortcut('month')">Bulan Ini</button>
            <button type="button" class="exp-shortcut" onclick="setShortcut('lastmonth')">Bulan Lalu</button>
        </div>

        <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px;">
            <div class="exp-field">
                <label class="exp-label">Tanggal Mulai</label>
                <input type="date" id="exp_start" class="exp-input" value="<?= date('Y-m-d') ?>">
            </div>
            <div class="exp-field">
                <label class="exp-label">Tanggal Selesai</label>
                <input type="date" id="exp_end" class="exp-input" value="<?= date('Y-m-d') ?>">
            </div>
        </div>

        <div class="exp-field">
            <label class="exp-label">Nama Operator / Shift</label>
            <input type="text" id="exp_operator" class="exp-input"
                   value="<?= htmlspecialchars($_SESSION['username'] ?? 'Admin') ?>"
                   placeholder="Nama operator yang bertugas...">
        </div>

        <div class="exp-field">
            <label class="exp-label">Kategori Data</label>
            <select id="exp_type" class="exp-input">
                <option value="all">Semua Data (Billing + F&B + Top Up)</option>
                <option value="ps">Billing Rental Saja</option>
                <option value="fnb">F&B Saja</option>
                <option value="topup">Top Up Member Saja</option>
            </select>
        </div>

        <div class="exp-info">
            💡 <b>Cara simpan PDF:</b> Klik <b>Buka Preview</b> → di halaman laporan klik tombol
            <b style="color:#fff;">🖨 Cetak / Simpan PDF</b> → pilih <b style="color:#fff;">Save as PDF</b> di dialog print browser.
        </div>

        <div class="exp-btn-row">
            <button type="button" class="exp-btn-cancel" onclick="closeExportModal()">Batal</button>
            <button type="button" class="exp-btn-go" onclick="doExport()">
                📄 Buka Preview
            </button>
        </div>
    </div>
</div>

<script>
// ══════════════════════════════════════════════════
// DELETE CONFIRM
// ══════════════════════════════════════════════════
function confirmDelete(url, label) {
    Swal.fire({
        title: 'Hapus Data?',
        html: `<span style="color:#94a3b8">Yakin ingin menghapus <b style="color:#f87171">${label}</b>?<br>Data yang dihapus tidak bisa dikembalikan.</span>`,
        icon: 'warning', showCancelButton: true,
        confirmButtonText: '<i class="bx bx-trash"></i> Ya, Hapus!',
        cancelButtonText: 'Batal',
        confirmButtonColor: '#ef4444', cancelButtonColor: '#334155',
        background: '#1e293b', color: '#fff',
    }).then(r => { if (r.isConfirmed) window.location.href = url; });
}

function confirmDeleteTopup(url, nama, amount) {
    Swal.fire({
        title: 'Hapus Top Up?',
        html: `<span style="color:#94a3b8">Yakin hapus top up <b style="color:#34d399">Rp ${parseInt(amount).toLocaleString('id-ID')}</b> milik <b style="color:#fff">${nama}</b>?<br><br>
               <span style="color:#f87171;font-size:.85rem;"><i class="bx bx-error"></i> Saldo member akan dikurangi kembali.</span></span>`,
        icon: 'warning', showCancelButton: true,
        confirmButtonText: '<i class="bx bx-trash"></i> Ya, Hapus!',
        cancelButtonText: 'Batal',
        confirmButtonColor: '#ef4444', cancelButtonColor: '#334155',
        background: '#1e293b', color: '#fff',
    }).then(r => { if (r.isConfirmed) window.location.href = url; });
}

function confirmBulkDelete() {
    const count = <?= $count_all ?>;
    const start = '<?= $start_date ?>';
    const end   = '<?= $end_date ?>';
    const type  = '<?= $view_type === "all" ? "semua kategori" : $view_type ?>';
    Swal.fire({
        title: '<i class="bx bx-error" style="color:#ef4444"></i> Hapus Massal',
        html: `<div style="text-align:left;color:#94a3b8;font-size:.9rem;line-height:1.8;">
            <b style="color:#f87171">${count} data</b> akan dihapus permanen:<br>
            📅 Periode: <b style="color:#fff">${start}</b> s/d <b style="color:#fff">${end}</b><br>
            📂 Kategori: <b style="color:#fff">${type}</b><br><br>
            <span style="color:#f87171;font-weight:700;">⚠ Tindakan ini TIDAK BISA dibatalkan!</span></div>`,
        icon: null, showCancelButton: true,
        confirmButtonText: '<i class="bx bx-trash"></i> Hapus Semua',
        cancelButtonText: 'Batal',
        confirmButtonColor: '#ef4444', cancelButtonColor: '#334155',
        background: '#1e293b', color: '#fff',
    }).then(r => { if (r.isConfirmed) document.getElementById('bulkDeleteForm').submit(); });
}

// ══════════════════════════════════════════════════
// MODAL TOP UP
// ══════════════════════════════════════════════════
function openTopupModal() {
    document.getElementById('modalTopup').classList.add('active');
    document.getElementById('tu_amount').value = '';
    document.getElementById('tu_member_id').value = '';
    document.getElementById('saldoPreview').classList.remove('show');
}

function closeTopupModal() {
    document.getElementById('modalTopup').classList.remove('active');
}

function handleTopupOverlay(e) {
    if (e.target === document.getElementById('modalTopup')) closeTopupModal();
}

function setTuAmount(val) {
    const inp = document.getElementById('tu_amount');
    inp.value = (parseInt(inp.value) || 0) + val;
    updateSaldoPreview();
}

function updateSaldoPreview() {
    const sel    = document.getElementById('tu_member_id');
    const amount = parseInt(document.getElementById('tu_amount').value) || 0;
    const opt    = sel.options[sel.selectedIndex];
    if (!opt || !opt.value || amount <= 0) {
        document.getElementById('saldoPreview').classList.remove('show');
        return;
    }
    const saldoNow = parseInt(opt.dataset.saldo) || 0;
    const after    = saldoNow + amount;
    document.getElementById('prev_current').textContent = 'Rp ' + saldoNow.toLocaleString('id-ID');
    document.getElementById('prev_add').textContent     = '+ Rp ' + amount.toLocaleString('id-ID');
    document.getElementById('prev_after').textContent   = 'Rp ' + after.toLocaleString('id-ID');
    document.getElementById('saldoPreview').classList.add('show');
}

// Pastikan filter tanggal ikut terbawa saat POST
document.getElementById('topupForm').addEventListener('submit', function(e) {
    const btn = document.getElementById('topupSubmitBtn');
    const memberId = document.getElementById('tu_member_id').value;
    const amount   = parseInt(document.getElementById('tu_amount').value);
    if (!memberId) { e.preventDefault(); Swal.fire({ title:'Pilih Member', text:'Harap pilih member terlebih dahulu.', icon:'warning', background:'#1e293b', color:'#fff' }); return; }
    if (!amount || amount < 1000) { e.preventDefault(); Swal.fire({ title:'Nominal Tidak Valid', text:'Masukkan nominal top up minimal Rp 1.000.', icon:'warning', background:'#1e293b', color:'#fff' }); return; }
    btn.disabled = true;
    btn.innerHTML = '<i class="bx bx-loader-alt bx-spin"></i> Menyimpan...';
    // Set redirect params
    this.action = `history.php?start_date=<?= $start_date ?>&end_date=<?= $end_date ?>&view_type=<?= $view_type ?>`;
});

// ══════════════════════════════════════════════════
// EXPORT MODAL
// ══════════════════════════════════════════════════
function openExportModal() {
    const p = new URLSearchParams(window.location.search);
    if (p.get('start_date')) document.getElementById('exp_start').value = p.get('start_date');
    if (p.get('end_date'))   document.getElementById('exp_end').value   = p.get('end_date');
    if (p.get('view_type'))  document.getElementById('exp_type').value  = p.get('view_type');
    document.getElementById('exportModal').classList.add('active');
}
function closeExportModal() { document.getElementById('exportModal').classList.remove('active'); }
function handleExportOverlay(e) { if (e.target === document.getElementById('exportModal')) closeExportModal(); }

function setShortcut(type) {
    const today = new Date();
    const fmt   = d => d.toISOString().split('T')[0];
    let s = today, e = today;
    if (type === 'yesterday') {
        const y = new Date(today); y.setDate(y.getDate() - 1); s = e = y;
    } else if (type === 'week') {
        const w = new Date(today); w.setDate(w.getDate() - 6); s = w;
    } else if (type === 'month') {
        s = new Date(today.getFullYear(), today.getMonth(), 1);
    } else if (type === 'lastmonth') {
        s = new Date(today.getFullYear(), today.getMonth() - 1, 1);
        e = new Date(today.getFullYear(), today.getMonth(), 0);
    }
    document.getElementById('exp_start').value = fmt(s);
    document.getElementById('exp_end').value   = fmt(e);
}

function doExport() {
    const s  = document.getElementById('exp_start').value;
    const e  = document.getElementById('exp_end').value;
    const t  = document.getElementById('exp_type').value;
    const op = encodeURIComponent(document.getElementById('exp_operator').value.trim() || 'Operator');
    if (!s || !e) { alert('Harap isi tanggal mulai dan selesai.'); return; }
    if (s > e)    { alert('Tanggal mulai tidak boleh lebih besar dari tanggal selesai.'); return; }
    window.open(`export_pdf.php?start_date=${s}&end_date=${e}&view_type=${t}&operator=${op}`, '_blank');
    closeExportModal();
}

document.addEventListener('keydown', e => {
    if (e.key === 'Escape') { closeExportModal(); closeTopupModal(); }
});

// ══════════════════════════════════════════════════
// KONFIRMASI BAYAR DARI HISTORY
// ══════════════════════════════════════════════════
const METODE_HISTORY = [
    { nama: 'Cash',         icon: 'bx-money',      color: '#10b981' },
    { nama: 'QRIS',         icon: 'bx-qr-scan',    color: '#06b6d4' },
    { nama: 'Transfer Bank',icon: 'bx-transfer',    color: '#8b5cf6' },
    { nama: 'Debit',        icon: 'bx-credit-card', color: '#f59e0b' },
];

function konfirmasiBayarHistory(trxId, tvName) {
    // Buat grid metode pembayaran
    let metodeBtns = METODE_HISTORY.map((m, i) =>
        `<button type="button" onclick="selectMetodeHistory(this,'${m.nama}')"
            style="padding:12px 8px;background:rgba(0,0,0,.3);border:1.5px solid rgba(255,255,255,.08);
                   border-radius:12px;cursor:pointer;color:#94a3b8;font-size:.75rem;font-weight:700;
                   display:flex;flex-direction:column;align-items:center;gap:6px;transition:all .2s;"
            data-method="${m.nama}" ${i===0?'class="selected-metode"':''}>
            <i class='bx ${m.icon}' style="font-size:1.4rem;color:${m.color};"></i>
            ${m.nama}
        </button>`
    ).join('');

    Swal.fire({
        title: `<i class="bx bx-wallet-alt" style="color:#10b981"></i> Konfirmasi Pembayaran`,
        html: `
            <div style="text-align:left;font-size:.9rem;color:#94a3b8;margin-bottom:16px;">
                <b style="color:#fff">${tvName}</b> — transaksi belum terbayar.
            </div>
            <div style="font-size:.72rem;color:#64748b;text-transform:uppercase;letter-spacing:1px;
                        font-weight:700;margin-bottom:10px;">Pilih metode pembayaran:</div>
            <div id="metode_history_grid" style="display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin-bottom:4px;">
                ${metodeBtns}
            </div>`,
        showCancelButton: true,
        confirmButtonText: '<i class="bx bx-check"></i> Konfirmasi Bayar',
        cancelButtonText: 'Batal',
        confirmButtonColor: '#10b981',
        cancelButtonColor: '#334155',
        background: '#1e293b',
        color: '#fff',
        didOpen: () => {
            // Set default selected
            const first = document.querySelector('#metode_history_grid button');
            if (first) applySelectedStyle(first);
        },
        preConfirm: () => {
            const selected = document.querySelector('#metode_history_grid button.selected-metode');
            return selected ? selected.dataset.method : 'Cash';
        }
    }).then(result => {
        if (!result.isConfirmed) return;
        const metode = result.value;

        const fd = new FormData();
        fd.append('action',         'update_payment_method');
        fd.append('trx_id',         trxId);
        fd.append('tv_id',          0); // tidak perlu tv_id untuk completed trx
        fd.append('payment_method', metode);
        fd.append('payment_status', 'paid');
        fd.append('ajax',           '1');

        fetch('process.php', { method: 'POST', body: fd })
            .then(r => r.json())
            .then(data => {
                if (data.status === 'success') {
                    Swal.fire({
                        title: '✓ Pembayaran Dikonfirmasi!',
                        text: `Metode: ${metode}`,
                        icon: 'success',
                        background: '#1e293b',
                        color: '#fff',
                        timer: 1500,
                        showConfirmButton: false
                    }).then(() => location.reload());
                } else {
                    Swal.fire({ title: 'Gagal', text: data.msg || 'Error', icon: 'error', background: '#1e293b', color: '#fff' });
                }
            })
            .catch(() => location.reload());
    });
}

function selectMetodeHistory(btn, nama) {
    document.querySelectorAll('#metode_history_grid button').forEach(b => {
        b.classList.remove('selected-metode');
        b.style.borderColor = 'rgba(255,255,255,.08)';
        b.style.background  = 'rgba(0,0,0,.3)';
        b.style.color       = '#94a3b8';
    });
    btn.classList.add('selected-metode');
    applySelectedStyle(btn);
}

function applySelectedStyle(btn) {
    btn.style.borderColor = '#06b6d4';
    btn.style.background  = 'rgba(6,182,212,.18)';
    btn.style.color       = '#06b6d4';
}


</script>

<?php
echo "</body></html>";
ob_end_flush();
?>