<!doctype html>
<html lang="id">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Mobile Intake POS</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-slate-100 text-slate-900">
<main class="mx-auto min-h-screen max-w-md bg-slate-100 px-4 pb-36 pt-5">
    <header class="rounded-2xl bg-white p-5 shadow-sm">
        <div class="flex items-start justify-between gap-3">
            <div>
                <div class="text-sm text-slate-500">Mobile Intake POS</div>
                <h1 class="mt-1 text-2xl font-semibold">Terima Barang</h1>
                <div class="mt-1 text-sm text-slate-500">{{ auth()->user()->branch?->name ?? 'Cabang' }}</div>
            </div>
            <a href="{{ route('dashboard') }}" class="rounded-md border px-3 py-2 text-sm">Admin</a>
        </div>
    </header>

    @if ($errors->any())
        <div class="mt-4 rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800">{{ $errors->first() }}</div>
    @endif
    @if (session('status'))
        <div class="mt-4 rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-800">{{ session('status') }}</div>
    @endif

    <form method="post" action="{{ route('mobile-intake.store') }}" id="intake-form" class="mt-4 space-y-4">
        @csrf

        <section class="rounded-2xl bg-white p-5 shadow-sm">
            <h2 class="font-semibold">Pelanggan</h2>
            <div class="mt-4 grid grid-cols-3 gap-2 text-sm">
                @foreach (['existing' => 'Pilih', 'new' => 'Baru', 'walkin' => 'Walk-in'] as $mode => $label)
                    <label class="cursor-pointer rounded-xl border px-3 py-2 text-center has-[:checked]:border-slate-900 has-[:checked]:bg-slate-900 has-[:checked]:text-white">
                        <input type="radio" name="customer_mode" value="{{ $mode }}" @checked(old('customer_mode', 'existing') === $mode) class="sr-only customer-mode">
                        {{ $label }}
                    </label>
                @endforeach
            </div>
            <div class="mt-4 customer-panel" data-mode-panel="existing">
                <input type="hidden" name="customer_id" id="customer-id" value="{{ old('customer_id') }}">
                <input id="customer-search" placeholder="Ketik nama atau nomor HP" autocomplete="off" class="w-full rounded-xl border px-3 py-3 text-sm">
                <div id="selected-customer" class="mt-3 hidden rounded-xl border border-emerald-200 bg-emerald-50 px-3 py-3 text-sm text-emerald-900">
                    <div class="flex items-center justify-between gap-3">
                        <span id="selected-customer-label" class="truncate"></span>
                        <button type="button" id="clear-customer" class="text-xs font-medium underline">Ganti</button>
                    </div>
                </div>
                <div id="customer-results" class="mt-2 hidden overflow-hidden rounded-xl border bg-white text-sm shadow-sm"></div>
            </div>
            <div class="mt-4 hidden customer-panel" data-mode-panel="new">
                <input name="new_customer[name]" value="{{ old('new_customer.name') }}" placeholder="Nama pelanggan" class="w-full rounded-xl border px-3 py-3 text-sm">
                <input name="new_customer[phone]" value="{{ old('new_customer.phone') }}" placeholder="Nomor HP" class="mt-3 w-full rounded-xl border px-3 py-3 text-sm">
                <textarea name="new_customer[address]" placeholder="Alamat" class="mt-3 w-full rounded-xl border px-3 py-3 text-sm">{{ old('new_customer.address') }}</textarea>
            </div>
        </section>

        <section class="rounded-2xl bg-white p-5 shadow-sm">
            <div>
                <h2 class="font-semibold">Layanan / Produk</h2>
                <p class="mt-1 text-sm text-slate-500">Ketik nama layanan, produk, atau SKU lalu pilih hasilnya.</p>
            </div>
            <div class="relative mt-4">
                <label for="product-search" class="mb-1 block text-sm font-medium">Cari produk / layanan</label>
                <input id="product-search" placeholder="Contoh: cuci, setrika, parfum, SKU" autocomplete="off" class="w-full rounded-xl border px-3 py-3 text-sm">
                <div id="product-results" class="mt-2 hidden overflow-hidden rounded-xl border bg-white text-sm shadow-sm"></div>
            </div>
            <div class="mt-4">
                <div class="mb-2 flex items-center justify-between">
                    <h3 class="text-sm font-semibold">Keranjang</h3>
                    <span id="cart-count" class="text-xs text-slate-500">0 item</span>
                </div>
                <div id="cart-empty" class="rounded-xl border border-dashed p-5 text-center text-sm text-slate-500">Belum ada item. Cari layanan/produk untuk menambahkan.</div>
                <div class="space-y-3" id="cart-items"></div>
            </div>
        </section>

        <section class="rounded-2xl bg-white p-5 shadow-sm">
            <h2 class="font-semibold">Pembayaran & Catatan</h2>
            <label class="mt-4 block text-sm font-medium">Estimasi selesai
                <input name="estimated_done_at" type="datetime-local" value="{{ old('estimated_done_at') }}" class="mt-1 w-full rounded-xl border px-3 py-3 text-sm">
            </label>
            <p class="mt-1 text-xs text-slate-500">Tanggal dan jam perkiraan order selesai atau siap diambil/dikirim.</p>
            <div class="mt-3 grid grid-cols-2 gap-3">
                <label class="block text-sm font-medium">DP / bayar sekarang
                    <input name="paid_amount" type="number" min="0" step="100" inputmode="numeric" value="{{ old('paid_amount', 0) }}" placeholder="0" class="mt-1 w-full rounded-xl border px-3 py-3 text-sm">
                </label>
                <label class="block text-sm font-medium">Metode bayar
                    <select name="payment_method" class="mt-1 w-full rounded-xl border px-3 py-3 text-sm">
                        @foreach (['cash' => 'Cash', 'transfer' => 'Transfer', 'qris' => 'QRIS'] as $value => $label)
                            <option value="{{ $value }}" @selected(old('payment_method', 'cash') === $value)>{{ $label }}</option>
                        @endforeach
                    </select>
                </label>
            </div>
            <label class="mt-3 block text-sm font-medium">Ongkir / biaya delivery
                <input id="delivery-fee" name="delivery_fee" type="number" min="0" step="100" inputmode="numeric" value="{{ old('delivery_fee', 0) }}" placeholder="0" class="mt-1 w-full rounded-xl border px-3 py-3 text-sm">
            </label>
            <p class="mt-1 text-xs text-slate-500">Isi jika order perlu antar/jemput berbayar. Nilai ini masuk ke grand total nota.</p>
            <label class="mt-3 block text-sm font-medium">Catatan nota
                <textarea name="note" placeholder="Contoh: minta dipisah, antar sore, jangan pakai pewangi" class="mt-1 w-full rounded-xl border px-3 py-3 text-sm">{{ old('note') }}</textarea>
            </label>
        </section>

        <div class="fixed inset-x-0 bottom-0 z-20 mx-auto max-w-md border-t bg-white/95 px-4 py-3 shadow-[0_-10px_30px_rgba(15,23,42,.12)] backdrop-blur">
            <div class="mb-3 flex items-center justify-between text-sm">
                <span class="text-slate-500">Estimasi total</span>
                <strong id="estimated-total" class="text-lg">Rp 0</strong>
            </div>
            <button class="w-full rounded-xl bg-slate-900 px-4 py-3 font-semibold text-white">Buat Nota & Lanjut Evidence</button>
        </div>
    </form>
</main>

<script>
const formatter = new Intl.NumberFormat('id-ID');
const modeInputs = document.querySelectorAll('.customer-mode');
const panels = document.querySelectorAll('.customer-panel');
const productSearch = document.getElementById('product-search');
const productResults = document.getElementById('product-results');
const cartItems = document.getElementById('cart-items');
const cartEmpty = document.getElementById('cart-empty');
const cartCount = document.getElementById('cart-count');
const customerSearch = document.getElementById('customer-search');
const customerId = document.getElementById('customer-id');
const customerResults = document.getElementById('customer-results');
const selectedCustomer = document.getElementById('selected-customer');
const selectedCustomerLabel = document.getElementById('selected-customer-label');
const clearCustomer = document.getElementById('clear-customer');
const totalNode = document.getElementById('estimated-total');
const deliveryFeeInput = document.getElementById('delivery-fee');
let customerSearchTimer = null;
let productSearchTimer = null;
let cart = [];

function syncCustomerPanels() {
    const mode = document.querySelector('.customer-mode:checked')?.value || 'existing';
    panels.forEach(panel => panel.classList.toggle('hidden', panel.dataset.modePanel !== mode));
}

function syncTotal() {
    let total = cart.reduce((sum, item) => sum + Math.max(0, (item.quantity * item.price) - item.discount), 0);
    total += Number(deliveryFeeInput?.value || 0);
    totalNode.textContent = 'Rp ' + formatter.format(total);
}

modeInputs.forEach(input => input.addEventListener('change', syncCustomerPanels));
deliveryFeeInput?.addEventListener('input', syncTotal);
productSearch.addEventListener('input', () => {
    clearTimeout(productSearchTimer);
    const query = productSearch.value.trim();

    if (query.length < 2) {
        productResults.classList.add('hidden');
        productResults.innerHTML = '';
        return;
    }

    productSearchTimer = setTimeout(async () => {
        productResults.classList.remove('hidden');
        productResults.innerHTML = '<div class="px-3 py-3 text-slate-500">Mencari...</div>';
        const response = await fetch(`{{ route('pos.products.search') }}?q=${encodeURIComponent(query)}`, {
            headers: { 'Accept': 'application/json' },
        });
        const products = await response.json();
        productResults.innerHTML = products.length
            ? products.map(product => `<button type="button" class="product-result block w-full px-3 py-3 text-left hover:bg-slate-50" data-product="${encodeURIComponent(JSON.stringify(product))}"><span class="block font-medium">${escapeHtml(product.name)}</span><span class="text-xs text-slate-500">${escapeHtml(product.sku || '')} - ${escapeHtml(product.type)} - Rp ${formatter.format(product.price)} / ${escapeHtml(product.unit)}</span></button>`).join('')
            : '<div class="px-3 py-3 text-slate-500">Produk tidak ditemukan.</div>';
    }, 250);
});
productResults?.addEventListener('click', (event) => {
    const button = event.target.closest('.product-result');
    if (!button) return;
    addToCart(JSON.parse(decodeURIComponent(button.dataset.product)));
    productSearch.value = '';
    productResults.classList.add('hidden');
    productResults.innerHTML = '';
    productSearch.focus();
});
customerSearch?.addEventListener('input', () => {
    clearTimeout(customerSearchTimer);
    const query = customerSearch.value.trim();

    if (query.length < 2) {
        customerResults.classList.add('hidden');
        customerResults.innerHTML = '';
        return;
    }

    customerSearchTimer = setTimeout(async () => {
        customerResults.classList.remove('hidden');
        customerResults.innerHTML = '<div class="px-3 py-3 text-slate-500">Mencari...</div>';
        const response = await fetch(`{{ route('pos.customers.search') }}?q=${encodeURIComponent(query)}`, {
            headers: { 'Accept': 'application/json' },
        });
        const customers = await response.json();
        customerResults.innerHTML = customers.length
            ? customers.map(customer => `<button type="button" class="customer-result block w-full px-3 py-3 text-left hover:bg-slate-50" data-id="${customer.id}" data-label="${escapeHtml(customer.label)}"><span class="block font-medium">${escapeHtml(customer.name)}</span><span class="text-xs text-slate-500">${escapeHtml(customer.phone || '')}${customer.address ? ' - ' + escapeHtml(customer.address) : ''}</span></button>`).join('')
            : '<div class="px-3 py-3 text-slate-500">Pelanggan tidak ditemukan.</div>';
    }, 300);
});
customerResults?.addEventListener('click', (event) => {
    const button = event.target.closest('.customer-result');
    if (!button) return;
    customerId.value = button.dataset.id;
    selectedCustomerLabel.textContent = button.dataset.label;
    selectedCustomer.classList.remove('hidden');
    customerSearch.value = '';
    customerResults.classList.add('hidden');
    customerResults.innerHTML = '';
});
clearCustomer?.addEventListener('click', () => {
    customerId.value = '';
    selectedCustomerLabel.textContent = '';
    selectedCustomer.classList.add('hidden');
    customerSearch.focus();
});
function escapeHtml(value) {
    return String(value ?? '').replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' }[char]));
}
function addToCart(product) {
    const existing = cart.find(item => item.product_id === product.id);
    if (existing) {
        existing.quantity = Math.round((existing.quantity + 1) * 1000) / 1000;
    } else {
        cart.push({
            product_id: product.id,
            name: product.name,
            sku: product.sku,
            type: product.type,
            unit: product.unit,
            price: Number(product.price),
            quantity: 1,
            discount: 0,
        });
    }
    renderCart();
}
function renderCart() {
    cartEmpty.classList.toggle('hidden', cart.length > 0);
    cartCount.textContent = `${cart.length} item`;
    cartItems.innerHTML = cart.map((item, index) => `
        <div class="rounded-xl border p-3" data-cart-index="${index}">
            <input type="hidden" name="items[${index}][product_id]" value="${item.product_id}">
            <input type="hidden" name="items[${index}][staff_id]" value="{{ auth()->id() }}">
            <div class="flex items-start justify-between gap-3">
                <div class="min-w-0">
                    <div class="truncate font-medium">${escapeHtml(item.name)}</div>
                    <div class="mt-1 text-xs text-slate-500">${escapeHtml(item.sku)} - Rp ${formatter.format(item.price)} / ${escapeHtml(item.unit)}</div>
                </div>
                <button type="button" class="remove-cart-item text-sm text-red-600">Hapus</button>
            </div>
            <div class="mt-3 grid grid-cols-[1fr_1fr_auto] gap-2">
                <label class="text-xs font-medium text-slate-600">Jumlah
                    <input name="items[${index}][quantity]" type="number" min="0.001" step="0.001" inputmode="decimal" value="${item.quantity}" class="cart-qty mt-1 w-full rounded-lg border px-3 py-2 text-sm">
                </label>
                <label class="text-xs font-medium text-slate-600">Diskon item
                    <input name="items[${index}][discount]" type="number" min="0" step="100" inputmode="numeric" value="${item.discount}" placeholder="0" class="cart-discount mt-1 w-full rounded-lg border px-3 py-2 text-sm">
                </label>
                <button type="button" class="increment-cart self-end rounded-lg bg-slate-900 px-3 py-2 text-sm font-medium text-white">+1</button>
            </div>
        </div>
    `).join('');
    syncTotal();
}
cartItems.addEventListener('input', (event) => {
    const row = event.target.closest('[data-cart-index]');
    if (!row) return;
    const item = cart[Number(row.dataset.cartIndex)];
    if (event.target.classList.contains('cart-qty')) item.quantity = Number(event.target.value || 0);
    if (event.target.classList.contains('cart-discount')) item.discount = Number(event.target.value || 0);
    syncTotal();
});
cartItems.addEventListener('click', (event) => {
    const row = event.target.closest('[data-cart-index]');
    if (!row) return;
    const index = Number(row.dataset.cartIndex);
    if (event.target.classList.contains('remove-cart-item')) {
        cart.splice(index, 1);
        renderCart();
    }
    if (event.target.classList.contains('increment-cart')) {
        cart[index].quantity = Math.round((cart[index].quantity + 1) * 1000) / 1000;
        renderCart();
    }
});
syncCustomerPanels();
syncTotal();
</script>
</body>
</html>
