<?php
require 'config.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$mode = $_GET['mode'] ?? 'daily';
$date = $_GET['date'] ?? date('Y-m-d');
$bulan = isset($_GET['bulan']) ? (int)$_GET['bulan'] : (int)date('m');
$tahun = isset($_GET['tahun']) ? (int)$_GET['tahun'] : (int)date('Y');

switch ($mode) {
    case 'daily':
        $title_periode = date('d F Y', strtotime($date));
        $stmt = $pdo->prepare("SELECT * FROM transactions WHERE DATE(created_at) = ? ORDER BY created_at ASC");
        $stmt->execute([$date]);
        break;
    case 'weekly':
        $start = date('Y-m-d', strtotime('monday this week'));
        $end   = date('Y-m-d', strtotime('sunday this week'));
        $title_periode = date('d M', strtotime($start)) . ' - ' . date('d M Y', strtotime($end));
        $stmt = $pdo->prepare("SELECT * FROM transactions WHERE DATE(created_at) BETWEEN ? AND ? ORDER BY created_at ASC");
        $stmt->execute([$start, $end]);
        break;
    case 'monthly':
        $title_periode = date('F Y', mktime(0,0,0,$bulan,1,$tahun));
        $stmt = $pdo->prepare("SELECT * FROM transactions WHERE YEAR(created_at)=? AND MONTH(created_at)=? ORDER BY created_at ASC");
        $stmt->execute([$tahun, $bulan]);
        break;
    default:
        $title_periode = 'Semua Periode';
        $stmt = $pdo->query("SELECT * FROM transactions ORDER BY created_at ASC");
}

$transactions = $stmt->fetchAll();

$total_transaksi = count($transactions);
$total_omzet = 0;
$total_dinein = $total_takeaway = $total_catering = $total_gojek = $total_grab = $total_shopee = $total_mixed = 0;
$total_diskon = 0;
$total_fee = 0;
$total_subtotal = 0;

$daily_groups = [];
foreach ($transactions as $row) {
    $total_omzet    += (int)$row['total'];
    $total_diskon   += (int)$row['discount'];
    $total_fee      += (int)$row['takeaway_fee'];
    $total_subtotal += (int)$row['subtotal'];
    
    $dt = date('Y-m-d', strtotime($row['created_at']));
    if (!isset($daily_groups[$dt])) {
        $daily_groups[$dt] = ['count' => 0, 'total' => 0, 'discount' => 0, 'fee' => 0];
    }
    $daily_groups[$dt]['count']++;
    $daily_groups[$dt]['total']    += (int)$row['total'];
    $daily_groups[$dt]['discount'] += (int)$row['discount'];
    $daily_groups[$dt]['fee']      += (int)$row['takeaway_fee'];
    
    if ($row['order_type'] == 'dinein') $total_dinein++;
    elseif ($row['order_type'] == 'takeaway') $total_takeaway++;
    elseif ($row['order_type'] == 'catering') $total_catering++;
    elseif ($row['order_type'] == 'gojek') $total_gojek++;
    elseif ($row['order_type'] == 'grab') $total_grab++;
    elseif ($row['order_type'] == 'shopee') $total_shopee++;
    else $total_mixed++;
}
ksort($daily_groups);

$rata_rata = $total_transaksi > 0 ? round($total_omzet / $total_transaksi) : 0;
$net_profit = $total_omzet - $total_diskon;

$mode_label = ['daily' => 'HARIAN', 'weekly' => 'MINGGUAN', 'monthly' => 'BULANAN'][$mode] ?? strtoupper($mode);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <link rel="icon" href="favicon.ico" type="image/x-icon">
    <meta charset="UTF-8">
    <title>Laporan <?= $mode_label ?> | GoldenWok Resto</title>
    <style>
        @page { size: A4; margin: 10mm 12mm; }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
            font-size: 11px; color: #1e1e2e;
            background: #fff;
            -webkit-print-color-adjust: exact; print-color-adjust: exact;
            padding: 0 4px;
        }

        /* ====== HEADER ====== */
        .report-header {
            display: flex; align-items: center; justify-content: space-between;
            padding-bottom: 12px; margin-bottom: 14px;
            border-bottom: 3px solid #1a1a2e;
        }
        .brand {}
        .brand h1 { font-size: 22px; font-weight: 900; letter-spacing: 2px; color: #1a1a2e; line-height: 1; }
        .brand .tagline { font-size: 9px; color: #888; letter-spacing: 3px; text-transform: uppercase; margin-top: 2px; }
        .brand .addr { font-size: 9px; color: #999; margin-top: 1px; }
        .report-badge {
            text-align: right;
        }
        .report-badge .label {
            display: inline-block; background: #1a1a2e; color: #c8a951;
            padding: 4px 14px; border-radius: 4px; font-size: 10px;
            font-weight: 700; letter-spacing: 2px;
        }
        .report-badge .periode { font-size: 13px; font-weight: 800; color: #1a1a2e; margin-top: 6px; }
        .report-badge .generated { font-size: 8px; color: #aaa; margin-top: 2px; }

        /* ====== SUMMARY CARDS ====== */
        .cards { display: flex; gap: 10px; margin-bottom: 16px; }
        .card {
            flex: 1; border-radius: 10px; padding: 14px 16px;
            text-align: center; position: relative; overflow: hidden;
        }
        .card::before {
            content: ''; position: absolute; top: 0; left: 0; right: 0; height: 3px;
        }
        .card.dark   { background: #fafafa; border: 1.5px solid #e8e8e8; }
        .card.dark::before { background: #1a1a2e; }
        .card.gold   { background: #fffdf5; border: 1.5px solid #f0e6c0; }
        .card.gold::before { background: #c8a951; }
        .card.green  { background: #f5fdf7; border: 1.5px solid #c8e6d0; }
        .card.green::before { background: #16a34a; }
        .card.blue   { background: #f5f8ff; border: 1.5px solid #c8d8f0; }
        .card.blue::before { background: #2563eb; }
        .card .icon  { font-size: 18px; margin-bottom: 4px; }
        .card .title { font-size: 8px; text-transform: uppercase; letter-spacing: 1.5px; color: #888; font-weight: 600; }
        .card .value { font-size: 20px; font-weight: 900; margin: 2px 0; }
        .card.dark .value  { color: #1a1a2e; }
        .card.gold .value  { color: #b8941f; }
        .card.green .value { color: #16a34a; }
        .card.blue .value  { color: #2563eb; }
        .card .sub   { font-size: 9px; color: #aaa; }

        /* ====== TYPE PILLS ====== */
        .type-pills { display: flex; gap: 8px; justify-content: center; margin-bottom: 16px; }
        .type-pill {
            display: flex; align-items: center; gap: 5px;
            padding: 6px 14px; border-radius: 20px;
            font-size: 10px; font-weight: 600;
        }
        .type-pill.dinein   { background: #eff6ff; color: #1d4ed8; border: 1px solid #bfdbfe; }
        .type-pill.takeaway { background: #f0fdfa; color: #0f766e; border: 1px solid #99f6e4; }
        .type-pill.catering { background: #f5f3ff; color: #6d28d9; border: 1px solid #ddd6fe; }
.type-pill.gojek   { background: #e6ffe6; color: #00AA13; border: 1px solid #b3ffb3; }
.type-pill.grab    { background: #e6fff0; color: #00B14F; border: 1px solid #b3ffcc; }
.type-pill.shopee  { background: #fff0ed; color: #EE4D2D; border: 1px solid #ffc9bf; }
        .type-pill.mixed    { background: #fffbeb; color: #92400e; border: 1px solid #fde68a; }
        .type-pill .count { font-size: 14px; font-weight: 800; }

        /* ====== SECTION HEADER ====== */
        .section-title {
            display: flex; align-items: center; gap: 10px;
            font-size: 12px; font-weight: 800; color: #1a1a2e;
            margin: 20px 0 10px 0; padding-bottom: 6px;
            border-bottom: 2px solid #1a1a2e;
        }
        .section-title .dot { width: 8px; height: 8px; background: #c8a951; border-radius: 50%; }

        /* ====== TABLES ====== */
        table { width: 100%; border-collapse: collapse; font-size: 10px; }
        thead th {
            background: #f5f5f5; padding: 7px 8px; text-align: left;
            font-size: 8px; text-transform: uppercase; letter-spacing: 1px;
            color: #666; border-bottom: 2px solid #ddd;
        }
        tbody td { padding: 7px 8px; border-bottom: 1px solid #f0f0f0; }
        tbody tr:nth-child(even) td { background: #fafafa; }
        tbody tr:hover td { background: #fffef5; }
        .t-right { text-align: right; }
        .t-center { text-align: center; }
        .fw-bold { font-weight: 700; }
        .fw-mono { font-family: 'Consolas', 'Courier New', monospace; font-size: 9px; }
        .text-muted { color: #999; }
        .text-red { color: #dc2626; }
        .text-amber { color: #92400e; }

        .grand-row td {
            font-weight: 800; font-size: 12px;
            background: #1a1a2e !important; color: #c8a951 !important;
            border: none; padding: 10px 8px;
        }

        /* ====== MINI TABLE (daily recap) ====== */
        .mini-table { font-size: 10px; margin-bottom: 0; }
        .mini-table thead th { font-size: 8px; padding: 5px 6px; }
        .mini-table tbody td { padding: 5px 6px; }

        /* ====== BADGE ====== */
        .badge {
            display: inline-block; padding: 3px 10px; border-radius: 12px;
            font-size: 8px; font-weight: 700; letter-spacing: 0.5px;
        }
        .badge.dinein   { background: #eff6ff; color: #1d4ed8; }
        .badge.takeaway { background: #f0fdfa; color: #0f766e; }
        .badge.catering { background: #f5f3ff; color: #6d28d9; }
.badge.gojek   { background: #e6ffe6; color: #00AA13; }
.badge.grab    { background: #e6fff0; color: #00B14F; }
.badge.shopee  { background: #fff0ed; color: #EE4D2D; }
        .badge.mixed    { background: #fffbeb; color: #92400e; }

        /* ====== FOOTER ====== */
        .report-footer {
            margin-top: 24px; padding-top: 12px;
            border-top: 2px solid #e0e0e0;
            display: flex; justify-content: space-between; align-items: flex-end;
            font-size: 9px; color: #999;
        }
        .footer-right { text-align: right; }
        .signature-line { margin-top: 20px; }
        .signature-line .line { width: 120px; border-bottom: 1px solid #999; margin-bottom: 3px; }
        .signature-line .name { font-weight: 700; color: #555; font-size: 10px; }

        /* ====== PRINT & BUTTONS ====== */
        @media print { .no-print { display: none !important; } }
        .toolbar {
            text-align: center; margin-bottom: 12px;
            display: flex; gap: 8px; justify-content: center;
        }
        .btn {
            padding: 9px 24px; border: none; border-radius: 8px;
            font-size: 12px; font-weight: 700; cursor: pointer;
            font-family: inherit; transition: all .15s;
        }
        .btn-dark  { background: #1a1a2e; color: #fff; }
        .btn-dark:hover { background: #2d2d4a; }
        .btn-green { background: #16a34a; color: #fff; }
        .btn-green:hover { background: #15803d; }
    </style>
</head>
<body>

<div class="toolbar no-print">
    <button onclick="window.print()" class="btn btn-dark">Cetak Rekapan</button>
    <button onclick="saveReportImage()" class="btn btn-green">Simpan Gambar</button>
</div>

<!-- ==================== HEADER ==================== -->
<div class="report-header">
    <div class="brand">
        <h1>GOLDENWOK RESTO</h1>
        <div class="tagline">Laporan <?= $mode_label ?></div>
        <div class="addr">Jl. Ciater, Palapa &bull; Tangerang Selatan</div>
    </div>
    <div class="report-badge">
        <div class="label"><?= $mode_label ?></div>
        <div class="periode"><?= $title_periode ?></div>
        <div class="generated">Dibuat: <?= date('d/m/Y H:i') ?></div>
    </div>
</div>

<!-- ==================== SUMMARY CARDS ==================== -->
<div class="cards">
    <div class="card dark">
        <div class="icon">&#x1F4CB;</div>
        <div class="title">Total Transaksi</div>
        <div class="value"><?= $total_transaksi ?></div>
        <div class="sub">transaksi</div>
    </div>
    <div class="card gold">
        <div class="icon">&#x1F4B0;</div>
        <div class="title">Total Omzet</div>
        <div class="value">Rp <?= number_format($total_omzet) ?></div>
        <div class="sub">kotor</div>
    </div>
    <div class="card green">
        <div class="icon">&#x1F4C8;</div>
        <div class="title">Net Profit</div>
        <div class="value">Rp <?= number_format($net_profit) ?></div>
        <div class="sub">setelah diskon</div>
    </div>
    <div class="card blue">
        <div class="icon">&#x1F4CA;</div>
        <div class="title">Rata-rata / Transaksi</div>
        <div class="value">Rp <?= number_format($rata_rata) ?></div>
        <div class="sub">per transaksi</div>
    </div>
</div>

<!-- ==================== TYPE BREAKDOWN ==================== -->
<div class="type-pills">
    <div class="type-pill dinein">
        &#x1F37D; Dine In <span class="count"><?= $total_dinein ?></span>
    </div>
    <div class="type-pill takeaway">
        &#x1F6CD; Take Away <span class="count"><?= $total_takeaway ?></span>
    </div>
    <div class="type-pill catering">
        &#x1F4E6; Catering <span class="count"><?= $total_catering ?></span>
    </div>
    <?php if ($total_mixed > 0): ?>
    <div class="type-pill mixed">
        &#x1F504; Mixed <span class="count"><?= $total_mixed ?></span>
    </div>
    <?php endif; ?>
</div>

<!-- ==================== REKAPAN HARIAN ==================== -->
<?php if ($mode !== 'daily' && count($daily_groups) > 1): ?>
<div class="section-title"><span class="dot"></span> REKAPAN PER TANGGAL</div>
<table class="mini-table">
    <thead>
        <tr>
            <th>Tanggal</th>
            <th class="t-center">Transaksi</th>
            <th class="t-right">Omzet</th>
            <th class="t-right">Diskon</th>
            <th class="t-right">Fee</th>
            <th class="t-right fw-bold">Net</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($daily_groups as $dt => $dg): 
            $net = $dg['total'];
        ?>
        <tr>
            <td class="fw-bold"><?= date('D, d M Y', strtotime($dt)) ?></td>
            <td class="t-center"><?= $dg['count'] ?></td>
            <td class="t-right">Rp <?= number_format($dg['total'] + $dg['discount']) ?></td>
            <td class="t-right text-red"><?= $dg['discount'] > 0 ? '-Rp '.number_format($dg['discount']) : '-' ?></td>
            <td class="t-right text-amber"><?= $dg['fee'] > 0 ? 'Rp '.number_format($dg['fee']) : '-' ?></td>
            <td class="t-right fw-bold">Rp <?= number_format($net) ?></td>
        </tr>
        <?php endforeach; ?>
        <tr class="grand-row">
            <td>TOTAL</td>
            <td class="t-center"><?= $total_transaksi ?></td>
            <td class="t-right">Rp <?= number_format($total_subtotal) ?></td>
            <td class="t-right">-Rp <?= number_format($total_diskon) ?></td>
            <td class="t-right">Rp <?= number_format($total_fee) ?></td>
            <td class="t-right">Rp <?= number_format($net_profit) ?></td>
        </tr>
    </tbody>
</table>
<?php endif; ?>

<!-- ==================== DETAIL TRANSAKSI ==================== -->
<div class="section-title"><span class="dot"></span> DETAIL TRANSAKSI</div>
<table>
    <thead>
        <tr>
            <th style="width:4%">#</th>
            <th style="width:16%">Invoice</th>
            <th style="width:13%">Waktu</th>
            <th>Customer</th>
            <th style="width:9%" class="t-center">Tipe</th>
            <th style="width:11%" class="t-right">Subtotal</th>
            <th style="width:8%" class="t-right">Diskon</th>
            <th style="width:7%" class="t-right">Fee</th>
            <th style="width:12%" class="t-right">Total</th>
        </tr>
    </thead>
    <tbody>
        <?php $no = 1; foreach ($transactions as $row): 
            $typeLabel = $row['order_type'];
            $typeIcon = [
                'dinein' => 'Dine In', 'takeaway' => 'Take Away', 
                'catering' => 'Catering', 'mixed' => 'Mixed'
            ][$typeLabel] ?? $typeLabel;
        ?>
        <tr>
            <td class="t-center text-muted"><?= $no++ ?></td>
            <td class="fw-mono"><?= htmlspecialchars($row['invoice']) ?></td>
            <td class="text-muted"><?= date('d/m H:i', strtotime($row['created_at'])) ?></td>
            <td><?= htmlspecialchars($row['customer_name']) ?></td>
            <td class="t-center"><span class="badge <?= $row['order_type'] ?>"><?= $typeIcon ?></span></td>
            <td class="t-right"><?= number_format($row['subtotal']) ?></td>
            <td class="t-right text-red"><?= $row['discount'] > 0 ? number_format($row['discount']) : '-' ?></td>
            <td class="t-right text-amber"><?= $row['takeaway_fee'] > 0 ? number_format($row['takeaway_fee']) : '-' ?></td>
            <td class="t-right fw-bold">Rp <?= number_format($row['total']) ?></td>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($transactions)): ?>
        <tr><td colspan="9" style="text-align:center;padding:30px;color:#bbb;font-size:13px;">
            &#x1F4ED; Tidak ada transaksi pada periode ini
        </td></tr>
        <?php endif; ?>
    </tbody>
</table>

<!-- ==================== FOOTER ==================== -->
<div class="report-footer">
    <div>
        <div style="font-weight:700;color:#555;">GoldenWok Resto</div>
        <div>Laporan <?= $mode_label ?> &bull; <?= $title_periode ?></div>
        <div style="margin-top:2px;">Dicetak otomatis oleh POS System</div>
    </div>
    <div class="footer-right">
        <div class="signature-line">
            <div class="line"></div>
            <div class="name">Manager</div>
        </div>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script>
function saveReportImage() {
    var btn = event.target;
    btn.textContent = 'Menyimpan...';
    btn.disabled = true;
    btn.style.opacity = '0.7';

    html2canvas(document.body, {
        backgroundColor: '#ffffff',
        scale: 2,
        useCORS: true,
        windowWidth: 794
    }).then(function(canvas) {
        var link = document.createElement('a');
        var mode = '<?= $mode ?>';
        var date = '<?= $title_periode ?>'.replace(/[^a-zA-Z0-9]/g, '_');
        link.download = 'Laporan_GoldenWok_' + mode + '_' + date + '.png';
        link.href = canvas.toDataURL('image/png');
        link.click();
        btn.textContent = 'Simpan Gambar';
        btn.disabled = false;
        btn.style.opacity = '1';
    }).catch(function() {
        btn.textContent = 'Simpan Gambar';
        btn.disabled = false;
        btn.style.opacity = '1';
    });
}
</script>

</body>
</html>
