@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>Pilih Pembeli</label>
        <div class="d-flex align-items-center mb-2">
            <button type="button" id="btn-scan-qr" class="btn btn-default btn-sm mr-2">Scan QR</button>
            <select id="buyer_type" name="buyer_type" class="form-control mr-2" style="width:120px;">
                <option value="member">Member</option>
                <option value="visitor">Visitor</option>
            </select>
            <input type="hidden" name="buyer_id" id="buyer_id">
        </div>
        <input type="text" id="buyer_search" class="form-control" placeholder="Cari nama pembeli..." autocomplete="off">
        <div id="buyer_suggestion" class="list-group mt-1"></div>
        <div id="buyer_detail" class="mt-2"></div>
        <div id="qr_area" class="mt-3" style="display:none;">
            <div id="reader" style="width:180px;"></div>
        </div>
    </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>

    <div class="form-group">
        <label>Metode Pembayaran</label>
        <select name="payment_method" class="form-control" required>
            <option value="cash" selected>Cash</option>
            <option value="QRIS">QRIS</option>
        </select>
    </div>
    <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>
const members = @json($members);
const visitors = @json($visitors);

function searchBuyer(type, keyword) {
    let data = type === 'visitor' ? visitors : members;
    return data.filter(item => item.nama.toLowerCase().includes(keyword.toLowerCase()));
}

document.addEventListener('DOMContentLoaded', function() {
    // Opsi Scan QR
    document.getElementById('btn-scan-qr').onclick = function() {
        document.getElementById('qr_area').style.display = 'block';
    };

    // Autocomplete pembeli
    const buyerType = document.getElementById('buyer_type');
    const buyerSearch = document.getElementById('buyer_search');
    const buyerSuggest = document.getElementById('buyer_suggestion');
    const buyerDetail = document.getElementById('buyer_detail');
    const buyerId = document.getElementById('buyer_id');

    buyerSearch.addEventListener('input', function() {
        const keyword = this.value;
        const type = buyerType.value;
        if (keyword.length < 1) {
            buyerSuggest.innerHTML = '';
            return;
        }
        const hasil = searchBuyer(type, keyword);
        buyerSuggest.innerHTML = '';
        hasil.forEach(function(b) {
            const item = document.createElement('a');
            item.href = "#";
            item.className = "list-group-item list-group-item-action";
            item.textContent = b.nama + (b.alamat ? ' ('+b.alamat+')' : '');
            item.onclick = function() {
                buyerSearch.value = b.nama;
                buyerId.value = b.id;
                buyerDetail.innerHTML = '<b>Nama:</b> '+b.nama+'<br><b>Alamat:</b> '+(b.alamat||'-')+'<br><b>Kontak:</b> '+(b.kontak||'-');
                buyerSuggest.innerHTML = '';
                return false;
            };
            buyerSuggest.appendChild(item);
        });
    });

    buyerType.addEventListener('change', function() {
        buyerSearch.value = '';
        buyerId.value = '';
        buyerDetail.innerHTML = '';
        buyerSuggest.innerHTML = '';
    });

    // QR SCAN LOGIC
    function onScanSuccess(qrCodeMessage) {
        let type = buyerType.value;
        let found = (type === 'member' ? members : visitors).find(x => x.id == qrCodeMessage);
        if(found){
            buyerId.value = found.id;
            buyerSearch.value = found.nama;
            buyerDetail.innerHTML = '<b>Nama:</b> '+found.nama+'<br><b>Alamat:</b> '+(found.alamat||'-')+'<br><b>Kontak:</b> '+(found.kontak||'-');
            document.getElementById('qr_area').style.display = 'none';
        } else {
            buyerDetail.innerHTML = '<span class="text-danger">Data tidak ditemukan</span>';
        }
    }
    if(document.getElementById('reader')){
        let html5QrcodeScanner = new Html5QrcodeScanner(
            "reader", { fps: 10, qrbox: 200 });
        html5QrcodeScanner.render(onScanSuccess);
    }

    // Produk dinamis & total
    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();
    });

    function updateTotal() {
        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;
        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);
    setTimeout(updateTotal, 300);
});
</script>
@endpush
@stop