<div class="hero">
    <div>
        <h2 style="margin:0 0 6px;">Riwayat Transaksi</h2>
        <p style="margin:0; opacity:0.95;">Lihat semua transaksi yang pernah terjadi dan cetak ulang struknya kapan saja.</p>
    </div>
</div>

<div class="panel">
    <h3 style="margin-top:0;">Filter</h3>
    <form method="get" action="/transaction-history" class="form-grid">
        <input type="date" name="date_from" value="<?= esc($filters['date_from']) ?>">
        <input type="date" name="date_to" value="<?= esc($filters['date_to']) ?>">
        <select name="barber">
            <option value="">Semua Barber</option>
            <?php foreach ($barbers as $barber) : ?>
                <option value="<?= esc($barber['name']) ?>" <?= ($filters['barber'] ?? '') === $barber['name'] ? 'selected' : '' ?>><?= esc($barber['name']) ?></option>
            <?php endforeach; ?>
        </select>
        <button class="btn-primary" type="submit">Terapkan</button>
    </form>
</div>

<?php
$iconView = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>';
$iconPrint = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 6 2 18 2 18 9"></polyline><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"></path><rect x="6" y="14" width="12" height="8"></rect></svg>';
$iconDelete = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"></path><path d="M10 11v6"></path><path d="M14 11v6"></path><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"></path></svg>';

$baseParams = array_filter($filters, static fn ($v) => $v !== '');
$baseParams['per_page'] = $perPage;
$pageLink = function ($page) use ($baseParams) {
    $params = $baseParams;
    $params['page'] = $page;
    return '/transaction-history?' . http_build_query($params);
};
?>
<div class="panel">
    <div style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:10px; margin-bottom:12px;">
        <h3 style="margin:0;">Daftar Transaksi</h3>
        <form method="get" action="/transaction-history" style="display:flex; align-items:center; gap:8px; margin:0;">
            <?php foreach ($filters as $key => $value) : ?>
                <?php if ($value !== '') : ?>
                    <input type="hidden" name="<?= esc($key) ?>" value="<?= esc($value) ?>">
                <?php endif; ?>
            <?php endforeach; ?>
            <label class="muted" style="font-size:13px; white-space:nowrap;" for="perPageSelect">Tampilkan</label>
            <select name="per_page" id="perPageSelect" onchange="this.form.submit()" style="min-width:90px;">
                <option value="10" <?= $perPage === 10 ? 'selected' : '' ?>>10</option>
                <option value="25" <?= $perPage === 25 ? 'selected' : '' ?>>25</option>
                <option value="50" <?= $perPage === 50 ? 'selected' : '' ?>>50</option>
                <option value="100" <?= $perPage === 100 ? 'selected' : '' ?>>100</option>
            </select>
        </form>
    </div>
    <div class="table-wrap">
        <table>
            <thead>
                <tr><th>ID</th><th>Pelanggan</th><th>Kasir</th><th>Barber</th><th>Total</th><th>Waktu</th><th>Aksi</th></tr>
            </thead>
            <tbody>
                <?php foreach ($transactions as $transaction) : ?>
                    <?php $items = is_string($transaction['items'] ?? '') ? (json_decode($transaction['items'], true) ?: []) : ($transaction['items'] ?? []); ?>
                    <tr>
                        <td><?= esc($transaction['id']) ?></td>
                        <td><?= esc($transaction['customer']) ?></td>
                        <td><?= esc($transaction['cashier']) ?></td>
                        <td><?= esc($transaction['barber']) ?></td>
                        <td>Rp <?= number_format($transaction['total'], 0, ',', '.') ?></td>
                        <td><?= esc($transaction['created_at']) ?></td>
                        <td>
                            <div class="action-cell">
                                <button type="button" class="icon-btn icon-view" title="Detail"
                                    data-id="<?= esc($transaction['id'] ?? '-') ?>"
                                    data-customer="<?= esc($transaction['customer'] ?? '-') ?>"
                                    data-cashier="<?= esc($transaction['cashier'] ?? '-') ?>"
                                    data-barber="<?= esc($transaction['barber'] ?? '-') ?>"
                                    data-created="<?= esc($transaction['created_at'] ?? '-') ?>"
                                    data-total="<?= esc($transaction['total'] ?? 0) ?>"
                                    data-payment="<?= esc($transaction['payment_method'] ?? 'cash') ?>"
                                    data-paid="<?= esc($transaction['amount_paid'] ?? $transaction['total'] ?? 0) ?>"
                                    data-items='<?= esc(json_encode($items), 'attr') ?>'
                                    data-reward="<?= esc($transaction['reward_name'] ?? '') ?>"
                                    data-discount="<?= esc($transaction['discount_amount'] ?? 0) ?>"
                                    data-points-redeemed="<?= esc($transaction['points_redeemed'] ?? 0) ?>"
                                    data-points-earned="<?= esc($transaction['points_earned'] ?? 0) ?>"
                                    onclick="showDetail(this)"><?= $iconView ?></button>
                                <button type="button" class="icon-btn icon-print" title="Cetak Ulang"
                                    data-id="<?= esc($transaction['id'] ?? '-') ?>"
                                    data-customer="<?= esc($transaction['customer'] ?? '-') ?>"
                                    data-cashier="<?= esc($transaction['cashier'] ?? '-') ?>"
                                    data-barber="<?= esc($transaction['barber'] ?? '-') ?>"
                                    data-created="<?= esc($transaction['created_at'] ?? '-') ?>"
                                    data-total="<?= esc($transaction['total'] ?? 0) ?>"
                                    data-payment="<?= esc($transaction['payment_method'] ?? 'cash') ?>"
                                    data-paid="<?= esc($transaction['amount_paid'] ?? $transaction['total'] ?? 0) ?>"
                                    data-items='<?= esc(json_encode($items), 'attr') ?>'
                                    data-reward="<?= esc($transaction['reward_name'] ?? '') ?>"
                                    data-discount="<?= esc($transaction['discount_amount'] ?? 0) ?>"
                                    data-points-redeemed="<?= esc($transaction['points_redeemed'] ?? 0) ?>"
                                    data-points-earned="<?= esc($transaction['points_earned'] ?? 0) ?>"
                                    onclick="printReceipt(this)"><?= $iconPrint ?></button>
                                <a class="icon-btn icon-delete" href="#" title="Hapus" onclick="confirmDelete('/owner/delete-transaction/<?= esc($transaction['id']) ?>'); return false;"><?= $iconDelete ?></a>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($transactions)) : ?>
                    <tr><td colspan="7" class="muted">Tidak ada transaksi untuk filter yang dipilih.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php if ($totalRows > 0) : ?>
        <div style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:10px; margin-top:16px;">
            <span class="muted" style="font-size:13px;">Halaman <?= esc($currentPage) ?> dari <?= esc($totalPages) ?> &middot; <?= esc($totalRows) ?> transaksi</span>
            <div style="display:flex; gap:8px;">
                <a class="btn-secondary" style="width:auto; min-height:auto; padding:8px 16px; <?= $currentPage <= 1 ? 'opacity:0.4; pointer-events:none;' : '' ?>" href="<?= esc($pageLink(max(1, $currentPage - 1))) ?>">&larr; Sebelumnya</a>
                <a class="btn-secondary" style="width:auto; min-height:auto; padding:8px 16px; <?= $currentPage >= $totalPages ? 'opacity:0.4; pointer-events:none;' : '' ?>" href="<?= esc($pageLink(min($totalPages, $currentPage + 1))) ?>">Berikutnya &rarr;</a>
            </div>
        </div>
    <?php endif; ?>
</div>

<div class="print-only" id="printSection" style="display:none;">
    <div class="receipt-print">
        <div class="shop-name">RAJA CUKUR<br>BARBERSHOP</div>
        <div class="shop-tagline">Cetak Ulang Struk</div>
        <div class="divider"></div>
        <div class="meta-row"><span>No. Struk</span><span>#<span id="printId"></span></span></div>
        <div class="meta-row"><span>Tanggal</span><span id="printDate"></span></div>
        <div class="meta-row"><span>Kasir</span><span id="printCashier"></span></div>
        <div class="meta-row"><span>Pelanggan</span><span id="printCustomer"></span></div>
        <div class="meta-row"><span>Barber</span><span id="printBarber"></span></div>
        <div class="divider"></div>
        <div id="printItems"></div>
        <div class="divider"></div>
        <div class="meta-row" id="printRewardRow"><span>Promo</span><span id="printReward"></span></div>
        <div class="meta-row" id="printPointsRow"><span>Potong Poin</span><span id="printPointsRedeemed"></span></div>
        <div class="total-row"><span>TOTAL</span><span id="printTotal"></span></div>
        <div class="meta-row"><span>Metode Bayar</span><span id="printPaymentMethod"></span></div>
        <div class="meta-row" id="printPaidRow"><span>Tunai</span><span id="printPaid"></span></div>
        <div class="meta-row" id="printChangeRow"><span>Kembalian</span><span id="printChange"></span></div>
        <div class="meta-row" id="printPointsEarnedRow"><span>Poin Didapat</span><span id="printPointsEarned"></span></div>
        <div class="footer">
            <div class="thanks">Terima Kasih!</div>
            <div>Sampai jumpa kembali</div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<style>
.swal2-container { z-index: 10050 !important; }
.receipt-print { width: 300px; margin: 0 auto; font-family: 'Courier New', Courier, monospace; color: #000; }
.receipt-print .shop-name { text-align: center; font-size: 17px; font-weight: 800; letter-spacing: 1px; line-height: 1.3; }
.receipt-print .shop-tagline { text-align: center; font-size: 11px; margin: 2px 0 0; }
.receipt-print .divider { border-top: 1px dashed #000; margin: 10px 0; }
.receipt-print .meta-row { display: flex; justify-content: space-between; font-size: 12px; margin: 3px 0; gap: 10px; }
.receipt-print .meta-row span:first-child { color: #444; }
.receipt-print .item-row { display: flex; justify-content: space-between; font-size: 12px; margin: 5px 0; gap: 10px; }
.receipt-print .item-row .name { flex: 1; }
.receipt-print .total-row { display: flex; justify-content: space-between; font-size: 15px; font-weight: 800; margin-top: 4px; }
.receipt-print .footer { text-align: center; font-size: 12px; margin-top: 14px; }
.receipt-print .footer .thanks { font-weight: 700; margin-bottom: 2px; }
@media print {
    .sidebar, .topheader, .no-print { display: none !important; }
    .content-body { padding: 0 !important; }
    .content-body > *:not(#printSection) { display: none !important; }
    #printSection { display: block !important; }
    @page { margin: 8mm; }
}
</style>
<script>
const PAYMENT_LABELS = { cash: 'Tunai', debit: 'Kartu Debit', qris: 'QRIS', transfer: 'Transfer Bank' };
function confirmDelete(url) {
    Swal.fire({ title: 'Apakah Anda yakin?', text: 'Transaksi ini akan dihapus permanen.', icon: 'warning', showCancelButton: true, confirmButtonText: 'Ya, hapus', cancelButtonText: 'Batal' }).then((result) => {
        if (result.isConfirmed) {
            fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } }).then(r => r.json()).then(() => { Swal.fire('Berhasil', 'Data Berhasil Dihapus', 'success').then(() => location.reload()); });
        }
    });
}
function showDetail(btn) {
    const items = JSON.parse(btn.dataset.items || '[]');
    const rows = items.map(function (item) {
        const price = Number(item.price || 0);
        return '<tr><td style="padding:6px 8px; text-align:left; border-bottom:1px solid #e2e8f0;">' + item.name + '</td><td style="padding:6px 8px; text-align:right; border-bottom:1px solid #e2e8f0;">Rp ' + price.toLocaleString('id-ID') + '</td></tr>';
    }).join('');
    const total = Number(btn.dataset.total || 0);
    const paymentMethod = btn.dataset.payment || 'cash';
    const paid = Number(btn.dataset.paid || total);
    const change = paid - total;
    const paymentLabel = PAYMENT_LABELS[paymentMethod] || 'Tunai';
    const rewardName = btn.dataset.reward || '';
    const discount = Number(btn.dataset.discount || 0);
    const pointsRedeemed = Number(btn.dataset.pointsRedeemed || 0);
    const pointsEarned = Number(btn.dataset.pointsEarned || 0);

    let paymentHtml = '<p style="margin:4px 0;"><strong>Metode Bayar:</strong> ' + paymentLabel + '</p>';
    if (paymentMethod === 'cash') {
        paymentHtml += '<p style="margin:4px 0;"><strong>Tunai Diterima:</strong> Rp ' + paid.toLocaleString('id-ID') + '</p>'
            + '<p style="margin:4px 0;"><strong>Kembalian:</strong> Rp ' + Math.max(change, 0).toLocaleString('id-ID') + '</p>';
    }

    let rewardHtml = '';
    if (rewardName || pointsRedeemed > 0) {
        rewardHtml = '<p style="margin:4px 0; color:#dc2626;"><strong>Promo:</strong> ' + (rewardName || '-')
            + (discount > 0 ? ' (Diskon Rp ' + discount.toLocaleString('id-ID') + ')' : '') + '</p>'
            + (pointsRedeemed > 0 ? '<p style="margin:4px 0; color:#dc2626;"><strong>Potong Poin:</strong> ' + pointsRedeemed.toLocaleString('id-ID') + ' poin</p>' : '');
    }

    let pointsEarnedHtml = '';
    if (pointsEarned > 0) {
        pointsEarnedHtml = '<p style="margin:4px 0; color:#16a34a;"><strong>Poin Didapat:</strong> +' + pointsEarned.toLocaleString('id-ID') + ' poin</p>';
    }

    Swal.fire({
        title: 'Detail Transaksi #' + btn.dataset.id,
        width: 480,
        confirmButtonText: 'Tutup',
        html: '<div style="text-align:left; font-size:14px;">'
            + '<p style="margin:4px 0;"><strong>Pelanggan:</strong> ' + btn.dataset.customer + '</p>'
            + '<p style="margin:4px 0;"><strong>Kasir:</strong> ' + btn.dataset.cashier + '</p>'
            + '<p style="margin:4px 0;"><strong>Barber:</strong> ' + btn.dataset.barber + '</p>'
            + '<p style="margin:4px 0;"><strong>Waktu:</strong> ' + btn.dataset.created + '</p>'
            + '<table style="width:100%; margin-top:10px; border-collapse:collapse;">'
            + '<thead><tr><th style="text-align:left; padding:6px 8px; border-bottom:2px solid #e2e8f0;">Item</th><th style="text-align:right; padding:6px 8px; border-bottom:2px solid #e2e8f0;">Harga</th></tr></thead>'
            + '<tbody>' + rows + '</tbody>'
            + '</table>'
            + '<p style="margin-top:10px; text-align:right; font-size:16px;"><strong>Total: Rp ' + total.toLocaleString('id-ID') + '</strong></p>'
            + '<hr style="margin:10px 0; border:none; border-top:1px solid #e2e8f0;">'
            + rewardHtml
            + paymentHtml
            + pointsEarnedHtml
            + '</div>'
    });
}
function printReceipt(btn) {
    document.getElementById('printId').textContent = btn.dataset.id || '-';
    document.getElementById('printCustomer').textContent = btn.dataset.customer;
    document.getElementById('printCashier').textContent = btn.dataset.cashier;
    document.getElementById('printBarber').textContent = btn.dataset.barber;
    document.getElementById('printDate').textContent = btn.dataset.created;

    const items = JSON.parse(btn.dataset.items || '[]');
    const list = document.getElementById('printItems');
    list.innerHTML = '';
    items.forEach(function (item) {
        const row = document.createElement('div');
        row.className = 'item-row';
        const price = Number(item.price || 0);
        row.innerHTML = '<span class="name"></span><span></span>';
        row.querySelector('.name').textContent = item.name;
        row.querySelector('.name').nextElementSibling.textContent = 'Rp ' + price.toLocaleString('id-ID');
        list.appendChild(row);
    });

    const rewardName = btn.dataset.reward || '';
    const discount = Number(btn.dataset.discount || 0);
    const pointsRedeemed = Number(btn.dataset.pointsRedeemed || 0);
    const showReward = !!rewardName || pointsRedeemed > 0;
    document.getElementById('printRewardRow').style.display = showReward ? 'flex' : 'none';
    document.getElementById('printPointsRow').style.display = pointsRedeemed > 0 ? 'flex' : 'none';
    if (showReward) {
        document.getElementById('printReward').textContent = (rewardName || '-') + (discount > 0 ? ' (-Rp ' + discount.toLocaleString('id-ID') + ')' : '');
    }
    if (pointsRedeemed > 0) {
        document.getElementById('printPointsRedeemed').textContent = '-' + pointsRedeemed.toLocaleString('id-ID') + ' poin';
    }

    const pointsEarned = Number(btn.dataset.pointsEarned || 0);
    document.getElementById('printPointsEarnedRow').style.display = pointsEarned > 0 ? 'flex' : 'none';
    if (pointsEarned > 0) {
        document.getElementById('printPointsEarned').textContent = '+' + pointsEarned.toLocaleString('id-ID') + ' poin';
    }

    const total = Number(btn.dataset.total || 0);
    document.getElementById('printTotal').textContent = 'Rp ' + total.toLocaleString('id-ID');

    const paymentMethod = btn.dataset.payment || 'cash';
    const paid = Number(btn.dataset.paid || total);
    const change = paid - total;
    document.getElementById('printPaymentMethod').textContent = PAYMENT_LABELS[paymentMethod] || 'Tunai';
    const showCash = paymentMethod === 'cash';
    document.getElementById('printPaidRow').style.display = showCash ? 'flex' : 'none';
    document.getElementById('printChangeRow').style.display = showCash ? 'flex' : 'none';
    if (showCash) {
        document.getElementById('printPaid').textContent = 'Rp ' + paid.toLocaleString('id-ID');
        document.getElementById('printChange').textContent = 'Rp ' + Math.max(change, 0).toLocaleString('id-ID');
    }

    window.print();
}
</script>
