<!DOCTYPE html>
<html lang="id" class="h-full">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Riwayat Transaksi — {{ \App\Models\Setting::get('store_name', 'POS UMKM') }}</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <script>tailwind.config={theme:{extend:{fontFamily:{sans:['Plus Jakarta Sans','sans-serif']}}}}</script>
</head>
<body class="bg-slate-50 font-sans min-h-full overflow-x-hidden">



{{-- Header --}}
<header class="bg-slate-900 text-white px-4 py-3 flex items-center gap-3">
    <a href="{{ route('pos.index') }}" class="p-1.5 rounded-lg hover:bg-slate-700 transition text-slate-400 hover:text-white">
        ← Kembali
    </a>
    <div class="font-bold">Riwayat Transaksi Hari Ini</div>
    <div class="ml-auto text-sm text-slate-400" id="clock"></div>
</header>

<div class="max-w-4xl mx-auto p-4 space-y-4">


    {{-- Filter & Search --}}
    <div class="flex gap-2">
        <input type="text" id="searchTrx" placeholder="🔍 Cari invoice atau pelanggan..."
            class="flex-1 px-3 py-2 border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-400 bg-white">
        <select id="filterMethod" class="px-3 py-2 border border-slate-200 rounded-xl text-sm bg-white focus:outline-none">
            <option value="">Semua Metode</option>
            <option value="cash">Tunai</option>
            <option value="qris">QRIS</option>
            <option value="transfer">Transfer</option>
        </select>
    </div>

    {{-- Tabel Transaksi --}}
    <div class="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
        <div class="px-4 py-3 border-b border-slate-200">
            <h3 class="font-bold text-slate-800">Daftar Transaksi</h3>
        </div>

        @forelse($transactions as $trx)
        <div class="trx-row border-b border-slate-100 last:border-0 hover:bg-slate-50 transition cursor-pointer"
             data-invoice="{{ strtolower($trx->invoice_number) }}"
             data-customer="{{ strtolower($trx->customer_name ?? '') }}"
             data-method="{{ $trx->payment_method }}"
             onclick="toggleDetail('detail-{{ $trx->id }}')">

            <div class="px-4 py-3 flex items-center gap-3">
                {{-- Status icon --}}
                <div class="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0
                    {{ $trx->payment_method === 'cash' ? 'bg-emerald-100' : ($trx->payment_method === 'qris' ? 'bg-purple-100' : 'bg-blue-100') }}">
                    <span class="text-lg">
                        {{ $trx->payment_method === 'cash' ? '💵' : ($trx->payment_method === 'qris' ? '📱' : '🏦') }}
                    </span>
                </div>

                <div class="flex-1 min-w-0">
                    <div class="flex items-center gap-2">
                        <span class="font-mono text-xs font-bold text-blue-600">{{ $trx->invoice_number }}</span>
                        <span class="text-xs text-slate-400">{{ $trx->transaction_date->format('H:i') }}</span>
                    </div>
                    <div class="text-xs text-slate-500 truncate">
                        {{ $trx->customer_name ?? 'Umum' }} · {{ $trx->items->count() }} item
                    </div>
                </div>

                <div class="text-right flex-shrink-0">
                    <div class="font-bold {{ $trx->status === 'void' ? 'text-slate-400 line-through' : 'text-slate-800' }}">Rp {{ number_format($trx->grand_total, 0, ',', '.') }}</div>
                    @if($trx->status === 'void')
                    <div class="text-[10px] font-black text-red-600 bg-red-100 px-1.5 py-0.5 rounded-md uppercase tracking-tighter mt-1">DIBATALKAN (VOID)</div>
                    @elseif($trx->discount_amount > 0)
                    <div class="text-xs text-amber-600">-Rp {{ number_format($trx->discount_amount, 0, ',', '.') }}</div>
                    @endif
                </div>

                <div class="flex items-center gap-2">
                    <button onclick="printReceipt({{ $trx->id }})"
                       class="p-1.5 rounded-lg bg-slate-100 hover:bg-blue-100 text-slate-500 hover:text-blue-600 transition text-xs" title="Cetak Struk">
                        🖨️
                    </button>
                    @if($trx->status !== 'void' && \App\Models\Setting::get('void_feature_enabled', false))
                    <button onclick="openVoidModal({{ $trx->id }}, '{{ $trx->invoice_number }}')"
                       class="p-1.5 rounded-lg bg-red-50 hover:bg-red-100 text-red-400 hover:text-red-600 transition text-xs" title="Void Transaksi">
                        🚫
                    </button>
                    @endif
                    <span class="text-slate-300 text-xs" id="arrow-{{ $trx->id }}">▼</span>
                </div>
            </div>

            {{-- Detail items (collapsed) --}}
            <div id="detail-{{ $trx->id }}" class="hidden px-4 pb-3">
                <div class="bg-slate-50 rounded-xl p-3 text-xs space-y-1.5">
                    @foreach($trx->items as $item)
                    <div class="flex justify-between">
                        <span class="text-slate-600">{{ $item->product_name }}</span>
                        <span class="text-slate-800 font-medium">
                            {{ $item->quantity }}x Rp{{ number_format($item->unit_price, 0, ',', '.') }}
                            = Rp{{ number_format($item->subtotal, 0, ',', '.') }}
                        </span>
                    </div>
                    @endforeach

                    <div class="border-t border-slate-200 pt-1.5 mt-1.5 space-y-1">
                        <div class="flex justify-between">
                            <span class="text-slate-500">Subtotal</span>
                            <span>Rp{{ number_format($trx->subtotal, 0, ',', '.') }}</span>
                        </div>
                        @if($trx->discount_amount > 0)
                        <div class="flex justify-between text-amber-600">
                            <span>Diskon</span>
                            <span>-Rp{{ number_format($trx->discount_amount, 0, ',', '.') }}</span>
                        </div>
                        @endif
                        @if($trx->tax_amount > 0)
                        <div class="flex justify-between text-slate-500">
                            <span>PPN ({{ $trx->tax_percent }}%)</span>
                            <span>Rp{{ number_format($trx->tax_amount, 0, ',', '.') }}</span>
                        </div>
                        @endif
                        <div class="flex justify-between font-bold text-slate-800 border-t border-slate-200 pt-1">
                            <span>Total</span>
                            <span>Rp{{ number_format($trx->grand_total, 0, ',', '.') }}</span>
                        </div>
                        @if($trx->payment_method === 'cash')
                        <div class="flex justify-between text-slate-500">
                            <span>Bayar</span>
                            <span>Rp{{ number_format($trx->amount_paid, 0, ',', '.') }}</span>
                        </div>
                        <div class="flex justify-between text-emerald-600 font-semibold">
                            <span>Kembali</span>
                            <span>Rp{{ number_format($trx->change_amount, 0, ',', '.') }}</span>
                        </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>
        @empty
        <div class="px-4 py-16 text-center text-slate-400">
            <div class="text-5xl mb-3">🧾</div>
            <div class="font-medium">Belum ada transaksi hari ini</div>
        </div>
        @endforelse
    </div>

    {{-- Pagination --}}
    <div class="pb-4">
        {{ $transactions->links() }}
    </div>
</div>

{{-- MODAL: VOID AUTHORIZATION --}}
<div id="voidModal" class="fixed inset-0 z-[300] flex items-center justify-center p-4 bg-slate-900/80 backdrop-blur hidden">
    <div class="bg-white rounded-3xl shadow-2xl w-full max-w-sm overflow-hidden scale-in">
        <div class="bg-red-600 px-6 py-6 text-white text-center relative">
            <h3 class="text-xl font-black">VOID TRANSAKSI</h3>
            <p id="voidInvoiceDisplay" class="text-red-100 text-xs mt-1 font-mono uppercase"></p>
        </div>
        <div class="p-6 space-y-4">
            <div>
                <label class="text-[10px] font-bold text-slate-400 uppercase tracking-widest block mb-1">Alasan Pembatalan</label>
                <textarea id="voidReason" class="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-2xl focus:ring-2 focus:ring-red-500 outline-none text-sm h-20" placeholder="Contoh: Kesalahan input item / Customer batal beli"></textarea>
            </div>
            <div>
                <label class="text-[10px] font-bold text-slate-400 uppercase tracking-widest block mb-1">Password Supervisor/Admin</label>
                <input type="password" id="authPassword" class="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-2xl focus:ring-2 focus:ring-red-500 outline-none text-sm" placeholder="••••••">
            </div>

            <div class="pt-2 flex gap-3">
                <button onclick="closeVoidModal()" class="flex-1 py-4 bg-slate-100 text-slate-600 font-bold rounded-2xl text-xs uppercase tracking-widest">Batal</button>
                <button onclick="submitVoid()" class="flex-1 py-4 bg-red-600 text-white font-bold rounded-2xl text-xs uppercase tracking-widest shadow-xl shadow-red-600/20">Konfirmasi Void</button>
            </div>
        </div>
    </div>
</div>

{{-- ALERT MODAL --}}
<div id="alertModal" class="fixed inset-0 z-[400] flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur hidden">
    <div class="bg-white rounded-3xl shadow-2xl w-full max-w-xs p-6 text-center scale-in">
        <div id="alertIcon" class="text-5xl mb-4">⚠️</div>
        <h3 id="alertTitle" class="text-lg font-black text-slate-800">Peringatan</h3>
        <p id="alertMessage" class="text-slate-500 text-sm mt-2"></p>
        <button onclick="document.getElementById('alertModal').classList.add('hidden')" class="mt-6 w-full py-3 bg-slate-900 text-white font-bold rounded-xl text-xs uppercase tracking-widest">Mengerti</button>
    </div>
</div>

<script>
    const CSRF = document.querySelector('meta[name=csrf-token]').content;

    function updateClock() {
        document.getElementById('clock').textContent =
            new Date().toLocaleTimeString('id-ID', {hour:'2-digit',minute:'2-digit',second:'2-digit'});
    }
    setInterval(updateClock, 1000); updateClock();

    // Initial check
    window.onload = () => {
    };

    function toggleDetail(id) {
        const el = document.getElementById(id);
        const arrow = document.getElementById('arrow-' + id.replace('detail-', ''));
        el.classList.toggle('hidden');
        arrow.textContent = el.classList.contains('hidden') ? '▼' : '▲';
    }

    // Live filter
    function filterRows() {
        const q      = document.getElementById('searchTrx').value.toLowerCase();
        const method = document.getElementById('filterMethod').value;

        document.querySelectorAll('.trx-row').forEach(row => {
            const invoice  = row.dataset.invoice || '';
            const customer = row.dataset.customer || '';
            const pm       = row.dataset.method || '';

            const matchSearch = !q || invoice.includes(q) || customer.includes(q);
            const matchMethod = !method || pm === method;

            row.style.display = (matchSearch && matchMethod) ? '' : 'none';
        });
    }

    function printReceipt(id) {
        let iframe = document.getElementById('printFrame');
        if (!iframe) {
            iframe = document.createElement('iframe');
            iframe.id = 'printFrame';
            iframe.style.display = 'none';
            document.body.appendChild(iframe);
        }
        iframe.src = `/pos/receipt/${id}`;
        iframe.onload = function() {
            iframe.contentWindow.print();
        };
    }

    let currentVoidId = null;

    function openVoidModal(id, invoice) {
        currentVoidId = id;
        document.getElementById('voidInvoiceDisplay').textContent = invoice;
        document.getElementById('voidModal').classList.remove('hidden');
    }

    function closeVoidModal() {
        document.getElementById('voidModal').classList.add('hidden');
        document.getElementById('voidReason').value = '';
        document.getElementById('authPassword').value = '';
    }

    async function submitVoid() {
        const reason = document.getElementById('voidReason').value;
        const pass = document.getElementById('authPassword').value;

        if (reason.length < 5) return showAlert('Alasan Terlalu Pendek', 'Berikan alasan yang jelas minimal 5 karakter.', '✍️');
        if (!pass) return showAlert('Password Diperlukan', 'Otorisasi memerlukan password Admin/Manajer.', '🔑');

        try {
            const res = await fetch(`/pos/void/${currentVoidId}`, {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json', 
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': CSRF 
                },
                body: JSON.stringify({ auth_password: pass, reason: reason })
            });

            const contentType = res.headers.get("content-type");
            if (contentType && contentType.indexOf("application/json") !== -1) {
                const data = await res.json();
                if (data.success) {
                    location.reload();
                } else {
                    showAlert('Gagal!', data.message || 'Terjadi kesalahan.', '❌');
                }
            } else {
                const text = await res.text();
                console.error('Server error:', text);
                showAlert('Error Server', 'Respon server tidak valid.', '❌');
            }
        } catch (e) {
            console.error('Fetch error:', e);
            showAlert('Error', 'Gagal menghubungi server. Pastikan koneksi aktif.', '🌐');
        }
    }

    function showAlert(title, message, icon = '⚠️') {
        document.getElementById('alertTitle').textContent = title;
        document.getElementById('alertMessage').textContent = message;
        document.getElementById('alertIcon').textContent = icon;
        document.getElementById('alertModal').classList.remove('hidden');
    }

    document.getElementById('searchTrx').addEventListener('input', filterRows);
    document.getElementById('filterMethod').addEventListener('change', filterRows);
</script>
</body>
</html>
