<?php
require 'config.php';

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

$id = $_GET['id'] ?? 0;

$stmt = $pdo->prepare("SELECT * FROM transactions WHERE id = ?");
$stmt->execute([$id]);
$trans = $stmt->fetch();

if (!$trans) {
    die("Transaksi tidak ditemukan!");
}

$cart_items = json_decode($trans['cart'], true) ?? [];

// Group items
$dinein_items = array_filter($cart_items, fn($i) => ($i['item_order_type'] ?? 'dinein') === 'dinein');
$takeaway_items = array_filter($cart_items, fn($i) => ($i['item_order_type'] ?? 'dinein') === 'takeaway');
$catering_items = array_filter($cart_items, fn($i) => ($i['item_order_type'] ?? 'dinein') === 'catering');
$groups = [
    'dinein'   => ['label' => 'MAKAN DI TEMPAT', 'icon' => '🍽', 'items' => $dinein_items, 'color' => '#2563eb'],
    'takeaway' => ['label' => 'BAWA PULANG', 'icon' => '🛍', 'items' => $takeaway_items, 'color' => '#0f766e'],
    'catering' => ['label' => 'CATERING', 'icon' => '📦', 'items' => $catering_items, 'color' => '#6d28d9'],
];
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <link rel="icon" href="favicon.ico" type="image/x-icon">
    <meta charset="UTF-8">
    <title>Struk A4 #<?= $trans['invoice'] ?> | GoldenWok</title>
    <style>
        @page { size: A4; margin: 10mm; }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: 'Segoe UI', 'Helvetica Neue', Arial, sans-serif;
            font-size: 13px; color: #1a1a2e;
            -webkit-print-color-adjust: exact; print-color-adjust: exact;
        }
        .receipt {
            max-width: 190mm; margin: 0 auto;
            border: 2px solid #1a1a2e; border-radius: 12px;
            padding: 20px 24px;
        }
        .header {
            display: flex; justify-content: space-between; align-items: center;
            padding-bottom: 16px; margin-bottom: 16px;
            border-bottom: 3px solid #1a1a2e;
        }
        .header .logo h1 { font-size: 24px; letter-spacing: 2px; color: #1a1a2e; }
        .header .logo .sub { font-size: 10px; color: #888; margin-top: 2px; }
        .header .invoice-box {
            text-align: right;
        }
        .invoice-box .inv-label { font-size: 9px; text-transform: uppercase; color: #888; letter-spacing: 1px; }
        .invoice-box .inv-number { font-size: 16px; font-weight: 800; font-family: 'Courier New', monospace; }
        .invoice-box .inv-date { font-size: 10px; color: #666; }

        .meta { display: flex; gap: 40px; margin-bottom: 20px; font-size: 12px; }
        .meta .label { font-size: 9px; text-transform: uppercase; color: #888; letter-spacing: 1px; }
        .meta .value { font-weight: 700; }

        h3.group-title {
            font-size: 13px; margin: 16px 0 8px 0; padding: 6px 12px;
            border-left: 4px solid; border-radius: 4px; display: flex; align-items: center; gap: 8px;
        }

        table { width: 100%; border-collapse: collapse; margin-bottom: 8px; }
        th { text-align: left; font-size: 10px; text-transform: uppercase; letter-spacing: 1px; color: #888; padding: 6px 4px; border-bottom: 1px solid #ddd; }
        td { padding: 8px 4px; border-bottom: 1px solid #f0f0f0; }
        .t-right { text-align: right; }
        .t-center { text-align: center; }
        .bold { font-weight: 700; }

        .summary-section {
            margin-top: 16px; padding-top: 12px; border-top: 2px solid #1a1a2e;
        }
        .summary-row { display: flex; justify-content: space-between; padding: 4px 0; font-size: 13px; }
        .summary-row.total { font-size: 18px; font-weight: 800; margin-top: 8px; padding-top: 8px; border-top: 2px solid #1a1a2e; }
        .summary-row.discount { color: #dc2626; }
        .summary-row.fee { color: #92400e; }

        .footer {
            margin-top: 20px; padding-top: 16px; border-top: 2px dashed #ddd;
            text-align: center; font-size: 11px; color: #888;
        }
        .footer .thanks { font-size: 18px; font-weight: 800; color: #c8a951; margin-bottom: 6px; }
        .barcode-box { text-align: center; margin: 16px 0; }
        svg#barcode { max-width: 150mm; }

        @media print { .no-print { display: none; } }
        .btn-print {
            display: block; margin: 10px auto 20px auto; padding: 10px 30px;
            background: #1a1a2e; color: #fff; border: none; border-radius: 8px;
            cursor: pointer; font-size: 13px; font-weight: 600; font-family: inherit;
        }
    </style>
</head>
<body>

<button onclick="window.print()" class="btn-print no-print">🖨 Cetak Struk A4</button>

<div class="receipt">
    <div class="header">
        <div class="logo">
            <h1>GOLDENWOK RESTO</h1>
            <div class="sub">Jl. Ciater, Palapa &bull; Tangerang Selatan</div>
        </div>
        <div class="invoice-box">
            <div class="inv-label">Invoice</div>
            <div class="inv-number"><?= $trans['invoice'] ?></div>
            <div class="inv-date"><?= date('d M Y / H:i', strtotime($trans['created_at'])) ?></div>
        </div>
    </div>

    <div class="meta">
        <div>
            <div class="label">Customer</div>
            <div class="value"><?= htmlspecialchars($trans['customer_name']) ?: 'Umum' ?></div>
        </div>
        <div>
            <div class="label">Tipe Order</div>
            <div class="value"><?= strtoupper($trans['order_type']) ?></div>
        </div>
        <div>
            <div class="label">Kasir</div>
            <div class="value"><?= htmlspecialchars($_SESSION['name'] ?? '-') ?></div>
        </div>
    </div>

    <?php foreach ($groups as $gtype => $group): 
        if (empty($group['items'])) continue;
        $group_sub = 0;
    ?>
    <h3 class="group-title" style="border-left-color:<?= $group['color'] ?>;background:<?= $group['color'] ?>08;">
        <?= $group['icon'] ?> <?= $group['label'] ?>
    </h3>
    <table>
        <thead>
            <tr>
                <th style="width:35%">Item</th>
                <th class="t-center" style="width:10%">Qty</th>
                <th class="t-right" style="width:20%">Harga</th>
                <th class="t-right" style="width:15%">Diskon</th>
                <th class="t-right bold" style="width:20%">Subtotal</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($group['items'] as $item): 
                $price = (int)($item['price'] ?? 0);
                $qty = (int)($item['qty'] ?? 1);
                $disc = (float)($item['disc'] ?? $item['itemDiscount'] ?? 0);
                $isPct = (bool)($item['isPercent'] ?? false);
                $finalPrice = $price;
                $discAmount = 0;
                if ($disc > 0) {
                    $finalPrice = $isPct ? (int)round($price * (1 - $disc / 100)) : max(0, $price - (int)$disc);
                    $discAmount = ($price - $finalPrice) * $qty;
                }
                $lineTotal = $finalPrice * $qty;
                $group_sub += $lineTotal;
            ?>
            <tr>
                <td class="bold"><?= htmlspecialchars($item['name']) ?></td>
                <td class="t-center"><?= $qty ?></td>
                <td class="t-right">Rp <?= number_format($price) ?></td>
                <td class="t-right" style="color:#dc2626;"><?= $disc > 0 ? ($isPct ? $disc.'%' : 'Rp '.number_format($disc)) : '-' ?></td>
                <td class="t-right bold">Rp <?= number_format($lineTotal) ?></td>
            </tr>
            <?php endforeach; ?>
            <tr style="font-size:11px;color:#666;">
                <td colspan="4">Subtotal Grup</td>
                <td class="t-right bold">Rp <?= number_format($group_sub) ?></td>
            </tr>
        </tbody>
    </table>
    <?php endforeach; ?>

    <div class="summary-section">
        <div class="summary-row">
            <span>Sub Total</span>
            <span>Rp <?= number_format($trans['subtotal']) ?></span>
        </div>
        <?php if ($trans['discount'] > 0): ?>
        <div class="summary-row discount">
            <span>Diskon Item</span>
            <span>- Rp <?= number_format($trans['discount']) ?></span>
        </div>
        <?php endif; ?>
        <?php if ($trans['voucher_discount'] > 0): ?>
        <div class="summary-row discount">
            <span>Voucher <?= htmlspecialchars($trans['voucher_code']) ?></span>
            <span>- Rp <?= number_format($trans['voucher_discount']) ?></span>
        </div>
        <?php endif; ?>
        <?php if ($trans['takeaway_fee'] > 0): ?>
        <div class="summary-row fee">
            <span>Fee Bungkus / Catering</span>
            <span>+ Rp <?= number_format($trans['takeaway_fee']) ?></span>
        </div>
        <?php endif; ?>
        <?php if ($trans['service_charge'] > 0): ?>
        <div class="summary-row">
            <span>Service Charge</span>
            <span>Rp <?= number_format($trans['service_charge']) ?></span>
        </div>
        <?php endif; ?>
        <div class="summary-row total">
            <span>TOTAL</span>
            <span>Rp <?= number_format($trans['total']) ?></span>
        </div>
    </div>

    <div class="barcode-box">
        <svg id="barcode"></svg>
    </div>

    <div class="footer">
        <div class="thanks">Terima Kasih 🙏</div>
        <div>Barang yang sudah dibeli tidak dapat dikembalikan</div>
        <div style="margin-top:6px;">Dicetak: <?= date('d/m/Y H:i') ?> &bull; GoldenWok POS</div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"></script>
<script>
try {
    JsBarcode("#barcode", "<?= $trans['invoice'] ?>", {
        format: "CODE128", lineColor: "#000",
        width: 1.5, height: 40, displayValue: true, fontSize: 12
    });
} catch(e) {}
window.onload = function() { setTimeout(function() { window.print(); }, 800); };
</script>

</body>
</html>
