<?php $paymentLabels = ['cash' => 'Tunai', 'debit' => 'Kartu Debit', 'qris' => 'QRIS', 'transfer' => 'Transfer Bank']; ?>
<div class="hero no-print">
    <h2 style="margin:0 0 6px;">Transaksi cepat, tampilan profesional</h2>
    <p style="margin:0; opacity:0.95;">Masukkan data pelanggan, pilih layanan, lalu cetak struk langsung dari halaman ini.</p>
</div>
<div class="pos-grid no-print">
    <div class="panel">
        <span class="pill">Pilih Layanan</span>
        <h3 class="panel-title">Form transaksi</h3>
        <form action="/cashier/add-service" method="post" class="no-print">
            <div class="field member-search-wrap">
                <label for="customer_name">Pelanggan / Cari Member</label>
                <input type="text" id="customer_name" name="customer_name" value="<?= esc($member['name'] ?? $customerName ?? '') ?>" placeholder="Cari nama, email, atau no HP member..." autocomplete="off">
                <input type="hidden" id="member_id" name="member_id" value="<?= esc($memberId ?? '') ?>">
                <div class="member-search-results" id="memberSearchResults"></div>
                <?php if ($member) : ?>
                    <p class="member-search-hint" id="memberSelectedHint">Member terpilih: <strong><?= esc($member['name']) ?></strong> (<?= esc(number_format((int) $member['points'], 0, ',', '.')) ?> poin) &middot; <a href="#" onclick="clearMemberSelection(); return false;">ganti</a></p>
                <?php endif; ?>
            </div>
            <div class="field">
                <label for="service">Layanan / Produk</label>
                <select id="service" name="service">
                    <?php if (!empty($itemServices)) : ?>
                        <optgroup label="Layanan">
                            <?php foreach ($itemServices as $service) : ?>
                                <option value="item-<?= esc($service['id']) ?>"><?= esc($service['name']) ?> - Rp <?= number_format($service['price'], 0, ',', '.') ?></option>
                            <?php endforeach; ?>
                        </optgroup>
                    <?php endif; ?>
                    <?php if (!empty($products)) : ?>
                        <optgroup label="Produk">
                            <?php foreach ($products as $product) : ?>
                                <option value="item-<?= esc($product['id']) ?>"><?= esc($product['name']) ?> - Rp <?= number_format($product['price'], 0, ',', '.') ?></option>
                            <?php endforeach; ?>
                        </optgroup>
                    <?php endif; ?>
                </select>
            </div>
            <div class="field">
                <label for="barber_name">Barber yang Gunting</label>
                <select id="barber_name" name="barber_name">
                    <?php foreach ($barbers as $barber) : ?>
                        <option value="<?= esc($barber['name']) ?>"><?= esc($barber['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <button class="btn-primary" type="submit">Tambah ke Keranjang</button>
        </form>
    </div>
    <div class="panel">
        <span class="pill">Ringkasan</span>
        <h3 class="panel-title">Keranjang saat ini</h3>
        <div class="summary-row"><span>Pelanggan</span><strong><?= esc($customerName ?? 'Pelanggan') ?></strong></div>
        <div class="summary-row"><span>Barber</span><strong><?= esc($barberName ?? '-') ?></strong></div>

        <?php if (!empty($cart)) : ?>
            <ul class="cart-list">
                <?php foreach ($cart as $index => $item) : ?>
                    <li>
                        <span><?= esc($item['name']) ?></span>
                        <span class="cart-item-right">
                            <span class="cart-item-price">Rp <?= number_format($item['price'], 0, ',', '.') ?></span>
                            <a href="/cashier/remove-item/<?= esc($index) ?>" class="cart-remove" title="Hapus item ini">&times;</a>
                        </span>
                    </li>
                <?php endforeach; ?>
            </ul>
        <?php else : ?>
            <p class="cart-empty">Keranjang masih kosong.</p>
        <?php endif; ?>

        <?php if ($member) : ?>
            <?php if ($appliedReward) : ?>
                <div class="reward-applied no-print">
                    <div>
                        <strong><?= esc($appliedReward['name']) ?></strong>
                        <span class="muted" style="display:block; font-size:12px;">-<?= esc($appliedReward['points_required']) ?> poin dipakai</span>
                    </div>
                    <a href="/cashier/remove-reward" class="cart-remove" title="Batalkan promo">&times;</a>
                </div>
            <?php elseif (!empty($availableRewards)) : ?>
                <div class="reward-list no-print">
                    <p class="muted" style="margin:0 0 8px; font-size:13px; font-weight:600;">Promo Tersedia</p>
                    <?php foreach ($availableRewards as $rewardOption) : ?>
                        <a href="/cashier/apply-reward/<?= esc($rewardOption['id']) ?>" class="reward-option">
                            <span><?= esc($rewardOption['name']) ?></span>
                            <span class="pill" style="margin:0;"><?= esc($rewardOption['points_required']) ?> poin</span>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        <?php endif; ?>

        <?php if ($discount > 0) : ?>
            <div class="summary-row"><span>Subtotal</span><strong>Rp <?= number_format($subtotal, 0, ',', '.') ?></strong></div>
            <div class="summary-row"><span>Diskon Promo</span><strong style="color:#dc2626;">-Rp <?= number_format($discount, 0, ',', '.') ?></strong></div>
        <?php endif; ?>
        <div class="total-row">
            <span class="label">Total</span>
            <span class="amount">Rp <?= number_format($total, 0, ',', '.') ?></span>
        </div>

        <div class="no-print action-buttons">
            <button class="btn-primary" type="button" onclick="openPaymentModal()">Bayar Sekarang</button>
            <button class="btn-danger-outline" type="button" onclick="confirmClearCart()">Bersihkan</button>
        </div>
        <form id="checkoutForm" action="/cashier/checkout" method="post" style="display:none;">
            <input type="hidden" name="payment_method" id="paymentMethodInput" value="cash">
            <input type="hidden" name="amount_paid" id="amountPaidInput" value="0">
        </form>

        <?php if (!empty($receipt)) : ?>
            <div class="receipt-card no-print">
                <h4>Pembayaran Berhasil</h4>
                <div class="receipt-row"><span>Pelanggan</span><strong><?= esc($receipt['customer']) ?></strong></div>
                <div class="receipt-row"><span>Barber</span><strong><?= esc($receipt['barber']) ?></strong></div>
                <div class="receipt-row"><span>Metode Bayar</span><strong><?= esc($paymentLabels[$receipt['payment_method'] ?? 'cash'] ?? 'Tunai') ?></strong></div>
                <?php if (($receipt['payment_method'] ?? 'cash') === 'cash') : ?>
                    <div class="receipt-row"><span>Uang Diterima</span><strong>Rp <?= number_format($receipt['amount_paid'] ?? 0, 0, ',', '.') ?></strong></div>
                    <div class="receipt-row"><span>Kembalian</span><strong>Rp <?= number_format($receipt['change'] ?? 0, 0, ',', '.') ?></strong></div>
                <?php endif; ?>
                <?php if (!empty($receipt['reward_name'])) : ?>
                    <div class="receipt-row"><span>Promo</span><strong><?= esc($receipt['reward_name']) ?></strong></div>
                    <div class="receipt-row"><span>Diskon</span><strong style="color:#dc2626;">-Rp <?= number_format($receipt['discount'] ?? 0, 0, ',', '.') ?></strong></div>
                <?php endif; ?>
                <div class="receipt-row"><span>Total</span><strong>Rp <?= number_format($receipt['total'], 0, ',', '.') ?></strong></div>
                <?php if (!empty($receipt['member_name'])) : ?>
                    <div class="receipt-row"><span>Member</span><strong><?= esc($receipt['member_name']) ?></strong></div>
                    <?php if (!empty($receipt['points_redeemed'])) : ?>
                        <div class="receipt-row"><span>Poin Ditukar</span><strong>-<?= esc($receipt['points_redeemed']) ?> poin</strong></div>
                    <?php endif; ?>
                    <?php if (!empty($receipt['points_earned'])) : ?>
                        <div class="receipt-row"><span>Poin Didapat</span><strong>+<?= esc($receipt['points_earned']) ?> poin</strong></div>
                    <?php endif; ?>
                <?php endif; ?>
                <button class="btn-primary" type="button" onclick="window.print()" style="margin-top:12px;">Cetak Struk</button>
            </div>
        <?php endif; ?>
    </div>
</div>
<div class="print-only">
    <div class="receipt-print">
        <div class="shop-name">RAJA CUKUR<br>BARBERSHOP</div>
        <div class="shop-tagline">Terima kasih telah menggunakan layanan kami</div>
        <div class="divider"></div>
        <div class="meta-row"><span>No. Struk</span><span>#<?= esc($receipt['id'] ?? '-') ?></span></div>
        <div class="meta-row"><span>Tanggal</span><span><?= esc($receipt['created_at'] ?? date('d/m/Y H:i')) ?></span></div>
        <div class="meta-row"><span>Kasir</span><span><?= esc($receipt['cashier'] ?? '-') ?></span></div>
        <div class="meta-row"><span>Pelanggan</span><span><?= esc($receipt['customer'] ?? 'Pelanggan') ?></span></div>
        <div class="meta-row"><span>Barber</span><span><?= esc($receipt['barber'] ?? '-') ?></span></div>
        <div class="divider"></div>
        <?php foreach ($receipt['items'] ?? [] as $item) : ?>
            <div class="item-row"><span class="name"><?= esc($item['name']) ?></span><span>Rp <?= number_format($item['price'], 0, ',', '.') ?></span></div>
        <?php endforeach; ?>
        <?php if (!empty($receipt['reward_name'])) : ?>
            <div class="divider"></div>
            <div class="meta-row"><span>Promo</span><span><?= esc($receipt['reward_name']) ?></span></div>
            <div class="meta-row"><span>Diskon</span><span>-Rp <?= number_format($receipt['discount'] ?? 0, 0, ',', '.') ?></span></div>
        <?php endif; ?>
        <div class="divider"></div>
        <div class="total-row"><span>TOTAL</span><span>Rp <?= number_format($receipt['total'] ?? 0, 0, ',', '.') ?></span></div>
        <div class="meta-row"><span>Metode Bayar</span><span><?= esc($paymentLabels[$receipt['payment_method'] ?? 'cash'] ?? 'Tunai') ?></span></div>
        <?php if (($receipt['payment_method'] ?? 'cash') === 'cash') : ?>
            <div class="meta-row"><span>Tunai</span><span>Rp <?= number_format($receipt['amount_paid'] ?? 0, 0, ',', '.') ?></span></div>
            <div class="meta-row"><span>Kembalian</span><span>Rp <?= number_format($receipt['change'] ?? 0, 0, ',', '.') ?></span></div>
        <?php endif; ?>
        <?php if (!empty($receipt['member_name'])) : ?>
            <div class="divider"></div>
            <div class="meta-row"><span>Member</span><span><?= esc($receipt['member_name']) ?></span></div>
            <?php if (!empty($receipt['points_redeemed'])) : ?>
                <div class="meta-row"><span>Poin Ditukar</span><span>-<?= esc($receipt['points_redeemed']) ?> poin</span></div>
            <?php endif; ?>
            <?php if (!empty($receipt['points_earned'])) : ?>
                <div class="meta-row"><span>Poin Didapat</span><span>+<?= esc($receipt['points_earned']) ?> poin</span></div>
            <?php endif; ?>
        <?php endif; ?>
        <div class="footer">
            <div class="thanks">Terima Kasih!</div>
            <div>Sampai jumpa kembali</div>
        </div>
    </div>
</div>

<div class="modal no-print" id="paymentModal" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.45); z-index:9999; align-items:center; justify-content:center; padding:16px;">
    <div style="background:white; width:min(420px, 92vw); border-radius:16px; padding:22px;">
        <h3 style="margin:0 0 14px;">Pembayaran</h3>
        <div class="total-row" style="margin:0 0 16px; padding-top:0; border-top:none;">
            <span class="label">Total Belanja</span>
            <span class="amount" id="payTotalDisplay">Rp 0</span>
        </div>
        <div class="field">
            <label for="paymentMethod">Metode Pembayaran</label>
            <select id="paymentMethod">
                <option value="cash">Tunai</option>
                <option value="debit">Kartu Debit</option>
                <option value="qris">QRIS</option>
                <option value="transfer">Transfer Bank</option>
            </select>
        </div>
        <div class="field" id="cashFieldWrap">
            <label for="amountPaidDisplay">Nominal Uang Diterima</label>
            <input type="text" inputmode="numeric" id="amountPaidDisplay" placeholder="Rp 0">
        </div>
        <div class="total-row" id="changeRow" style="display:none; margin:0 0 10px; padding-top:0; border-top:none;">
            <span class="label">Kembalian</span>
            <span class="amount" id="changeDisplay">Rp 0</span>
        </div>
        <p id="paymentError" style="color:#dc2626; font-size:13px; font-weight:600; display:none; margin:0 0 10px;"></p>
        <div class="action-buttons">
            <button class="btn-primary" type="button" onclick="confirmPayment()">Konfirmasi Pembayaran</button>
            <button class="btn-secondary" type="button" onclick="closePaymentModal()">Batal</button>
        </div>
    </div>
</div>

<style>
.swal2-container { z-index: 10050 !important; }
.btn-danger-outline { background: white; color: #dc2626; border: 1px solid #fecaca; }
.btn-danger-outline:hover { background: #fef2f2; border-color: #fca5a5; }
.panel-title { margin: 6px 0 16px; font-size: 17px; }
.field { margin-bottom: 14px; }
.field label { display: block; margin-bottom: 6px; font-weight: 600; color: var(--muted); font-size: 13px; }
.member-search-wrap { position: relative; }
.member-search-results { display: none; position: absolute; top: calc(100% + 4px); left: 0; right: 0; background: white; border: 1px solid var(--border); border-radius: 12px; box-shadow: 0 14px 30px rgba(15,23,42,0.12); max-height: 240px; overflow-y: auto; z-index: 30; }
.member-search-item { display: flex; flex-direction: column; gap: 2px; padding: 10px 14px; cursor: pointer; border-bottom: 1px solid var(--border); }
.member-search-item:last-child { border-bottom: none; }
.member-search-item:hover { background: #f5f3ff; }
.member-search-item strong { font-size: 13px; color: var(--text); }
.member-search-item span { font-size: 12px; color: var(--muted); }
.member-search-empty { padding: 12px 14px; font-size: 13px; color: var(--muted); }
.member-search-hint { margin: 8px 0 0; font-size: 12px; color: #16a34a; }
.member-search-hint a { color: var(--accent); text-decoration: none; font-weight: 600; }
.summary-row { display: flex; justify-content: space-between; gap: 10px; font-size: 14px; color: var(--muted); margin: 6px 0; }
.summary-row strong { color: var(--text); }
.reward-list { margin-top: 12px; border: 1px solid var(--border); border-radius: 12px; padding: 10px; }
.reward-option { display: flex; justify-content: space-between; align-items: center; gap: 10px; padding: 9px 8px; border-radius: 8px; text-decoration: none; color: var(--text); font-size: 13px; font-weight: 600; }
.reward-option:hover { background: #f5f3ff; }
.reward-applied { display: flex; justify-content: space-between; align-items: center; gap: 10px; background: #f0fdf4; border: 1px solid #bbf7d0; border-radius: 12px; padding: 10px 14px; margin-top: 12px; font-size: 13px; color: #166534; }
.cart-list { list-style: none; margin: 14px 0; padding: 0; border-top: 1px solid var(--border); }
.cart-list li { display: flex; justify-content: space-between; align-items: center; gap: 10px; padding: 10px 0; border-bottom: 1px solid var(--border); font-size: 14px; }
.cart-item-right { display: flex; align-items: center; gap: 10px; flex-shrink: 0; }
.cart-item-price { font-weight: 700; color: var(--text); white-space: nowrap; }
.cart-remove { display: inline-flex; align-items: center; justify-content: center; width: 22px; height: 22px; border-radius: 50%; background: #fef2f2; color: #dc2626; text-decoration: none; font-size: 15px; font-weight: 700; line-height: 1; flex-shrink: 0; }
.cart-remove:hover { background: #fecaca; }
.cart-empty { color: var(--muted); font-size: 14px; padding: 16px 0; text-align: center; }
.total-row { display: flex; justify-content: space-between; align-items: center; margin: 16px 0; padding-top: 10px; border-top: 2px solid var(--border); }
.total-row .label { color: var(--muted); font-weight: 600; font-size: 14px; }
.total-row .amount { font-size: 22px; font-weight: 800; color: var(--text); }
.action-buttons { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 4px; }
.action-buttons > * { flex: 1; min-width: 140px; }
.receipt-card { border: 1px dashed #94a3b8; border-radius: 16px; padding: 18px; margin-top: 16px; background: #f8fafc; }
.receipt-card h4 { margin: 0 0 10px; font-size: 15px; }
.receipt-row { display: flex; justify-content: space-between; margin: 4px 0; color: var(--muted); font-size: 13px; }
.receipt-row strong { color: var(--text); }

.pos-grid { display: grid; grid-template-columns: 1.2fr 0.8fr; gap: 20px; align-items: start; margin-bottom: 20px; }

.print-only { display: none; }
.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(.print-only) { display: none !important; }
    .print-only { display: block !important; }
    @page { margin: 8mm; }
}

@media screen and (max-width: 900px) {
    .pos-grid { grid-template-columns: 1fr; }
    .pos-grid .panel:first-child { order: 2; }
    .pos-grid .panel:last-child { order: 1; }
}
</style>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
const CART_TOTAL = <?= (int) $total ?>;

function formatRupiahDisplay(digits) {
    if (!digits) return '';
    return 'Rp ' + digits.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
}

(function () {
    const searchInput = document.getElementById('customer_name');
    const memberIdInput = document.getElementById('member_id');
    const resultsBox = document.getElementById('memberSearchResults');
    if (!searchInput || !memberIdInput || !resultsBox) return;

    let searchTimer;

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text || '';
        return div.innerHTML;
    }

    function hideResults() {
        resultsBox.style.display = 'none';
        resultsBox.innerHTML = '';
    }

    searchInput.addEventListener('input', function () {
        memberIdInput.value = '';
        const hint = document.getElementById('memberSelectedHint');
        if (hint) hint.remove();

        clearTimeout(searchTimer);
        const query = this.value.trim();
        if (query.length < 2) {
            hideResults();
            return;
        }

        searchTimer = setTimeout(function () {
            fetch('/cashier/search-member?q=' + encodeURIComponent(query))
                .then(function (r) { return r.json(); })
                .then(function (members) {
                    if (!members.length) {
                        resultsBox.innerHTML = '<div class="member-search-empty">Member tidak ditemukan. Akan dicatat sebagai pelanggan biasa.</div>';
                        resultsBox.style.display = 'block';
                        return;
                    }
                    resultsBox.innerHTML = members.map(function (m) {
                        const contact = m.phone || m.email || '-';
                        const points = Number(m.points || 0).toLocaleString('id-ID');
                        return '<div class="member-search-item" data-id="' + m.id + '" data-name="' + escapeHtml(m.name) + '">'
                            + '<strong>' + escapeHtml(m.name) + '</strong>'
                            + '<span>' + escapeHtml(contact) + ' &middot; ' + points + ' poin</span>'
                            + '</div>';
                    }).join('');
                    resultsBox.style.display = 'block';
                });
        }, 300);
    });

    resultsBox.addEventListener('click', function (e) {
        const item = e.target.closest('.member-search-item');
        if (!item || !item.dataset.id) return;
        searchInput.value = item.dataset.name;
        memberIdInput.value = item.dataset.id;
        hideResults();
    });

    document.addEventListener('click', function (e) {
        if (e.target !== searchInput && !resultsBox.contains(e.target)) {
            hideResults();
        }
    });
})();

function clearMemberSelection() {
    const searchInput = document.getElementById('customer_name');
    const memberIdInput = document.getElementById('member_id');
    const hint = document.getElementById('memberSelectedHint');
    searchInput.value = '';
    memberIdInput.value = '';
    if (hint) hint.remove();
    searchInput.focus();
}

function confirmClearCart() {
    if (CART_TOTAL <= 0) {
        return;
    }
    Swal.fire({
        title: 'Kosongkan keranjang?',
        text: 'Semua item yang sudah ditambahkan akan dihapus.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Ya, kosongkan',
        cancelButtonText: 'Batal',
        confirmButtonColor: '#dc2626'
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = '/cashier/clear';
        }
    });
}

function openPaymentModal() {
    if (CART_TOTAL <= 0) {
        alert('Keranjang masih kosong.');
        return;
    }
    document.getElementById('payTotalDisplay').textContent = 'Rp ' + CART_TOTAL.toLocaleString('id-ID');
    document.getElementById('paymentMethod').value = 'cash';
    document.getElementById('amountPaidDisplay').value = '';
    document.getElementById('changeRow').style.display = 'none';
    document.getElementById('paymentError').style.display = 'none';
    toggleCashField();
    document.getElementById('paymentModal').style.display = 'flex';
}
function closePaymentModal() {
    document.getElementById('paymentModal').style.display = 'none';
}
function toggleCashField() {
    const method = document.getElementById('paymentMethod').value;
    document.getElementById('cashFieldWrap').style.display = method === 'cash' ? 'block' : 'none';
    document.getElementById('changeRow').style.display = 'none';
    document.getElementById('paymentError').style.display = 'none';
}
document.getElementById('paymentMethod').addEventListener('change', toggleCashField);

document.getElementById('amountPaidDisplay').addEventListener('input', function () {
    const digits = this.value.replace(/\D/g, '');
    this.value = formatRupiahDisplay(digits);
    const changeRow = document.getElementById('changeRow');
    const changeDisplay = document.getElementById('changeDisplay');
    if (digits) {
        const paid = Number(digits);
        const change = paid - CART_TOTAL;
        changeRow.style.display = 'flex';
        changeDisplay.textContent = 'Rp ' + Math.max(change, 0).toLocaleString('id-ID');
        changeDisplay.style.color = change < 0 ? '#dc2626' : '';
    } else {
        changeRow.style.display = 'none';
    }
    document.getElementById('paymentError').style.display = 'none';
});

function confirmPayment() {
    const method = document.getElementById('paymentMethod').value;
    const errorEl = document.getElementById('paymentError');

    let paid = CART_TOTAL;
    if (method === 'cash') {
        const digits = document.getElementById('amountPaidDisplay').value.replace(/\D/g, '');
        paid = Number(digits || 0);
        if (paid < CART_TOTAL) {
            errorEl.textContent = 'Nominal uang kurang dari total belanja.';
            errorEl.style.display = 'block';
            return;
        }
    }

    document.getElementById('paymentMethodInput').value = method;
    document.getElementById('amountPaidInput').value = paid;
    document.getElementById('checkoutForm').submit();
}

window.addEventListener('afterprint', function () {
    window.location.href = '/cashier/new';
});
</script>
