@extends('layouts.app')

@section('content')
    @php
        $role = auth()->user()?->role?->nama_roles;
    @endphp
    <div class="space-y-6">
        <x-card>
            <div class="flex flex-wrap items-center justify-between gap-4">
                <div>
                    <h2 class="text-2xl font-semibold text-slate-900">Close Bill</h2>
                    <p class="text-sm text-slate-500">Order {{ $order->order_no }} - {{ $order->tanggal->format('d-m-Y H:i') }}</p>
                </div>
                <div class="text-right">
                    <x-badge :variant="$order->status === 'open' ? 'success' : ($order->status === 'closed' ? 'info' : 'danger')">
                        {{ ucfirst($order->status) }}
                    </x-badge>
                    @if($order->status === 'closed' && $role === 'cashier')
                        <div class="mt-2 flex justify-end">
                            <x-button type="button" id="print-close-bill" variant="secondary">Print</x-button>
                        </div>
                    @endif
                    @php
                        $orderTotal = $order->grand_total_after_discount ?? $order->grand_total;
                    @endphp
                    <p class="mt-2 text-lg font-semibold text-slate-900">{{ format_rupiah($orderTotal) }}</p>
                    @if(($order->discount_amount ?? 0) > 0)
                        <p class="mt-1 text-xs text-slate-500">
                            Total sebelum diskon: {{ format_rupiah($order->grand_total) }}
                        </p>
                        <p class="mt-1 text-xs text-amber-700">
                            Diskon {{ $order->discount_name ? '(' . $order->discount_name . ')' : '' }}:
                            -{{ format_rupiah($order->discount_amount) }}
                        </p>
                    @endif
                </div>
            </div>

            <div class="mt-4 flex flex-wrap gap-6 text-sm text-slate-600">
                <div>Waiter: <span class="font-semibold text-slate-800">{{ $order->waiter?->nama ?? '-' }}</span></div>
                <div>
                    @if($order->type === 'dine_in')
                        Meja: <span class="font-semibold text-slate-800">{{ $order->meja?->no_meja ?? '-' }}</span>
                    @else
                        Pelanggan: <span class="font-semibold text-slate-800">{{ $order->nama_pelanggan ?? '-' }}</span>
                    @endif
                </div>
                @if($order->status === 'closed')
                    @php
                        $paidAtDisplay = '-';
                        if ($order->updated_at) {
                            $paidAtDisplay = \Illuminate\Support\Carbon::parse($order->updated_at)->format('d-m-Y H:i');
                        }
                    @endphp
                    <div>
                        Waktu Bayar: <span class="font-semibold text-slate-800">{{ $paidAtDisplay }}</span>
                    </div>
                    <div>
                        Pembayaran: <span class="font-semibold text-slate-800">{{ strtoupper($order->tipe_pembayaran ?? '-') }}</span>
                        @if(($order->tipe_pembayaran ?? '') !== 'cash' && $order->no_transaksi_pembayaran)
                            <span class="text-xs text-slate-500">({{ $order->no_transaksi_pembayaran }})</span>
                        @endif
                    </div>
                    @if(($order->discount_amount ?? 0) > 0)
                        <div>
                            Discount: <span class="font-semibold text-slate-800">
                                {{ $order->discount_name ?? 'Diskon' }}
                            </span>
                            <span class="text-xs text-slate-500">(-{{ format_rupiah($order->discount_amount) }})</span>
                        </div>
                        <div>
                            Total Setelah Diskon:
                            <span class="font-semibold text-slate-800">{{ format_rupiah($order->grand_total_after_discount ?? $order->grand_total) }}</span>
                        </div>
                    @endif
                @endif
            </div>
        </x-card>

        <x-card>
            <h3 class="text-lg font-semibold text-slate-900">Items</h3>
            <div class="mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
                @php($activeDetails = $order->details->where('status', 'active'))
                @forelse($activeDetails as $detail)
                    <div class="w-full rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                        <div class="flex items-center justify-between">
                            <div class="text-sm font-semibold text-slate-900">{{ $detail->menu?->nama }}</div>
                            <x-badge variant="info">Qty {{ $detail->qty }}</x-badge>
                        </div>
                        <div class="mt-3 grid gap-2 text-sm text-slate-600">
                            <div class="flex items-center justify-between">
                                <span>Harga</span>
                                <span class="font-semibold text-slate-800">{{ format_rupiah($detail->harga) }}</span>
                            </div>
                            <div class="flex items-center justify-between">
                                <span>Line Total</span>
                                <span class="font-semibold text-slate-800">{{ format_rupiah($detail->line_total) }}</span>
                            </div>
                            <div class="text-xs text-slate-500">Note: {{ $detail->note ?? '-' }}</div>
                        </div>
                    </div>
                @empty
                    <div class="rounded-lg border border-slate-200 bg-slate-50 px-4 py-3 text-sm text-slate-500">
                        Tidak ada item aktif.
                    </div>
                @endforelse
            </div>
        </x-card>

        @if($order->status === 'open')
            <x-card>
                <h3 class="text-lg font-semibold text-slate-900">Pembayaran</h3>
                @if($needsOpenSaldo)
                    <div class="mt-4 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-700">
                        Mohon lakukan Open Saldo terlebih dahulu sebelum Close Bill.
                    </div>
                @else
                    <div id="close-error" class="mt-4 hidden rounded-lg border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700"></div>
                    <form method="post" action="{{ route('orders.close', $order) }}" class="mt-4 grid gap-4 md:grid-cols-2" id="close-order-form" data-print-url="{{ route('orders.print', $order) }}" data-grand-total="{{ $order->grand_total }}">
                        @csrf
                        <input type="hidden" name="discount_id" id="discount-id" value="">

                        @if(($discounts ?? collect())->count())
                            <div class="md:col-span-2">
                                <label class="mb-2 block text-sm font-semibold text-slate-700">Discount</label>
                                <div class="flex flex-wrap items-center gap-2 text-xs">
                                    <button type="button" data-discount data-id="" data-type="" data-value="0"
                                            class="rounded-full border px-3 py-1 font-semibold border-slate-900 bg-slate-900 text-white">
                                        Tanpa Discount
                                    </button>
                                    @foreach($discounts as $discount)
                                        <button type="button" data-discount data-id="{{ $discount->id }}" data-type="{{ $discount->tipe }}" data-value="{{ $discount->nilai }}"
                                                class="rounded-full border px-3 py-1 font-semibold border-slate-200 text-slate-600 hover:bg-slate-50">
                                            {{ $discount->nama }}
                                            @if($discount->tipe === 'percent')
                                                ({{ rtrim(rtrim(number_format((float) $discount->nilai, 2, '.', ''), '0'), '.') }}%)
                                            @else
                                                ({{ format_rupiah($discount->nilai) }})
                                            @endif
                                        </button>
                                    @endforeach
                                </div>
                            </div>
                        @endif

                        <x-select name="tipe_pembayaran" label="Tipe Pembayaran" required id="payment-type">
                            <option value="">Pilih</option>
                            @foreach(['cash' => 'Cash', 'transfer' => 'Transfer', 'qris' => 'QRIS'] as $value => $label)
                                <option value="{{ $value }}" {{ old('tipe_pembayaran') === $value ? 'selected' : '' }}>{{ $label }}</option>
                            @endforeach
                        </x-select>
                        <div>
                            <label for="payment-amount-display" class="mb-2 block text-sm font-semibold text-slate-700">Bayar</label>
                            <input type="text" id="payment-amount-display" inputmode="numeric" autocomplete="off"
                                   value="{{ old('bayar') ? format_rupiah(old('bayar')) : '' }}"
                                   class="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-700 shadow-sm focus:border-amber-400 focus:ring-amber-200">
                            <input type="hidden" name="bayar" id="payment-amount" value="{{ old('bayar') }}">
                        </div>
                        <div id="bank-account-field" class="hidden md:col-span-2">
                            <x-select name="bank_account_id" label="Akun Bank">
                                <option value="">Pilih Akun Bank</option>
                                @foreach($bankAccounts as $bank)
                                    <option value="{{ $bank->id }}" {{ old('bank_account_id') == $bank->id ? 'selected' : '' }}>
                                        {{ $bank->bank_name }} - {{ $bank->account_name }} ({{ $bank->account_number }})
                                    </option>
                                @endforeach
                            </x-select>
                        </div>
                        <x-input name="no_transaksi_pembayaran" label="No Transaksi Pembayaran" :value="old('no_transaksi_pembayaran')" />
                        <div class="md:col-span-2 rounded-lg border border-amber-100 bg-amber-50/50 p-4 text-sm text-slate-700">
                            <div class="flex items-center justify-between">
                                <span>Total</span>
                                <span class="font-semibold text-slate-900">{{ format_rupiah($order->grand_total) }}</span>
                            </div>
                            <div class="mt-2 flex items-center justify-between">
                                <span>Diskon</span>
                                <span id="discount-display" class="font-semibold text-amber-700">Rp 0</span>
                            </div>
                            <div class="mt-2 flex items-center justify-between">
                                <span>Total Setelah Diskon</span>
                                <span id="total-after-display" class="font-semibold text-slate-900">{{ format_rupiah($order->grand_total) }}</span>
                            </div>
                            <div class="mt-2 flex items-center justify-between">
                                <span>Kembalian</span>
                                <span id="change-display" class="font-semibold text-emerald-600">Rp 0</span>
                            </div>
                        </div>
                        <div class="md:col-span-2 flex justify-end">
                            <x-button type="submit">Close Bill</x-button>
                        </div>
                    </form>
                @endif
            </x-card>
        @endif

        <div class="flex flex-wrap items-center gap-3">
            <x-button href="{{ route('orders.all') }}" variant="secondary">Kembali</x-button>
        </div>
    </div>

    <script>
        window.addEventListener('load', () => {
            const printCloseBtn = document.getElementById('print-close-bill');
            const closeOrderForm = document.getElementById('close-order-form');
            const paymentType = document.getElementById('payment-type');
            const bankField = document.getElementById('bank-account-field');
            const bankSelect = bankField?.querySelector('select');
            const paymentAmount = document.getElementById('payment-amount');
            const paymentAmountDisplay = document.getElementById('payment-amount-display');
            const changeDisplay = document.getElementById('change-display');
            const discountButtons = document.querySelectorAll('[data-discount]');
            const discountInput = document.getElementById('discount-id');
            const discountDisplay = document.getElementById('discount-display');
            const totalAfterDisplay = document.getElementById('total-after-display');
            const grandTotal = parseFloat(closeOrderForm?.dataset?.grandTotal ?? '0') || 0;
            let selectedDiscount = { type: '', value: 0 };

            function toggleBankField() {
                if (!paymentType || !bankField) return;
                const isTransfer = paymentType.value === 'transfer';
                bankField.classList.toggle('hidden', !isTransfer);
                bankField.style.display = isTransfer ? 'block' : 'none';
                if (bankSelect) {
                    bankSelect.required = isTransfer;
                }
            }

            function getDiscountAmount() {
                if (!selectedDiscount.type || !selectedDiscount.value) {
                    return 0;
                }
                if (selectedDiscount.type === 'percent') {
                    return Math.min(grandTotal, grandTotal * (selectedDiscount.value / 100));
                }
                return Math.min(grandTotal, selectedDiscount.value);
            }

            function getTotalAfterDiscount() {
                return Math.max(0, grandTotal - getDiscountAmount());
            }

            function formatRupiahNumber(value) {
                return new Intl.NumberFormat('id-ID', {
                    style: 'currency',
                    currency: 'IDR',
                    minimumFractionDigits: 0,
                }).format(value);
            }

            function parseRupiah(value) {
                if (!value) return 0;
                const numeric = value.replace(/[^\d]/g, '');
                return parseInt(numeric, 10) || 0;
            }

            function syncPaymentInput() {
                if (!paymentType || !paymentAmount || !paymentAmountDisplay) return;
                const isCash = paymentType.value === 'cash';
                paymentAmountDisplay.readOnly = !isCash;
                if (!isCash) {
                    const totalAfter = Math.round(getTotalAfterDiscount());
                    paymentAmount.value = totalAfter;
                    paymentAmountDisplay.value = formatRupiahNumber(totalAfter);
                } else {
                    const parsed = parseRupiah(paymentAmountDisplay.value || '');
                    paymentAmount.value = parsed ? parsed : '';
                }
                updateChange();
            }

            function updateChange() {
                if (!paymentAmount || !changeDisplay) return;
                const bayar = parseFloat(paymentAmount.value || '0') || 0;
                const totalAfter = getTotalAfterDiscount();
                const change = Math.max(0, bayar - totalAfter);
                changeDisplay.textContent = formatRupiahNumber(change);

                if (discountDisplay) {
                    discountDisplay.textContent = formatRupiahNumber(getDiscountAmount());
                }
                if (totalAfterDisplay) {
                    totalAfterDisplay.textContent = formatRupiahNumber(totalAfter);
                }
            }

            discountButtons?.forEach((btn) => {
                btn.addEventListener('click', () => {
                    discountButtons.forEach((el) => {
                        el.classList.remove('border-slate-900', 'bg-slate-900', 'text-white');
                        el.classList.add('border-slate-200', 'text-slate-600');
                    });
                    btn.classList.remove('border-slate-200', 'text-slate-600');
                    btn.classList.add('border-slate-900', 'bg-slate-900', 'text-white');
                    const id = btn.getAttribute('data-id') || '';
                    const type = btn.getAttribute('data-type') || '';
                    const value = parseFloat(btn.getAttribute('data-value') || '0') || 0;
                    selectedDiscount = { type, value };
                    if (discountInput) {
                        discountInput.value = id;
                    }
                    syncPaymentInput();
                    updateChange();
                });
            });

            document.addEventListener('change', (event) => {
                if (event.target && event.target.id === 'payment-type') {
                    toggleBankField();
                    syncPaymentInput();
                }
            });

            if (window.$ && $.fn.select2 && paymentType) {
                $(paymentType).on('select2:select', () => {
                    toggleBankField();
                    syncPaymentInput();
                });
            }

            toggleBankField();
            syncPaymentInput();
            updateChange();
            paymentAmountDisplay?.addEventListener('input', () => {
                if (!paymentAmount || !paymentAmountDisplay) return;
                const raw = parseRupiah(paymentAmountDisplay.value);
                paymentAmount.value = raw;
                paymentAmountDisplay.value = raw ? formatRupiahNumber(raw) : '';
                updateChange();
            });

            closeOrderForm?.addEventListener('submit', async (event) => {
                event.preventDefault();
                const printUrl = closeOrderForm.dataset.printUrl;
                const submitButton = closeOrderForm.querySelector('button[type="submit"]');
                const errorBox = document.getElementById('close-error');
                submitButton?.setAttribute('disabled', 'disabled');

                try {
                    const response = await fetch(closeOrderForm.action, {
                        method: 'POST',
                        headers: { 'X-Requested-With': 'XMLHttpRequest' },
                        body: new FormData(closeOrderForm),
                    });

                    if (!response.ok) {
                        let message = 'Gagal menutup bill.';
                        try {
                            const data = await response.json();
                            if (data?.message) {
                                message = data.message;
                            }
                        } catch (error) {
                            // ignore parse errors
                        }
                        if (errorBox) {
                            errorBox.textContent = message;
                            errorBox.classList.remove('hidden');
                        } else {
                            alert(message);
                        }
                        submitButton?.removeAttribute('disabled');
                        return;
                    }

                    if (errorBox) {
                        errorBox.classList.add('hidden');
                        errorBox.textContent = '';
                    }

                    if (printUrl) {
                        const printWindow = window.open(`${printUrl}?t=${Date.now()}`, '_blank');
                        if (printWindow) {
                            printWindow.focus();
                        }
                    }

                    if (response.redirected) {
                        window.location.href = response.url;
                    } else {
                        window.location.reload();
                    }
                } catch (error) {
                    submitButton?.removeAttribute('disabled');
                }
            });

            printCloseBtn?.addEventListener('click', () => {
                const url = @json(route('orders.print', $order));
                const win = window.open(`${url}?t=${Date.now()}`, '_blank');
                if (win) {
                    win.focus();
                }
            });
        });
    </script>
@endsection
