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

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

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

// Hapus satu transaksi billing
if (isset($_GET['delete_trx']) && is_numeric($_GET['delete_trx'])) {
    $del_id = (int)$_GET['delete_trx'];
    // Hapus FnB terkait
    mysqli_query($conn, "DELETE FROM orders_fnb WHERE trx_id = $del_id");
    // Hapus transaksi
    mysqli_query($conn, "DELETE FROM transactions WHERE id = $del_id AND status = 'completed'");
    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;
}

// Hapus satu FnB
if (isset($_GET['delete_fnb']) && is_numeric($_GET['delete_fnb'])) {
    $del_id = (int)$_GET['delete_fnb'];
    mysqli_query($conn, "DELETE FROM orders_fnb WHERE id = $del_id");
    mysqli_query($conn, "DELETE FROM snack_sales WHERE id = $del_id");
    write_log($conn, 'DELETE_FNB', "Hapus record FnB #$del_id");
    header("Location: history.php?" . http_build_query(array_diff_key($_GET, ['delete_fnb'=>''])));
    exit;
}

// Hapus satu topup
if (isset($_GET['delete_topup']) && is_numeric($_GET['delete_topup'])) {
    $del_id = (int)$_GET['delete_topup'];
    mysqli_query($conn, "DELETE FROM member_topups WHERE id = $del_id");
    write_log($conn, 'DELETE_TOPUP', "Hapus topup #$del_id");
    header("Location: history.php?" . http_build_query(array_diff_key($_GET, ['delete_topup'=>''])));
    exit;
}

// Hapus SEMUA data pada rentang tanggal
if (isset($_POST['bulk_delete'])) {
    $bd_start = $_POST['bd_start'] ?? date('Y-m-d');
    $bd_end   = $_POST['bd_end']   ?? date('Y-m-d');
    $bd_type  = $_POST['bd_type']  ?? 'all';

    $deleted_count = 0;

    if ($bd_type === 'all' || $bd_type === 'ps') {
        // Hapus FnB yang terkait transaksi pada rentang ini
        $trx_ids = mysqli_query($conn, "SELECT id FROM transactions WHERE DATE(end_time) BETWEEN '$bd_start' AND '$bd_end' AND status='completed'");
        while ($r = mysqli_fetch_assoc($trx_ids)) {
            mysqli_query($conn, "DELETE FROM orders_fnb WHERE trx_id = {$r['id']}");
        }
        $res = mysqli_query($conn, "DELETE FROM transactions WHERE DATE(end_time) BETWEEN '$bd_start' AND '$bd_end' AND status='completed'");
        $deleted_count += mysqli_affected_rows($conn);
    }

    if ($bd_type === 'all' || $bd_type === 'fnb') {
        mysqli_query($conn, "DELETE FROM orders_fnb WHERE DATE(created_at) BETWEEN '$bd_start' AND '$bd_end'");
        $deleted_count += mysqli_affected_rows($conn);
        mysqli_query($conn, "DELETE FROM snack_sales WHERE DATE(created_at) BETWEEN '$bd_start' AND '$bd_end'");
        $deleted_count += mysqli_affected_rows($conn);
    }

    if ($bd_type === 'all' || $bd_type === 'topup') {
        mysqli_query($conn, "DELETE FROM member_topups WHERE DATE(created_at) BETWEEN '$bd_start' AND '$bd_end'");
        $deleted_count += mysqli_affected_rows($conn);
    }

    write_log($conn, 'BULK_DELETE', "Hapus massal [$bd_type] dari $bd_start s/d $bd_end | $deleted_count records");
    header("Location: history.php?start_date=$bd_start&end_date=$bd_end&view_type=" . ($_GET['view_type'] ?? 'all') . "&deleted=$deleted_count");
    exit;
}

$deleted_msg = isset($_GET['deleted']) ? (int)$_GET['deleted'] : null;

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

// --- CEK STRUKTUR DATABASE ---
$check_packages = mysqli_query($conn, "SHOW TABLES LIKE 'packages'");
$has_packages_table = (mysqli_num_rows($check_packages) > 0);

$check_topup = mysqli_query($conn, "SHOW TABLES LIKE 'member_topups'");
$has_topup_table = (mysqli_num_rows($check_topup) > 0);

$check_col_paket = mysqli_query($conn, "SHOW COLUMNS FROM transactions LIKE 'paket_id'");
$has_paket_column = (mysqli_num_rows($check_col_paket) > 0);

$check_col_member = mysqli_query($conn, "SHOW COLUMNS FROM transactions LIKE 'member_id'");
$has_member_column = (mysqli_num_rows($check_col_member) > 0);

$check_col_stik = mysqli_query($conn, "SHOW COLUMNS FROM transactions LIKE 'stik_info'");
$has_stik_column = (mysqli_num_rows($check_col_stik) > 0);


// --- 1. QUERY PENDAPATAN 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";
} else {
    $select_fields .= ", 'Rental Regular' as nama_paket_dummy"; 
}

if ($has_member_column) {
    $select_fields .= ", m.nama_member";
    $joins .= " LEFT JOIN members m ON t.member_id = m.id";
} else {
    $select_fields .= ", NULL as nama_member";
}

if ($has_stik_column) {
    $select_fields .= ", t.stik_info";
} else {
    $select_fields .= ", '-' as stik_info";
}

$q_trans_sql = "SELECT $select_fields 
                FROM transactions t 
                $joins
                WHERE DATE(t.end_time) BETWEEN '$start_date' AND '$end_date' 
                AND t.status='completed' 
                ORDER BY t.end_time DESC";

$q_trans = mysqli_query($conn, $q_trans_sql);
$total_bill = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(total_bayar) as total FROM transactions WHERE DATE(end_time) BETWEEN '$start_date' AND '$end_date' AND status='completed'"))['total'] ?? 0;

// --- 2. QUERY PENDAPATAN F&B ---
$q_fnb_sql = "
    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 '$start_date' AND '$end_date'
    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 '$start_date' AND '$end_date'
    ORDER BY created_at DESC";
$q_fnb = mysqli_query($conn, $q_fnb_sql);
$t_fnb1 = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(total_harga) as total FROM orders_fnb WHERE DATE(created_at) BETWEEN '$start_date' AND '$end_date'"))['total'] ?? 0;
$t_fnb2 = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(total) as total FROM snack_sales WHERE DATE(created_at) BETWEEN '$start_date' AND '$end_date'"))['total'] ?? 0;
$total_fnb = $t_fnb1 + $t_fnb2;

// --- 3. QUERY PENDAPATAN TOP UP ---
$total_topup = 0;
$q_topup = false;
if($has_topup_table) {
    $q_topup_sql = "SELECT mt.*, m.nama_member FROM member_topups mt 
                    JOIN members m ON mt.member_id = m.id 
                    WHERE DATE(mt.created_at) BETWEEN '$start_date' AND '$end_date' ORDER BY mt.created_at DESC";
    $q_topup = mysqli_query($conn, $q_topup_sql);
    $total_topup = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as total FROM member_topups WHERE DATE(created_at) BETWEEN '$start_date' AND '$end_date'"))['total'] ?? 0;
}

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

// Count total records
$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;

// Reset pointer
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);
?>

<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;
    }
    .dashboard-container { display: flex; flex-direction: column; gap: 30px; padding-bottom: 50px; }
    .filter-bar { background: var(--glass-bg); border: 1px solid var(--glass-border); padding: 20px; border-radius: 16px; display: flex; flex-wrap: wrap; gap: 20px; 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; }
    .btn-filter { background: var(--gradient-primary); border: none; color: #fff; padding: 12px 25px; border-radius: 10px; font-weight: 700; cursor: pointer; height: 45px; }
    .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 20px; }
    .stat-card { background: var(--glass-bg); border: 1px solid var(--glass-border); padding: 25px; border-radius: 20px; position: relative; overflow: hidden; }
    .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-value { font-size: 1.8rem; font-weight: 800; color: #fff; margin-top: 5px; }
    .stat-title { color: var(--text-muted); font-size: 0.85rem; }
    .report-section { background: var(--glass-bg); border: 1px solid var(--glass-border); border-radius: 24px; overflow: hidden; backdrop-filter: blur(12px); }
    .section-header { padding: 25px; border-bottom: 1px solid var(--glass-border); background: rgba(255,255,255,0.02); display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 12px; }
    .section-title { font-size: 1.1rem; color: #fff; font-weight: 700; display: flex; align-items: center; gap: 10px; }
    .table-container { max-height: 500px; overflow-y: auto; }
    table { width: 100%; border-collapse: collapse; }
    th { text-align: left; padding: 15px 25px; color: var(--text-muted); font-size: 0.75rem; text-transform: uppercase; background: rgba(15, 23, 42, 0.5); position: sticky; top: 0; white-space:nowrap; }
    td { padding: 18px 25px; border-bottom: 1px solid var(--glass-border); color: #e2e8f0; font-size: 0.9rem; vertical-align: middle; }
    .money { font-family: 'JetBrains Mono', monospace; font-weight: 700; }
    .badge { padding: 4px 10px; border-radius: 6px; font-size: 0.75rem; font-weight: 700; }
    .badge-vip { background: rgba(139, 92, 246, 0.2); color: #c084fc; }

    /* Delete buttons */
    .btn-del {
        background: rgba(239, 68, 68, 0.1);
        border: 1px solid rgba(239, 68, 68, 0.2);
        color: #f87171;
        padding: 6px 10px;
        border-radius: 8px;
        cursor: pointer;
        font-size: 1rem;
        transition: all 0.2s;
        display: inline-flex;
        align-items: center;
        justify-content: center;
    }
    .btn-del:hover {
        background: rgba(239, 68, 68, 0.25);
        border-color: rgba(239, 68, 68, 0.5);
        color: #ef4444;
        transform: scale(1.05);
    }

    .btn-bulk-delete {
        background: rgba(239, 68, 68, 0.1);
        border: 1px solid rgba(239, 68, 68, 0.25);
        color: #f87171;
        padding: 10px 20px;
        border-radius: 12px;
        cursor: pointer;
        font-weight: 700;
        font-size: 0.82rem;
        transition: all 0.3s;
        display: inline-flex;
        align-items: center;
        gap: 8px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }
    .btn-bulk-delete:hover {
        background: rgba(239, 68, 68, 0.2);
        border-color: rgba(239, 68, 68, 0.5);
        box-shadow: 0 0 20px rgba(239, 68, 68, 0.15);
        transform: translateY(-1px);
    }

    .alert-deleted {
        background: rgba(239, 68, 68, 0.1);
        border: 1px solid rgba(239, 68, 68, 0.2);
        padding: 16px 22px;
        border-radius: 14px;
        color: #f87171;
        display: flex;
        align-items: center;
        gap: 12px;
        font-weight: 600;
        animation: fadeSlideIn 0.4s ease;
    }
    .alert-deleted i { font-size: 1.4rem; }
    @keyframes fadeSlideIn { from { opacity:0; transform:translateY(-8px); } to { opacity:1; transform:translateY(0); } }

    .record-count {
        font-size: 0.75rem;
        color: var(--text-muted);
        background: rgba(0,0,0,0.2);
        padding: 4px 10px;
        border-radius: 8px;
        font-weight: 600;
    }
</style>

<div class="dashboard-container">

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

    <?php if(!$has_stik_column): ?>
    <div style="background: rgba(245, 158, 11, 0.15); border: 1px solid rgba(245, 158, 11, 0.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 di tabel transaksi.
            <br><small>Laporan tetap berjalan, namun detail stik tidak tampil.</small>
        </div>
    </div>
    <?php endif; ?>

    <!-- FILTER SECTION -->
    <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">TAMPILKAN</button>
    </form>

    <!-- STATS CARDS -->
    <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>
        <div class="stat-card blue">
            <div class="stat-title">Pendapatan Rental</div>
            <div class="stat-value">Rp <?= number_format($total_bill) ?></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>
        <div class="stat-card green">
            <div class="stat-title">Deposit / Top Up</div>
            <div class="stat-value">Rp <?= number_format($total_topup) ?></div>
        </div>
    </div>

    <!-- BULK DELETE BUTTON -->
    <?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; ?>

    <!-- 1. 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 Digunakan</th>
                        <th>Durasi</th>
                        <th style="text-align:right;">Total</th>
                        <th style="text-align:center;width:50px;">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 = isset($row['nama_paket']) ? $row['nama_paket'] : "Rental " . ($durasi->h + ($durasi->days * 24)) . " Jam";
                            $del_params = $_GET;
                            $del_params['delete_trx'] = $row['id'];
                    ?>
                    <tr>
                        <td>
                            <div style="display:flex; flex-direction:column; gap:4px; font-size:0.8rem; 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;"><?= $row['nama_tv'] ?></td>
                        <td>
                            <div style="display:flex; flex-direction:column; gap:4px;">
                                <?php if(isset($row['nama_member']) && !empty($row['nama_member'])): ?>
                                    <span class="badge badge-vip"><i class='bx bxs-crown'></i> <?= $row['nama_member'] ?></span>
                                <?php else: ?>
                                    <span style="font-size:0.8rem;">Tamu Reguler</span>
                                <?php endif; ?>
                                <span style="font-size:0.75rem; color:var(--text-muted);"><?= $nama_paket_display ?></span>
                            </div>
                        </td>
                        <td>
                            <span style="font-size: 0.8rem; color: var(--text-muted); line-height: 1.6;">
                                <?= !empty($row['stik_info']) ? str_replace(',', '<br>', htmlspecialchars($row['stik_info'])) : '-' ?>
                            </span>
                        </td>
                        <td><?= $durasi->h ?>j <?= $durasi->i ?>m</td>
                        <td class="money" style="text-align:right; color:#60a5fa;">Rp <?= number_format($row['total_bayar']) ?></td>
                        <td style="text-align:center;">
                            <button class="btn-del" onclick="confirmDelete('history.php?<?= http_build_query($del_params) ?>', 'transaksi #<?= $row['id'] ?> (<?= $row['nama_tv'] ?>)')" title="Hapus">
                                <i class='bx bx-trash'></i>
                            </button>
                        </td>
                    </tr>
                    <?php endwhile; 
                    else: ?>
                    <tr><td colspan="7" style="text-align:center; padding:30px; color:#64748b;">Tidak ada data transaksi rental.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <!-- 2. 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:50px;">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><?= date('H:i', strtotime($sn['created_at'])) ?></td>
                        <td style="color:#fff;"><?= $sn['nama_barang'] ?></td>
                        <td>x<?= $sn['qty'] ?></td>
                        <td><?= $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;">Tidak ada penjualan F&B.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <!-- 3. 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>
            <span class="record-count"><?= $count_topup ?> data</span>
        </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;">Belum ada data topup.</div>
            <?php else: ?>
            <table>
                <thead><tr><th>Tanggal</th><th>Member</th><th style="text-align:right;">Nominal</th><th style="text-align:center;width:50px;">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><?= date('d/m H:i', strtotime($tu['created_at'])) ?></td>
                        <td style="color:#fff; font-weight:bold;"><?= $tu['nama_member'] ?></td>
                        <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="confirmDelete('history.php?<?= http_build_query($del_params_tu) ?>', 'topup <?= htmlspecialchars($tu['nama_member']) ?>')" title="Hapus">
                                <i class='bx bx-trash'></i>
                            </button>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

</div>

<!-- Hidden form untuk bulk delete -->
<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>

<script>
// Hapus satu record
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((result) => {
        if (result.isConfirmed) window.location.href = url;
    });
}

// Hapus semua data pada rentang tanggal
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((result) => {
        if (result.isConfirmed) {
            document.getElementById('bulkDeleteForm').submit();
        }
    });
}
</script>

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