@extends('adminlte::page')
@section('title', 'Transaksi Produk')
@section('content_header')
    <h1>Transaksi Produk</h1>
@stop
@section('content')

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
        @foreach ($errors->all() as $error)
            <li>{{ $error }}</li>
        @endforeach
        </ul>
    </div>
@endif

<form method="POST" action="{{ route('purchases.store') }}" id="form-transaksi">
    @csrf

    <div class="form-group">
        <label>Scan QR Member (Opsional)</label>
        <div id="reader" style="width: 180px;"></div>
        <input type="text" name="qr_scan" class="form-control mt-2" placeholder="Atau isi manual kode QR/member" id="qr_scan" autocomplete="off">
        <small class="text-muted">Arahkan kamera ke QR member, atau lanjut manual jika bukan member/lupa kartu.</small>
        <input type="hidden" name="member_id" id="member_id">
        <div id="nama_member_view" class="mt-2"></div>
    </div>
    
    <div class="form-group">
        <label>Nama Pembeli <small class="text-muted">(isi jika bukan member)</small></label>
        <input type="text" name="nama_pembeli" class="form-control" placeholder="Nama pembeli non-member">
    </div>
    <div class="form-group">
        <label>Produk & Qty</label>
        <div id="produk-list">
            <div class="row mb-2 align-items-center">
                <div class="col">
                    <select name="produk_id[]" class="form-control produk-select" required>
                        <option value="">- pilih produk -</option>
                        @foreach($products as $p)
                            <option value="{{ $p->id }}" data-harga="{{ $p->harga }}">{{ $p->nama }} ({{ ucfirst(str_replace('_',' ',$p->kategori)) }})</option>
                        @endforeach
                    </select>
                </div>
                <div class="col">
                    <input type="number" name="qty[]" class="form-control qty-input" min="1" value="1" required>
                </div>
                <div class="col-auto">
                    <button type="button" class="btn btn-success btn-tambah">+</button>
                </div>
            </div>
        </div>
    </div>

    {{-- Pembayaran --}}
    <div class="form-group">
        <label>Total Belanja</label>
        <input type="text" class="form-control-plaintext" id="total-belanja" readonly value="Rp 0">
        <input type="hidden" name="total_harga" id="total_harga" value="0">
    </div>
    <div class="form-group">
        <label>Bayar</label>
        <input type="number" name="bayar" id="bayar" class="form-control" min="0" required autocomplete="off" placeholder="Masukkan nominal pembayaran">
    </div>
    <div class="form-group">
        <label>Kembali</label>
        <input type="text" id="kembali" class="form-control-plaintext" readonly value="Rp 0">
    </div>

    <button type="submit" class="btn btn-primary btn-block">Simpan Transaksi & Cetak Struk</button>
</form>

@push('js')
<script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Delegasi event tambah/hapus produk
    document.getElementById('produk-list').addEventListener('click', function(e) {
        if (e.target.classList.contains('btn-tambah')) {
            let row = e.target.closest('.row').cloneNode(true);
            row.querySelector('select').value = '';
            row.querySelector('input').value = 1;
            let btn = row.querySelector('button');
            btn.classList.remove('btn-success', 'btn-tambah');
            btn.classList.add('btn-danger', 'btn-hapus');
            btn.innerText = '-';
            document.getElementById('produk-list').appendChild(row);
        } else if (e.target.classList.contains('btn-hapus')) {
            if(document.querySelectorAll('#produk-list .row').length > 1) {
                e.target.closest('.row').remove();
            }
        }
        updateTotal();
    });

    // QR CAMERA SCANNER
    function onScanSuccess(qrCodeMessage) {
        document.getElementById('qr_scan').value = qrCodeMessage;
        fetch('/api/member-by-qr/'+qrCodeMessage)
            .then(res => res.json())
            .then(data => {
                if(data.id){
                    document.getElementById('member_id').value = data.id;
                    document.getElementById('nama_member_view').innerHTML = '<b>Nama:</b> '+data.nama;
                } else {
                    document.getElementById('member_id').value = '';
                    document.getElementById('nama_member_view').innerHTML = '<span class="text-danger">Member tidak ditemukan</span>';
                }
            });
    }

    if(document.getElementById('reader')){
        let html5QrcodeScanner = new Html5QrcodeScanner(
            "reader", { fps: 10, qrbox: 200 });
        html5QrcodeScanner.render(onScanSuccess);
    }

    // QR Scan logic manual (input text QR)
    const qrScanInput = document.getElementById('qr_scan');
    if(qrScanInput){
        qrScanInput.addEventListener('change', function() {
            let kode = this.value;
            fetch('/api/member-by-qr/'+kode)
                .then(res => res.json())
                .then(data => {
                    if(data.id){
                        document.getElementById('member_id').value = data.id;
                        document.getElementById('nama_member_view').innerHTML = '<b>Nama:</b> '+data.nama;
                    } else {
                        document.getElementById('member_id').value = '';
                        document.getElementById('nama_member_view').innerHTML = '<span class="text-danger">Member tidak ditemukan</span>';
                    }
                });
        });
    }

    // === Hitung total belanja dan kembalian ===
    function updateTotal() {
        // Hitung total semua produk
        let total = 0;
        document.querySelectorAll('#produk-list .row').forEach(function(row) {
            let select = row.querySelector('select');
            let qty = row.querySelector('input').valueAsNumber || 0;
            let harga = select.selectedOptions[0]?.getAttribute('data-harga') || 0;
            total += qty * parseInt(harga);
        });
        document.getElementById('total-belanja').value = 'Rp ' + total.toLocaleString();
        document.getElementById('total_harga').value = total;
        // Update kembalian
        let bayar = parseInt(document.getElementById('bayar').value) || 0;
        let kembali = bayar - total;
        document.getElementById('kembali').value = 'Rp ' + (kembali >= 0 ? kembali.toLocaleString() : 0);
    }

    document.getElementById('produk-list').addEventListener('change', updateTotal);
    document.getElementById('bayar').addEventListener('input', updateTotal);

    // Hitung ulang saat halaman load
    setTimeout(updateTotal, 300);
});
</script>
@endpush
@stop