@extends('layouts.app')

@section('title','Kasir')

@section('content')
<style>
    .produk:active {
        transform: scale(.95);
        background: #e5e7eb;
    }

    .quick-pay {
        border-radius: 12px;
        font-weight: 600;
    }

    .produk img {
        height: 90px;
        object-fit: cover;
        border-radius: 12px;
    }

    .produk {
        min-height: 180px;
    }
</style>
<div class="container py-3">

    <h3 class="mb-3">Kathles POS</h3>

    <input type="text" id="search" class="form-control mb-3" placeholder="Cari produk...">

    <div class="row g-2 mb-4" id="produk-list">

        @foreach($products as $p)

        <div class="col-4 produk-item" data-name="{{ strtolower($p->name) }}">
            <div class="produk" onclick="addItem({{ $p->id }}, '{{ $p->name }}', {{ $p->sell_price }})">

                @if($p->image)

                <img
                    src="{{ asset('storage/'.$p->image) }}"
                    class="img-fluid rounded mb-2"
                    style="height:80px; width:100%; object-fit:cover;">

                @else

                <img
                    src="{{ asset('images/no-image.png') }}"
                    class="img-fluid rounded mb-2"
                    style="height:80px; width:100%; object-fit:cover;">

                @endif

                {{ $p->name }}

                <div class="text-success">
                    Rp {{ number_format($p->sell_price,0,',','.') }}
                </div>

            </div>
        </div>

        @endforeach

    </div>

    <div class="box mb-3">

        <h5>🛒 Keranjang</h5>

        <div id="cartArea"></div>

    </div>

    <div class="box mb-3 d-none" id="paymentBox">
        <div class="d-flex justify-content-between">
            <span>Subtotal</span>
            <span id="subtotal">0</span>
        </div>

        <div class="d-flex justify-content-between mt-2">
            <span>Diskon</span>
            <span>
                <input type="number" id="diskon" value="0" style="width:90px" onkeyup="renderCart()">
            </span>
        </div>

        <hr>

        <div class="d-flex justify-content-between">
            <h5>Total</h5>
            <h5 id="grandtotal">0</h5>
        </div>

        <label>Uang Dibayar</label>
        <input type="number" id="bayar" class="form-control mb-2" onkeyup="renderCart()">
        <input type="number" id="bayar"
            class="form-control mb-2"
            onkeyup="renderCart()">
        <div class="d-flex flex-wrap gap-2 mb-3">

            <button type="button"
                class="btn btn-light quick-pay"
                onclick="setBayar(10000)">

                10rb

            </button>

            <button type="button"
                class="btn btn-light quick-pay"
                onclick="setBayar(20000)">

                20rb

            </button>

            <button type="button"
                class="btn btn-light quick-pay"
                onclick="setBayar(50000)">

                50rb

            </button>

            <button type="button"
                class="btn btn-light quick-pay"
                onclick="setBayar(100000)">

                100rb

            </button>

            <button type="button"
                class="btn btn-success quick-pay"
                onclick="uangPas()">

                UANG PAS

            </button>

        </div>

        <label>Kembalian</label>
        <input type="text" id="kembali" class="form-control" readonly>

    </div>

    <div class="d-grid gap-2">

        <button onclick="showPayment()"
            id="btnBayar"
            class="btn btn-dark btn-lg rounded-4">

            💳 BAYAR

        </button>

        <button onclick="simpanTransaksi()"
            id="btnSimpan"
            class="btn btn-warning btn-lg rounded-4 d-none">

            💰 SIMPAN TRANSAKSI

        </button>

    </div>

    <!-- MODAL SUCCESS -->
    <div class="modal fade"
        id="successModal"
        tabindex="-1">

        <div class="modal-dialog modal-dialog-centered">

            <div class="modal-content border-0 rounded-4">

                <div class="modal-body text-center p-4">

                    <div style="font-size:60px;">
                        ✅
                    </div>

                    <h4 class="mt-3">
                        Transaksi Berhasil
                    </h4>

                    <p class="text-muted">
                        Data penjualan berhasil disimpan
                    </p>

                    <div class="d-grid gap-2 mt-4">

                        <a href="#"
                            id="printBtn"
                            target="_blank"
                            class="btn btn-dark btn-lg rounded-4">

                            🖨️ Cetak Struk

                        </a>

                        <button type="button"
                            class="btn btn-warning btn-lg rounded-4"
                            onclick="newTransaction()">

                            ➕ Transaksi Baru

                        </button>

                    </div>

                </div>

            </div>

        </div>

    </div>

</div>

<script>
    let cart = {};

    function addItem(id, nama, harga) {

        if (cart[id]) {
            cart[id].qty++;
        } else {
            cart[id] = {
                nama: nama,
                harga: harga,
                qty: 1.0
            };
        }

        renderCart();
    }

    function plus(id) {

        cart[id].qty += 1;

        renderCart();

    }

    function minus(id) {

        cart[id].qty -= 1;

        if (cart[id].qty <= 0) {

            delete cart[id];

        }

        renderCart();

    }

    function updateQty(id, value) {

        if (value === '') return;

        let qty = parseFloat(value);

        if (isNaN(qty) || qty <= 0) {

            delete cart[id];

        } else {

            cart[id].qty = qty;

        }

        renderCart();

    }

    function syncQtyInputs() {

        document.querySelectorAll('.qty-input')
            .forEach(input => {

                let id = input.dataset.id;
                let value = input.value;

                if (value === '') return;

                let qty = parseFloat(value);

                if (isNaN(qty) || qty <= 0) {

                    delete cart[id];

                } else {

                    cart[id].qty = qty;

                }

            });

        renderCart();

    }

    function showPayment() {

        syncQtyInputs();

        // tampil payment
        document
            .getElementById('paymentBox')
            .classList.remove('d-none');

        // hide tombol bayar
        document
            .getElementById('btnBayar')
            .classList.add('d-none');

        // tampil tombol simpan
        document
            .getElementById('btnSimpan')
            .classList.remove('d-none');

        // focus input bayar
        let bayarInput =
            document.getElementById('bayar');

        bayarInput.focus();

        bayarInput.scrollIntoView({
            behavior: 'smooth',
            block: 'center'
        });

    }

    function simpanTransaksi() {

        syncQtyInputs();
        if (Object.keys(cart).length === 0) {
            alert('Keranjang kosong');
            return;
        }

        let bayar = document.getElementById('bayar').value;
        let diskon = document.getElementById('diskon').value;

        bayar = parseFloat(bayar || 0);

        let totalText =
            document.getElementById('grandtotal')
            .innerText
            .replace('Rp ', '')
            .replaceAll('.', '')
            .replaceAll(',', '');

        let grandTotal = parseFloat(totalText);

        if (bayar <= 0) {

            Swal.fire({
                icon: 'warning',
                title: 'Uang bayar kurang',
                text: 'Periksa kembali nominal pembayaran'
            });

            document.getElementById('bayar').focus();

            return;

        }

        if (bayar < grandTotal) {

            Swal.fire({
                icon: 'warning',
                title: 'Uang bayar kurang',
                text: 'Periksa kembali nominal pembayaran'
            });

            document.getElementById('bayar').focus();

            return;

        }

        fetch('/sales', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                body: JSON.stringify({
                    cart: cart,
                    bayar: bayar,
                    diskon: diskon
                })
            })
            .then(res => res.json())
            .then(res => {

                // set tombol print
                document.getElementById('printBtn').href =
                    '/sales/' + res.sale_id + '/receipt';

                // tampil modal
                let modal = new bootstrap.Modal(
                    document.getElementById('successModal')
                );

                modal.show();

            });
    }

    function renderCart() {

        let html = '';
        let total = 0;

        for (let id in cart) {

            let item = cart[id];
            let sub = item.qty * item.harga;
            total += sub;

            html += `
                <div class="cart-item">

                <div class="d-flex justify-content-between">

                <div>
                <b>${item.nama}</b><br>
                Rp ${item.harga}
                </div>

                <div>

                <div class="d-flex align-items-center gap-1">

                <button class="qty-btn btn-danger"
                onclick="minus(${id})">

                -

                </button>

                <input type="number"
                step="0.01"
                min="0"
                value="${item.qty}"
                data-id="${id}"
                class="form-control text-center qty-input"
                style="width:80px"
                onchange="updateQty(${id}, this.value)">

                <button class="qty-btn btn-success"
                onclick="plus(${id})">

                +

                </button>

                </div>

                </div>

                </div>

                <div class="text-end mt-1">
                Rp ${Math.round(sub).toLocaleString()}
                </div>

                </div>
            `;
        }

        document.getElementById('cartArea').innerHTML = html;

        document.getElementById('subtotal').innerText =
            'Rp ' + Math.round(total).toLocaleString();

        let diskon = parseInt(document.getElementById('diskon').value || 0);

        let grand = total - diskon;

        document.getElementById('grandtotal').innerText =
            'Rp ' + grand.toLocaleString();

        let bayar = parseInt(document.getElementById('bayar').value || 0);

        let kembali = bayar - grand;

        document.getElementById('kembali').value =
            'Rp ' + kembali.toLocaleString();

    }

    function setBayar(nominal) {

        document.getElementById('bayar').value =
            nominal;

        renderCart();

    }

    function uangPas() {

        let totalText =
            document.getElementById('grandtotal')
            .innerText
            .replace('Rp ', '')
            .replaceAll('.', '')
            .replaceAll(',', '');

        let total = parseFloat(totalText);

        document.getElementById('bayar').value =
            total;

        renderCart();

    }

    document.getElementById('search').addEventListener('keyup', function() {

        let val = this.value.toLowerCase();

        document.querySelectorAll('.produk-item').forEach(el => {

            el.style.display =
                el.dataset.name.includes(val) ? 'block' : 'none';

        });

    });

    function newTransaction() {

        cart = {};

        renderCart();

        document.getElementById('bayar').value = '';
        document.getElementById('diskon').value = 0;

        // hide payment
        document
            .getElementById('paymentBox')
            .classList.add('d-none');

        // tampil tombol bayar
        document
            .getElementById('btnBayar')
            .classList.remove('d-none');

        // hide tombol simpan
        document
            .getElementById('btnSimpan')
            .classList.add('d-none');

        bootstrap.Modal.getInstance(
            document.getElementById('successModal')
        ).hide();

        // focus search
        document.getElementById('search').focus();

    }
</script>

@endsection