<?php
// ==========================================================
// EXPORT_PDF.PHP — Export Laporan Keuangan ke PDF
// Escobar Billing System
// Menggunakan: Pure PHP HTML → Print PDF (tanpa library eksternal)
// Fitur:
//   - Filter tanggal bebas
//   - Tampilkan nama operator/shift
//   - Rincian Billing, F&B, Top Up
//   - Summary & Grand Total
// ==========================================================
ob_start();
include 'config.php';
checkLogin();

// ── PARAMETER ──────────────────────────────────────────────
$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';

// Nama operator — bisa dari URL (dikirim modal) atau dari session
$operator_name = !empty($_GET['operator']) ? htmlspecialchars(strip_tags($_GET['operator'])) : ($_SESSION['username'] ?? 'Admin');
$operator_role = $_SESSION['role'] ?? 'admin';

// Nama rental
$rental_name = get_setting($conn, 'app_name') ?: 'PS Rental';

// ── CEK STRUKTUR DB ─────────────────────────────────────────
$has_packages = mysqli_num_rows(mysqli_query($conn, "SHOW TABLES LIKE 'packages'")) > 0;
$has_topup    = mysqli_num_rows(mysqli_query($conn, "SHOW TABLES LIKE 'member_topups'")) > 0;
$has_paket    = mysqli_num_rows(mysqli_query($conn, "SHOW COLUMNS FROM transactions LIKE 'paket_id'")) > 0;
$has_member   = mysqli_num_rows(mysqli_query($conn, "SHOW COLUMNS FROM transactions LIKE 'member_id'")) > 0;
$has_stik     = mysqli_num_rows(mysqli_query($conn, "SHOW COLUMNS FROM transactions LIKE 'stik_info'")) > 0;

// ── QUERY BILLING ────────────────────────────────────────────
$sel = "t.*, tv.nama_tv";
$jn  = "JOIN tvs tv ON t.tv_id = tv.id";
if ($has_packages && $has_paket) { $sel .= ", p.nama_paket"; $jn .= " LEFT JOIN packages p ON t.paket_id = p.id"; }
if ($has_member)  { $sel .= ", m.nama_member"; $jn .= " LEFT JOIN members m ON t.member_id = m.id"; }
if ($has_stik)    { $sel .= ", t.stik_info"; }

$q_trans = mysqli_query($conn, "SELECT $sel FROM transactions t $jn
    WHERE DATE(t.end_time) BETWEEN '$start_date' AND '$end_date' AND t.status='completed'
    ORDER BY t.end_time ASC");
$total_bill = (float)(mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(total_bayar) as t FROM transactions WHERE DATE(end_time) BETWEEN '$start_date' AND '$end_date' AND status='completed'"))['t'] ?? 0);

// ── QUERY F&B ────────────────────────────────────────────────
$q_fnb = mysqli_query($conn, "
    SELECT o.id, o.created_at, o.nama_barang, o.qty, o.total_harga as total, tv.nama_tv as sumber
    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
    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 ASC");
$t1 = (float)(mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(total_harga) as t FROM orders_fnb WHERE DATE(created_at) BETWEEN '$start_date' AND '$end_date'"))['t'] ?? 0);
$t2 = (float)(mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(total) as t FROM snack_sales WHERE DATE(created_at) BETWEEN '$start_date' AND '$end_date'"))['t'] ?? 0);
$total_fnb = $t1 + $t2;

// ── QUERY TOP UP ─────────────────────────────────────────────
$total_topup = 0;
$q_topup = false;
if ($has_topup) {
    $q_topup = mysqli_query($conn, "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 ASC");
    $total_topup = (float)(mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(amount) as t FROM member_topups WHERE DATE(created_at) BETWEEN '$start_date' AND '$end_date'"))['t'] ?? 0);
}

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

// ── COUNT ─────────────────────────────────────────────────────
$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;

// Hitung total sesi per TV (untuk ringkasan)
$q_per_tv = mysqli_query($conn, "SELECT tv.nama_tv, COUNT(*) as jml, SUM(t.total_bayar) as total
    FROM transactions t JOIN tvs tv ON t.tv_id = tv.id
    WHERE DATE(t.end_time) BETWEEN '$start_date' AND '$end_date' AND t.status='completed'
    GROUP BY tv.id ORDER BY total DESC");

// Tanggal cetak
$print_time = date('d/m/Y H:i:s');
$label_period = ($start_date === $end_date)
    ? date('d F Y', strtotime($start_date))
    : date('d F Y', strtotime($start_date)) . ' — ' . date('d F Y', strtotime($end_date));

ob_end_clean();
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laporan Keuangan — <?= htmlspecialchars($rental_name) ?></title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
    font-family: 'Segoe UI', Arial, sans-serif;
    font-size: 11px;
    color: #1a1a2e;
    background: #f0f4f8;
}

/* ── PRINT STYLES ── */
@media print {
    body { background: #fff; }
    .no-print { display: none !important; }
    .page-break { page-break-before: always; }
    .report-wrapper { box-shadow: none !important; margin: 0 !important; border-radius: 0 !important; }
    @page { margin: 12mm 10mm; size: A4 portrait; }
}

/* ── PRINT BUTTON BAR ── */
.no-print {
    position: fixed;
    top: 0; left: 0; right: 0;
    z-index: 9999;
    background: #1e293b;
    padding: 12px 24px;
    display: flex;
    align-items: center;
    gap: 12px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.3);
}
.no-print h4 { color: #94a3b8; font-size: 12px; flex: 1; }
.btn-print {
    background: linear-gradient(135deg, #06b6d4, #0891b2);
    color: #000;
    border: none;
    padding: 9px 22px;
    border-radius: 8px;
    font-weight: 800;
    font-size: 12px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 7px;
}
.btn-back {
    background: rgba(255,255,255,0.1);
    color: #fff;
    border: 1px solid rgba(255,255,255,0.2);
    padding: 9px 18px;
    border-radius: 8px;
    font-size: 12px;
    cursor: pointer;
    text-decoration: none;
    display: flex;
    align-items: center;
    gap: 6px;
}
.btn-back:hover { background: rgba(255,255,255,0.18); }

/* ── LAYOUT ── */
.report-wrapper {
    max-width: 800px;
    margin: 60px auto 40px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 30px rgba(0,0,0,0.12);
    overflow: hidden;
}

/* ── HEADER ── */
.report-header {
    background: linear-gradient(135deg, #0f172a 0%, #1e3a5f 100%);
    padding: 28px 32px 22px;
    color: #fff;
    position: relative;
    overflow: hidden;
}
.report-header::after {
    content: '';
    position: absolute;
    bottom: -1px; left: 0; right: 0;
    height: 4px;
    background: linear-gradient(90deg, #06b6d4, #8b5cf6, #06b6d4);
}
.header-top { display: flex; justify-content: space-between; align-items: flex-start; }
.rental-name {
    font-size: 22px;
    font-weight: 900;
    letter-spacing: 2px;
    color: #06b6d4;
    text-shadow: 0 0 20px rgba(6,182,212,0.4);
}
.rental-sub { font-size: 10px; color: #64748b; letter-spacing: 3px; text-transform: uppercase; margin-top: 2px; }
.doc-label {
    text-align: right;
    font-size: 10px;
    color: #94a3b8;
}
.doc-label strong { display: block; font-size: 14px; color: #fff; letter-spacing: 1px; }

.header-info {
    margin-top: 18px;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
    background: rgba(0,0,0,0.25);
    padding: 14px 18px;
    border-radius: 8px;
    border: 1px solid rgba(255,255,255,0.07);
}
.hinfo-item { }
.hinfo-label { font-size: 9px; color: #64748b; text-transform: uppercase; letter-spacing: 1px; }
.hinfo-val { font-size: 12px; font-weight: 700; color: #e2e8f0; margin-top: 2px; }
.hinfo-val.accent { color: #06b6d4; }

/* ── SUMMARY CARDS ── */
.summary-row {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 0;
    border-bottom: 2px solid #e2e8f0;
}
.sum-card {
    padding: 16px 18px;
    border-right: 1px solid #e2e8f0;
    text-align: center;
}
.sum-card:last-child { border-right: none; }
.sum-label { font-size: 9px; color: #64748b; text-transform: uppercase; letter-spacing: 1px; font-weight: 700; }
.sum-val { font-size: 15px; font-weight: 900; margin-top: 4px; }
.sum-val.blue  { color: #6366f1; }
.sum-val.orange{ color: #f59e0b; }
.sum-val.green { color: #10b981; }
.sum-val.purple{ color: #8b5cf6; }
.sum-count { font-size: 9px; color: #94a3b8; margin-top: 2px; }

/* ── SECTION ── */
.section {
    padding: 0;
    border-bottom: 1px solid #e8edf3;
}
.section:last-child { border-bottom: none; }
.section-title {
    padding: 12px 20px;
    background: #f8fafc;
    border-bottom: 1px solid #e8edf3;
    font-size: 10px;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: 1.5px;
    color: #475569;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.section-title span { color: #94a3b8; font-weight: 600; font-size: 9px; }

/* ── TABLE ── */
table { width: 100%; border-collapse: collapse; font-size: 10px; }
thead th {
    padding: 8px 12px;
    background: #1e293b;
    color: #94a3b8;
    font-size: 8.5px;
    text-transform: uppercase;
    letter-spacing: 0.8px;
    text-align: left;
    white-space: nowrap;
}
thead th.right { text-align: right; }
tbody tr:nth-child(even) { background: #f8fafc; }
tbody tr:hover { background: #f0f9ff; }
td {
    padding: 8px 12px;
    border-bottom: 1px solid #f1f5f9;
    color: #334155;
    vertical-align: top;
}
td.right { text-align: right; font-family: 'Courier New', monospace; font-weight: 700; }
td.money { color: #1e40af; }
td.money-green { color: #065f46; text-align: right; font-family: 'Courier New', monospace; font-weight: 700; }
td.money-purple { color: #5b21b6; text-align: right; font-family: 'Courier New', monospace; font-weight: 700; }
td.tv-name { font-weight: 800; color: #0f172a; }
td.small { font-size: 9px; color: #64748b; }

.badge {
    display: inline-block;
    padding: 2px 7px;
    border-radius: 4px;
    font-size: 8.5px;
    font-weight: 700;
}
.badge-vip { background: rgba(139,92,246,.12); color: #7c3aed; }
.badge-tamu { background: rgba(100,116,139,.1); color: #475569; }
.badge-fixed { background: rgba(99,102,241,.1); color: #4338ca; }
.badge-open { background: rgba(16,185,129,.1); color: #065f46; }
.no-data { padding: 20px; text-align: center; color: #94a3b8; font-style: italic; }

/* ── PER TV SUMMARY ── */
.tv-summary-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 8px;
    padding: 14px 20px;
}
.tv-item {
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 6px;
    padding: 10px 12px;
}
.tv-item-name { font-size: 10px; font-weight: 800; color: #0f172a; }
.tv-item-count { font-size: 9px; color: #64748b; margin-top: 1px; }
.tv-item-total { font-size: 11px; font-weight: 900; color: #6366f1; margin-top: 4px; font-family: 'Courier New', monospace; }

/* ── FOOTER ── */
.report-footer {
    background: #f8fafc;
    padding: 18px 24px;
    border-top: 2px solid #e2e8f0;
}
.grand-total-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #0f172a;
    color: #fff;
    padding: 14px 20px;
    border-radius: 8px;
    margin-bottom: 14px;
}
.gt-label { font-size: 11px; font-weight: 700; letter-spacing: 1px; text-transform: uppercase; color: #94a3b8; }
.gt-value { font-size: 20px; font-weight: 900; color: #06b6d4; font-family: 'Courier New', monospace; }

.sign-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin-top: 16px;
}
.sign-box {
    border: 1px solid #e2e8f0;
    border-radius: 6px;
    padding: 12px 16px;
    text-align: center;
}
.sign-label { font-size: 9px; text-transform: uppercase; letter-spacing: 1px; color: #64748b; font-weight: 700; }
.sign-space { height: 50px; }
.sign-name { font-size: 11px; font-weight: 800; color: #0f172a; border-top: 1px solid #cbd5e1; padding-top: 6px; margin-top: 4px; }
.sign-role { font-size: 9px; color: #64748b; }

.watermark-row {
    margin-top: 12px;
    text-align: center;
    font-size: 9px;
    color: #cbd5e1;
}
</style>
</head>
<body>

<!-- ── PRINT BAR (tidak ikut print) ── -->
<div class="no-print">
    <h4>📄 Preview Laporan — Siap Dicetak / Disimpan sebagai PDF</h4>
    <a href="history.php?start_date=<?= $start_date ?>&end_date=<?= $end_date ?>&view_type=<?= $view_type ?>" class="btn-back">← Kembali</a>
    <button class="btn-print" onclick="window.print()">🖨 Cetak / Simpan PDF</button>
</div>

<!-- ── LAPORAN ── -->
<div class="report-wrapper">

    <!-- HEADER -->
    <div class="report-header">
        <div class="header-top">
            <div>
                <div class="rental-name"><?= strtoupper(htmlspecialchars($rental_name)) ?></div>
                <div class="rental-sub">PS Rental Management System</div>
            </div>
            <div class="doc-label">
                <strong>LAPORAN KEUANGAN</strong>
                Dicetak: <?= $print_time ?><br>
                Oleh: <?= htmlspecialchars(strtoupper($operator_name)) ?>
            </div>
        </div>
        <div class="header-info">
            <div class="hinfo-item">
                <div class="hinfo-label">Periode Laporan</div>
                <div class="hinfo-val accent"><?= $label_period ?></div>
            </div>
            <div class="hinfo-item">
                <div class="hinfo-label">Operator / Shift</div>
                <div class="hinfo-val"><?= htmlspecialchars($operator_name) ?></div>
            </div>
            <div class="hinfo-item">
                <div class="hinfo-label">Kategori</div>
                <div class="hinfo-val"><?php
                    $cat_label = ['all'=>'Semua Data','ps'=>'Billing Rental','fnb'=>'F&B','topup'=>'Top Up Member'];
                    echo $cat_label[$view_type] ?? 'Semua Data';
                ?></div>
            </div>
        </div>
    </div>

    <!-- SUMMARY CARDS -->
    <div class="summary-row">
        <div class="sum-card">
            <div class="sum-label">Pendapatan Rental</div>
            <div class="sum-val blue">Rp <?= number_format($total_bill, 0, ',', '.') ?></div>
            <div class="sum-count"><?= $count_trx ?> transaksi</div>
        </div>
        <div class="sum-card">
            <div class="sum-label">Penjualan F&B</div>
            <div class="sum-val orange">Rp <?= number_format($total_fnb, 0, ',', '.') ?></div>
            <div class="sum-count"><?= $count_fnb ?> item terjual</div>
        </div>
        <div class="sum-card">
            <div class="sum-label">Top Up Member</div>
            <div class="sum-val green">Rp <?= number_format($total_topup, 0, ',', '.') ?></div>
            <div class="sum-count"><?= $count_topup ?> transaksi</div>
        </div>
        <div class="sum-card">
            <div class="sum-label">Grand Total Bersih</div>
            <div class="sum-val purple">Rp <?= number_format($grand_total, 0, ',', '.') ?></div>
            <div class="sum-count"><?= $count_trx + $count_fnb + $count_topup ?> total record</div>
        </div>
    </div>

    <!-- RINGKASAN PER TV -->
    <?php if ($q_per_tv && mysqli_num_rows($q_per_tv) > 0): ?>
    <div class="section">
        <div class="section-title">📊 Ringkasan Per Unit TV <span><?= mysqli_num_rows($q_per_tv) ?> unit aktif</span></div>
        <div class="tv-summary-grid">
            <?php while ($tv = mysqli_fetch_assoc($q_per_tv)): ?>
            <div class="tv-item">
                <div class="tv-item-name"><?= htmlspecialchars($tv['nama_tv']) ?></div>
                <div class="tv-item-count"><?= $tv['jml'] ?> sesi selesai</div>
                <div class="tv-item-total">Rp <?= number_format($tv['total'], 0, ',', '.') ?></div>
            </div>
            <?php endwhile; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- TABEL BILLING -->
    <?php if ($view_type === 'all' || $view_type === 'ps'): ?>
    <div class="section">
        <div class="section-title">🎮 Riwayat Billing Rental <span><?= $count_trx ?> transaksi</span></div>
        <?php if ($count_trx > 0): ?>
        <table>
            <thead>
                <tr>
                    <th style="width:30px;">#</th>
                    <th>Waktu Mulai</th>
                    <th>Waktu Selesai</th>
                    <th>Unit TV</th>
                    <th>Member / Tamu</th>
                    <th>Paket</th>
                    <th>Durasi</th>
                    <?php if ($has_stik): ?><th>Stik</th><?php endif; ?>
                    <th class="right">Total</th>
                </tr>
            </thead>
            <tbody>
            <?php
            $no = 1;
            while ($row = mysqli_fetch_assoc($q_trans)):
                $dur = (new DateTime($row['start_time']))->diff(new DateTime($row['end_time']));
                $dur_str = '';
                if ($dur->h > 0) $dur_str .= $dur->h . 'j ';
                $dur_str .= $dur->i . 'm';
                $nama_paket = isset($row['nama_paket']) ? $row['nama_paket'] : ($row['jenis_paket'] === 'open' ? 'Open Bill' : 'Rental');
            ?>
                <tr>
                    <td class="small"><?= $no++ ?></td>
                    <td class="small"><?= date('d/m H:i', strtotime($row['start_time'])) ?></td>
                    <td class="small"><?= date('d/m H:i', strtotime($row['end_time'])) ?></td>
                    <td class="tv-name"><?= htmlspecialchars($row['nama_tv']) ?></td>
                    <td>
                        <?php if (!empty($row['nama_member'])): ?>
                            <span class="badge badge-vip">★ <?= htmlspecialchars($row['nama_member']) ?></span>
                        <?php else: ?>
                            <span class="badge badge-tamu">Tamu</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <span class="badge <?= ($row['jenis_paket'] ?? '') === 'open' ? 'badge-open' : 'badge-fixed' ?>">
                            <?= htmlspecialchars($nama_paket) ?>
                        </span>
                    </td>
                    <td class="small"><?= $dur_str ?></td>
                    <?php if ($has_stik): ?>
                    <td class="small"><?= !empty($row['stik_info']) ? htmlspecialchars($row['stik_info']) : '-' ?></td>
                    <?php endif; ?>
                    <td class="money right">Rp <?= number_format($row['total_bayar'], 0, ',', '.') ?></td>
                </tr>
            <?php endwhile; ?>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="<?= 8 + ($has_stik ? 1 : 0) ?>" style="text-align:right;padding:10px 12px;font-weight:800;color:#334155;background:#f0f9ff;">Subtotal Rental:</td>
                    <td class="money right" style="background:#f0f9ff;font-size:12px;">Rp <?= number_format($total_bill, 0, ',', '.') ?></td>
                </tr>
            </tfoot>
        </table>
        <?php else: ?>
        <div class="no-data">Tidak ada data billing rental pada periode ini.</div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <!-- TABEL F&B -->
    <?php if ($view_type === 'all' || $view_type === 'fnb'): ?>
    <div class="section <?= $view_type === 'all' ? 'page-break' : '' ?>">
        <div class="section-title">🍔 Riwayat Penjualan F&B <span><?= $count_fnb ?> item</span></div>
        <?php if ($count_fnb > 0): ?>
        <table>
            <thead>
                <tr>
                    <th style="width:30px;">#</th>
                    <th>Waktu</th>
                    <th>Nama Item</th>
                    <th class="right">Qty</th>
                    <th>Sumber / Unit</th>
                    <th class="right">Subtotal</th>
                </tr>
            </thead>
            <tbody>
            <?php
            $no = 1;
            while ($sn = mysqli_fetch_assoc($q_fnb)):
            ?>
                <tr>
                    <td class="small"><?= $no++ ?></td>
                    <td class="small"><?= date('d/m H:i', strtotime($sn['created_at'])) ?></td>
                    <td style="font-weight:600;"><?= htmlspecialchars($sn['nama_barang']) ?></td>
                    <td class="right small">x<?= $sn['qty'] ?></td>
                    <td class="small"><?= htmlspecialchars($sn['sumber']) ?></td>
                    <td class="money-green">Rp <?= number_format($sn['total'], 0, ',', '.') ?></td>
                </tr>
            <?php endwhile; ?>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="5" style="text-align:right;padding:10px 12px;font-weight:800;color:#334155;background:#f0fdf4;">Subtotal F&B:</td>
                    <td class="money-green" style="background:#f0fdf4;font-size:12px;">Rp <?= number_format($total_fnb, 0, ',', '.') ?></td>
                </tr>
            </tfoot>
        </table>
        <?php else: ?>
        <div class="no-data">Tidak ada penjualan F&B pada periode ini.</div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <!-- TABEL TOP UP -->
    <?php if (($view_type === 'all' || $view_type === 'topup') && $has_topup): ?>
    <div class="section">
        <div class="section-title">💳 Riwayat Top Up Member <span><?= $count_topup ?> transaksi</span></div>
        <?php if ($q_topup && $count_topup > 0): ?>
        <table>
            <thead>
                <tr>
                    <th style="width:30px;">#</th>
                    <th>Tanggal & Waktu</th>
                    <th>Nama Member</th>
                    <th class="right">Nominal Top Up</th>
                </tr>
            </thead>
            <tbody>
            <?php
            $no = 1;
            while ($tu = mysqli_fetch_assoc($q_topup)):
            ?>
                <tr>
                    <td class="small"><?= $no++ ?></td>
                    <td class="small"><?= date('d/m/Y H:i', strtotime($tu['created_at'])) ?></td>
                    <td style="font-weight:700;">★ <?= htmlspecialchars($tu['nama_member']) ?></td>
                    <td class="money-purple">+ Rp <?= number_format($tu['amount'], 0, ',', '.') ?></td>
                </tr>
            <?php endwhile; ?>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="3" style="text-align:right;padding:10px 12px;font-weight:800;color:#334155;background:#faf5ff;">Subtotal Top Up:</td>
                    <td class="money-purple" style="background:#faf5ff;font-size:12px;">Rp <?= number_format($total_topup, 0, ',', '.') ?></td>
                </tr>
            </tfoot>
        </table>
        <?php else: ?>
        <div class="no-data">Tidak ada data top up pada periode ini.</div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <!-- FOOTER -->
    <div class="report-footer">
        <div class="grand-total-row">
            <div>
                <div class="gt-label">Grand Total Pendapatan</div>
                <div style="font-size:9px;color:#475569;margin-top:2px;">Periode: <?= $label_period ?></div>
            </div>
            <div class="gt-value">Rp <?= number_format($grand_total, 0, ',', '.') ?></div>
        </div>

        <div class="sign-row">
            <div class="sign-box">
                <div class="sign-label">Mengetahui / Pemilik</div>
                <div class="sign-space"></div>
                <div class="sign-name">(____________________)</div>
                <div class="sign-role">Pemilik / Manager</div>
            </div>
            <div class="sign-box">
                <div class="sign-label">Dibuat Oleh / Operator</div>
                <div class="sign-space"></div>
                <div class="sign-name"><?= htmlspecialchars($operator_name) ?></div>
                <div class="sign-role"><?= ucfirst($operator_role) ?> — <?= $print_time ?></div>
            </div>
        </div>

        <div class="watermark-row">
            Dokumen ini digenerate otomatis oleh <?= htmlspecialchars($rental_name) ?> · Escobar Billing System v3.0
        </div>
    </div>

</div><!-- /report-wrapper -->

<script>
// Auto trigger print dialog jika ada parameter ?autoprint=1
if (new URLSearchParams(window.location.search).get('autoprint') === '1') {
    window.addEventListener('load', () => setTimeout(() => window.print(), 500));
}
</script>
</body>
</html>