<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Teh Tarik 99 - Kasir</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <style>
        body { font-family: 'Poppins', sans-serif; background-color: #ffffff; color: #000; margin: 0; overflow: hidden; }
        
        .main-wrapper { display: flex; height: 100vh; }

        /* SIDEBAR - Sesuai Lebar Gambar */
        .sidebar { 
            width: 220px; 
            border-right: 1px solid #e0e0e0; 
            display: flex; 
            flex-direction: column; 
            padding: 30px 0;
        }
        .brand { padding: 0 25px 40px; font-weight: 800; font-size: 1.5rem; }

        .nav-link-custom { 
            padding: 12px 25px; 
            display: flex; 
            align-items: center; 
            text-decoration: none; 
            color: #333; 
            font-weight: 500;
            font-size: 0.95rem;
        }
        .nav-link-custom i { width: 30px; font-size: 1.2rem; }
        .nav-link-custom.active { 
            background-color: #448b39; 
            color: white; 
            border-radius: 0 12px 12px 0; 
            margin-right: 15px; 
        }
        .nav-link-custom:hover:not(.active) { color: #448b39; }

        /* CONTENT AREA - Tengah */
        .content-area { 
            flex: 1; 
            border-right: 1px solid #e0e0e0; 
            display: flex; 
            flex-direction: column; 
        }
        .top-header { 
            padding: 15px 30px; 
            border-bottom: 1px solid #f0f0f0; 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
        }
        .search-bar { 
            background-color: #e9e9e9; 
            border: none; 
            border-radius: 6px; 
            padding: 10px 15px; 
            width: 450px; 
            font-size: 0.85rem;
        }

        .main-scroll { padding: 30px; overflow-y: auto; flex: 1; }
        .grid-menu { 
            display: grid; 
            grid-template-columns: repeat(5, 1fr); 
            gap: 20px; 
        }
        .menu-card { text-align: center; margin-bottom: 15px; }
        .menu-card img { 
            width: 100%; 
            border-radius: 15px; 
            aspect-ratio: 1/1; 
            object-fit: cover; 
            margin-bottom: 10px; 
        }
        .menu-name { font-weight: 700; font-size: 0.85rem; margin: 0; }
        .menu-price { color: #666; font-size: 0.75rem; }

        /* CART AREA - Kanan */
        .cart-area { width: 320px; display: flex; flex-direction: column; padding: 25px; }
        .cart-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; }
        .cart-head h6 { font-weight: 700; margin: 0; }
        .btn-bersihkan { color: #ff3b3b; text-decoration: none; font-size: 0.8rem; font-weight: 700; }

        .cart-list { flex: 1; overflow-y: auto; }
        .cart-item { display: flex; align-items: center; margin-bottom: 20px; font-size: 0.85rem; }
        .cart-item img { width: 55px; height: 50px; border-radius: 10px; object-fit: cover; margin-right: 15px; }
        
        .qty-box { display: flex; align-items: center; gap: 8px; }
        .qty-btn { 
            width: 22px; height: 22px; border: none; border-radius: 4px; 
            font-size: 0.75rem; display: flex; align-items: center; justify-content: center; 
        }

        .footer-cart { border-top: 1px solid #eee; padding-top: 20px; }
        .row-total { display: flex; justify-content: space-between; margin-bottom: 8px; font-size: 0.95rem; }
        .total-bold { font-weight: 800; font-size: 1.2rem; margin: 10px 0 25px; }

        .pay-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 15px; }
        .pay-btn-opt { 
            background-color: #e5e5e5; border: none; padding: 15px; 
            border-radius: 10px; font-weight: 600; font-size: 0.85rem; 
        }
        .btn-checkout-utama { 
            background-color: #448b39; color: white; border: none; 
            width: 100%; padding: 15px; border-radius: 10px; font-weight: 700; 
        }

        /* User Info Top Right */
        .user-panel { display: flex; align-items: center; gap: 12px; }
        .user-meta { text-align: right; line-height: 1.1; }
        .user-name { font-weight: 700; font-size: 0.9rem; }
        .user-role { font-size: 0.75rem; color: #777; }
        .user-avatar { width: 40px; height: 40px; border-radius: 50%; object-fit: cover; }

        .pay-btn-opt {
            transition: all 0.3s ease;
            border: none;
            cursor: pointer;
        }
        .pay-btn-opt.btn-success {
            background-color: #448b39 !important; /* Hijau sesuai gambar dashboard */
            color: white !important;
        }
    </style>
</head>
<body>

<div class="main-wrapper">
    <div class="sidebar">
        <div class="brand">Teh Tarik 99</div>
        <nav class="flex-grow-1">
            <a href="{{ route('kasir.dashboard') }}" class="nav-link-custom {{ request()->is('kasir/dashboard') ? 'active' : '' }}">
                <i class="fa-solid fa-table-cells-large"></i> Dashboard
            </a>
            
            <a href="{{ route('kasir.transaksi') }}" class="nav-link-custom {{ request()->is('kasir/transaksi') ? 'active' : '' }}">
                <i class="fa-solid fa-receipt"></i> Riwayat
            </a>

            <a href="{{ route('kasir.laporan') }}" class="nav-link-custom {{ request()->is('kasir/laporan') ? 'active' : '' }}">
                <i class="fa-solid fa-chart-simple"></i> Laporan
            </a>
            
            <a href="{{ route('kasir.stok') }}" class="nav-link-custom {{ request()->is('kasir/stok') ? 'active' : '' }}">
                <i class="fa-solid fa-calendar-days"></i> Stok
            </a>
            
        </nav>
        <div class="mt-auto">
            <a href="#" class="nav-link-custom"><i class="fa-regular fa-circle-user"></i> Profil</a>
            <form action="{{ route('logout') }}" method="POST">
                @csrf
                <button type="submit" class="nav-link-custom border-0 bg-transparent text-danger w-100 text-start">
                    <i class="fa-solid fa-arrow-right-from-bracket"></i> Keluar
                </button>
            </form>
        </div>
    </div>

     <div class="content-area">
        <div class="top-header">
            <input type="text" class="search-bar" id="search-menu" placeholder="cari produk...">
            <div class="user-panel d-flex align-items-center gap-3">
                <i class="fa-solid fa-bell fs-5"></i>
                <div class="text-end" style="line-height: 1.2;">
                    <div class="fw-bold small">{{ auth()->user()->name }}</div>
                    <div class="text-muted" style="font-size: 0.7rem;">Kasir</div>
                </div>
                <img src="https://ui-avatars.com/api/?name={{ urlencode(auth()->user()->name) }}&background=448b39&color=fff" 
                    class="user-avatar" style="width: 35px; height: 35px; border-radius: 50%;">
            </div>
        </div>

        <div class="main-scroll">
            <h4 class="fw-bold m-0">Dashboard</h4>
            <p id="current-date" class="text-muted small mb-4">Memuat data...</p>

            <div class="grid-menu">
                @foreach($produks as $m)
                <div class="menu-card menu-item" onclick="addToCart('{{ $m->nama_produk }}', {{ $m->harga }}, '{{ $m->gambar ? asset($m->gambar) : 'https://via.placeholder.com/150' }}')" style="cursor: pointer;">
                    <img src="{{ $m->gambar ? asset($m->gambar) : 'https://via.placeholder.com/150' }}" onerror="this.src='https://via.placeholder.com/150'">
                    
                    <p class="menu-name item-name">{{ $m->nama_produk }}</p>
                    
                    <p class="menu-price">Rp. {{ number_format($m->harga, 0, ',', '.') }}</p>
                </div>
                @endforeach
            </div>
        </div>
    </div>

    <div class="cart-area">
        <div class="cart-head">
            <h6>Keranjang Belanja</h6>
            <a href="javascript:void(0)" class="btn-bersihkan" onclick="clearCart()">
        <i class="fa-solid fa-trash-can"></i> Bersihkan
    </a>
        </div>

    <div class="cart-list" id="cart-items">
    <div id="empty-cart-msg" class="text-center text-muted mt-5">
        <i class="fa-solid fa-cart-shopping fs-1 mb-3"></i>
        <p>Keranjang masih kosong</p>
    </div>
    </div>

            <div class="footer-cart">
            <div class="row-total text-muted">
                <span>Subtotal</span>
                <span id="subtotal-display">Rp. 0</span>
            </div>
            <div class="row-total total-bold">
                <span>Total</span>
                <span id="total-display">Rp. 0</span>
            </div>
            
            <div class="pay-grid">
                <button type="button" class="pay-btn-opt bg-light w-100" id="btn-tunai">
                    <i class="fa-solid fa-money-bill-wave me-1"></i> Tunai
                </button>
                <button type="button" class="pay-btn-opt bg-light w-100" id="btn-qris">
                    <i class="fa-solid fa-qrcode me-1"></i> QRIS
                </button>
            </div>
            <button class="btn btn-success w-100 py-3 fw-bold mt-3 btn-checkout-utama" 
                    style="border-radius: 12px; background-color: #448b39;" 
                    onclick="checkout()">
                Bayar Sekarang
            </button>
        </div>
    </div>
</div>


<div class="modal fade" id="modalBayar" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content" style="border-radius: 20px; border: none;">
            <div class="modal-header border-0 pt-4 px-4">
                <h5 class="fw-bold">Pembayaran <span id="text-metode" class="badge bg-success"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body px-4 pb-4">
                <div class="p-3 mb-3" style="background-color: #f8f9fa; border-radius: 15px;">
                    <p class="text-muted small mb-1">Total Tagihan</p>
                    <h3 class="fw-bold text-dark m-0" id="modal-total-tagihan">Rp. 0</h3>
                </div>
                
                <div class="mb-3">
                    <label class="form-label small fw-bold">Uang Diterima</label>
                    <div class="input-group">
                        <span class="input-group-text bg-white border-end-0">Rp</span>
                        <input type="number" id="input-uang-bayar" class="form-control border-start-0 ps-0 fw-bold" style="font-size: 1.2rem;" placeholder="0">
                    </div>
                </div>

                <div class="p-3" style="background-color: #e8f5e9; border-radius: 15px;">
                    <p class="text-success small mb-1 fw-bold">Kembalian</p>
                    <h3 class="fw-bold text-success m-0" id="text-kembalian">Rp. 0</h3>
                </div>
            </div>
            <div class="modal-footer border-0 p-4">
                <button type="button" class="btn btn-light w-100 py-3 fw-bold" data-bs-dismiss="modal" style="border-radius: 12px;">Batal</button>
                <button type="button" class="btn btn-success w-100 py-3 fw-bold" id="btn-proses-simpan" style="border-radius: 12px; background-color: #448b39;" onclick="prosesSimpanKeDatabase()">Selesaikan Transaksi</button>
            </div>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    let cart = [];

    function addToCart(name, price, image) {
        const existingItem = cart.find(item => item.name === name);
        if (existingItem) {
            existingItem.qty += 1;
        } else {
            cart.push({ name, price, image, qty: 1 });
        }
        renderCart();
    }

    function removeFromCart(index) {
        if (cart[index].qty > 1) {
            cart[index].qty -= 1;
        } else {
            cart.splice(index, 1);
        }
        renderCart();
    }

    function renderCart() {
        const cartContainer = document.getElementById('cart-items');
        
        if (cart.length === 0) {
            cartContainer.innerHTML = `
                <div id="empty-cart-msg" class="text-center text-muted mt-5">
                    <i class="fa-solid fa-cart-shopping fs-1 mb-3"></i>
                    <p>Keranjang masih kosong</p>
                </div>`;
            updateTotal(0);
            return;
        }

        cartContainer.innerHTML = '';
        let total = 0;

        cart.forEach((item, index) => {
            const subtotal = item.price * item.qty;
            total += subtotal;

            cartContainer.innerHTML += `
                <div class="cart-item">
                    <img src="${item.image}" alt="${item.name}" onerror="this.src='https://via.placeholder.com/50'">
                    <div class="flex-grow-1">
                        <div class="fw-bold">${item.name}</div>
                        <div class="text-muted small">Rp. ${item.price.toLocaleString('id-ID')}</div>
                    </div>
                    <div class="qty-box">
                        <button class="qty-btn bg-light" onclick="removeFromCart(${index})">-</button>
                        <span class="fw-bold small">${item.qty}</span>
                        <button class="qty-btn bg-success text-white" onclick="addToCart('${item.name}', ${item.price}, '${item.image}')">+</button>
                    </div>
                </div>`;
        });

        updateTotal(total);
    }

    function updateTotal(total) {
        // Mencari elemen berdasarkan ID yang kita buat tadi
        const subtotalDisplay = document.getElementById('subtotal-display');
        const totalDisplay = document.getElementById('total-display');

        if (subtotalDisplay && totalDisplay) {
            // Mengubah teks menjadi format Rupiah yang rapi
            const formattedTotal = `Rp. ${total.toLocaleString('id-ID')}`;
            subtotalDisplay.innerText = formattedTotal;
            totalDisplay.innerText = formattedTotal;
        }
    }

    function updateDashboardHeader() {
    const now = new Date();
    const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
    const dateString = now.toLocaleDateString('id-ID', options);
    
    const hours = now.getHours();
    let greeting = "";
    
    if (hours >= 5 && hours < 11) greeting = "Selamat Pagi";
    else if (hours >= 11 && hours < 15) greeting = "Selamat Siang";
    else if (hours >= 15 && hours < 18) greeting = "Selamat Sore";
    else greeting = "Selamat Malam";

    // Mengambil nama depan kasir secara dinamis
    const userName = "{{ explode(' ', auth()->user()->name)[0] }}"; 

    const headerElement = document.getElementById('current-date');
    if (headerElement) {
        headerElement.innerText = `${dateString} | ${greeting}, ${userName}`;
    }
}

// Jalankan fungsi saat halaman selesai dimuat
updateDashboardHeader();

// Fungsi Pencarian Real-time
const searchInput = document.getElementById('search-menu');

if (searchInput) {
    searchInput.addEventListener('input', function() {
        const keyword = this.value.toLowerCase();
        const menuCards = document.querySelectorAll('.menu-item');

        menuCards.forEach(card => {
            // Ambil teks nama dari element dengan class item-name
            const menuName = card.querySelector('.item-name').innerText.toLowerCase();
            
            if (menuName.includes(keyword)) {
                card.style.display = ""; // Tampilkan jika cocok
            } else {
                card.style.display = "none"; // Sembunyikan jika tidak cocok
            }
        });
    });
}

// 1. Pastikan variabel ini ada di paling atas script agar bisa diakses semua fungsi
let selectedMethod = ''; 

// 2. Logika Pilih Metode Pembayaran
const payButtons = document.querySelectorAll('.pay-btn-opt');
payButtons.forEach(btn => {
    btn.addEventListener('click', function() {
        payButtons.forEach(b => {
            b.classList.remove('btn-success', 'text-white');
            b.classList.add('bg-light');
            b.style.backgroundColor = ''; 
        });

        this.classList.remove('bg-light');
        this.classList.add('btn-success', 'text-white');
        this.style.backgroundColor = '#448b39'; 

        selectedMethod = this.innerText.trim();
    });
});

// 3. Fungsi Checkout yang Benar
function checkout() {
    if (cart.length === 0) {
        alert("Keranjang masih kosong, pilih menu dulu ya!");
        return;
    }

    if (selectedMethod === '') {
        alert("Silakan pilih metode pembayaran (Tunai/QRIS) terlebih dahulu!");
        return;
    }

    // PERBAIKAN: Gunakan .qty bukan .quantity
    let totalBayar = cart.reduce((sum, item) => sum + (item.price * item.qty), 0);
    
    // Panggil Modal Kalkulator
    var modalElement = document.getElementById('modalBayar');
    if (modalElement) {
        document.getElementById('text-metode').innerText = selectedMethod;
        document.getElementById('modal-total-tagihan').innerText = `Rp. ${totalBayar.toLocaleString('id-ID')}`;
        
        // Reset input kalkulator
        document.getElementById('input-uang-bayar').value = '';
        document.getElementById('text-kembalian').innerText = 'Rp. 0';
        
        var myModal = new bootstrap.Modal(modalElement);
        myModal.show();
    } else {
        // Fallback jika modal belum terpasang di HTML
        if (confirm(`Total: Rp. ${totalBayar.toLocaleString('id-ID')} via ${selectedMethod}. Lanjutkan?`)) {
            // panggil fungsi simpan ke database
        }
    }
}

// Logika Kalkulator Kembalian Otomatis
document.getElementById('input-uang-bayar').addEventListener('input', function() {
    const totalTagihan = cart.reduce((sum, item) => sum + (item.price * item.qty), 0);
    const uangDiterima = parseInt(this.value) || 0;
    const kembalian = uangDiterima - totalTagihan;
    
    const displayKembalian = document.getElementById('text-kembalian');
    if (kembalian < 0) {
        displayKembalian.innerText = 'Uang Kurang';
        displayKembalian.classList.replace('text-success', 'text-danger');
    } else {
        displayKembalian.innerText = `Rp. ${kembalian.toLocaleString('id-ID')}`;
        displayKembalian.classList.replace('text-danger', 'text-success');
    }
});

function prosesSimpanKeDatabase() {
    // 1. Persiapan Data untuk Struk
    const totalBayar = cart.reduce((sum, item) => sum + (item.price * item.qty), 0);
    const metode = selectedMethod;
    const waktu = new Date().toLocaleString('id-ID', { 
        weekday: 'long', 
        year: 'numeric', 
        month: 'long', 
        day: 'numeric', 
        hour: '2-digit', 
        minute: '2-digit' 
    });
    const kasir = "{{ auth()->user()->name }}";
    const idTransaksi = "TRX-" + Math.floor(Date.now() / 1000);

    // 2. Loop Item untuk Detail Pesanan di Struk Digital
    let itemHtml = '';
    cart.forEach(item => {
        itemHtml += `
            <div style="display: flex; justify-content: space-between; margin-bottom: 8px; font-size: 0.85rem;">
                <div style="text-align: left;">
                    <span style="font-weight: bold; display: block; color: #333;">${item.name}</span>
                    <span style="color: #666;">${item.qty}x Rp. ${item.price.toLocaleString('id-ID')}</span>
                </div>
                <div style="font-weight: bold; color: #333;">Rp. ${(item.qty * item.price).toLocaleString('id-ID')}</div>
            </div>`;
    });

    // 3. Proses Pengiriman ke Server
    fetch("{{ route('kasir.simpan_transaksi') }}", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-CSRF-TOKEN": "{{ csrf_token() }}"
        },
        body: JSON.stringify({
            total: totalBayar,
            metode: metode,
            items: cart
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Tutup modal kalkulator input uang
            const modalElement = document.getElementById('modalBayar');
            const modalInstance = bootstrap.Modal.getInstance(modalElement);
            if (modalInstance) modalInstance.hide();

            // 4. Tampilkan Struk Digital (Tanpa Timer agar tidak hilang sendiri)
            Swal.fire({
                html: `
                    <div style="text-align: center; font-family: 'Poppins', sans-serif;">
                        <div style="background: #448b39; width: 55px; height: 55px; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 15px;">
                            <i class="fa-solid fa-check text-white fs-3"></i>
                        </div>
                        <h4 style="font-weight: 800; margin-bottom: 5px; color: #333;">Transaksi Berhasil!</h4>
                        <p style="color: #888; font-size: 0.8rem; margin-bottom: 25px;">Pesanan telah diproses dan dicatat</p>
                        
                        <div style="border: 1px solid #eee; border-radius: 15px; padding: 20px; text-align: left; background: #fff; box-shadow: 0 4px 10px rgba(0,0,0,0.02);">
                            <p style="text-align: center; font-size: 0.65rem; font-weight: bold; color: #bbb; letter-spacing: 2px; margin-bottom: 15px; text-transform: uppercase;">Struk Digital</p>
                            
                            <div style="font-size: 0.75rem; color: #555; margin-bottom: 15px; border-bottom: 1px dashed #eee; padding-bottom: 10px; line-height: 1.6;">
                                <div style="display: flex; justify-content: space-between;"><span>ID Transaksi</span> <b style="color: #000;">#${idTransaksi}</b></div>
                                <div style="display: flex; justify-content: space-between;"><span>Waktu</span> <b style="color: #000;">${waktu} WIB</b></div>
                                <div style="display: flex; justify-content: space-between;"><span>Kasir</span> <b style="color: #000;">${kasir}</b></div>
                            </div>

                            <p style="font-size: 0.8rem; font-weight: bold; color: #448b39; margin-bottom: 12px;">Detail Pesanan</p>
                            <div style="max-height: 150px; overflow-y: auto; margin-bottom: 10px;">
                                ${itemHtml}
                            </div>
                            
                            <div style="border-top: 1px solid #eee; margin-top: 15px; padding-top: 12px;">
                                <div style="display: flex; justify-content: space-between; font-weight: 800; font-size: 1.15rem;">
                                    <span>Total</span>
                                    <span style="color: #448b39;">Rp. ${totalBayar.toLocaleString('id-ID')}</span>
                                </div>
                                <div style="display: flex; justify-content: space-between; font-size: 0.8rem; color: #666; margin-top: 6px;">
                                    <span>Metode Pembayaran</span>
                                    <span style="font-weight: 600; color: #333;"><i class="fa-solid fa-wallet me-1"></i> ${metode}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                `,
                showDenyButton: true,
                confirmButtonText: '<i class="fa-solid fa-print"></i> Cetak Struk',
                denyButtonText: '<i class="fa-solid fa-cart-plus"></i> Transaksi Baru',
                confirmButtonColor: '#448b39',
                denyButtonColor: '#6c757d',
                allowOutsideClick: false, // Penting: agar info ID/Waktu tidak hilang jika asal klik
                width: '450px'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Jalankan fungsi cetak struk fisik
                    cetakStruk(idTransaksi, waktu, kasir, cart, totalBayar, metode);
                    
                    // Beri jeda sebentar sebelum refresh agar proses cetak muncul
                    setTimeout(() => { location.reload(); }, 1500);
                } else if (result.isDenied) {
                    // Langsung transaksi baru
                    location.reload();
                }
            });
        }
    })
    .catch(error => {
        console.error("Error:", error);
        Swal.fire('Error', 'Gagal menyimpan transaksi ke database', 'error');
    });
}

function cetakStruk(idTrx, waktu, kasir, items, total, metode) {
    // Membuat jendela cetak baru (hidden)
    const printWindow = window.open('', '_blank');
    
    // Desain Struk untuk Printer Kasir (Thermal 58mm/80mm)
    let strukHtml = `
        <html>
        <head>
            <title>Cetak Struk - ${idTrx}</title>
            <style>
                body { font-family: 'Courier New', Courier, monospace; width: 300px; padding: 10px; margin: 0; }
                .text-center { text-align: center; }
                .line { border-bottom: 1px dashed #000; margin: 10px 0; }
                .item-row { display: flex; justify-content: space-between; font-size: 14px; margin-bottom: 5px; }
                .total-row { display: flex; justify-content: space-between; font-weight: bold; font-size: 16px; }
                @media print { @page { margin: 0; } body { margin: 0; } }
            </style>
        </head>
        <body onload="window.print(); window.close();">
            <div class="text-center">
                <h2 style="margin: 0;">TEH TARIK 99</h2>
                <p style="font-size: 12px; margin: 5px 0;">Jl. Contoh No. 123, Kota Anda</p>
                <div class="line"></div>
                <p style="font-size: 12px; margin: 5px 0;">
                    ${idTrx}<br>${waktu}<br>Kasir: ${kasir}
                </p>
                <div class="line"></div>
            </div>
    `;

    items.forEach(item => {
        strukHtml += `
            <div class="item-row">
                <span>${item.name} (${item.qty}x)</span>
                <span>Rp. ${(item.qty * item.price).toLocaleString('id-ID')}</span>
            </div>`;
    });

    strukHtml += `
            <div class="line"></div>
            <div class="total-row">
                <span>TOTAL</span>
                <span>Rp. ${total.toLocaleString('id-ID')}</span>
            </div>
            <div class="item-row" style="font-size: 12px; margin-top: 5px;">
                <span>Metode</span>
                <span>${metode}</span>
            </div>
            <div class="line"></div>
            <p class="text-center" style="font-size: 12px;">Terima Kasih Atas Kunjungannya!</p>
        </body>
        </html>
    `;

    printWindow.document.write(strukHtml);
    printWindow.document.close();
}

function clearCart() {
    // 1. Cek apakah keranjang memang ada isinya
    if (cart.length === 0) return;

    // 2. Gunakan SweetAlert untuk konfirmasi agar lebih cantik
    Swal.fire({
        title: 'Kosongkan Keranjang?',
        text: "Semua menu yang sudah dipilih akan dihapus.",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ff3b3b',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Ya, Bersihkan!',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            // 3. Kosongkan array keranjang
            cart = [];
            
            // 4. Update tampilan UI
            renderCart();
            
            // 5. Reset pilihan metode pembayaran
            selectedMethod = '';
            payButtons.forEach(b => {
                b.classList.remove('btn-success', 'text-white');
                b.classList.add('bg-light');
                b.style.backgroundColor = ''; 
            });
        }
    });
}
</script>

</body>
</html>