@extends('layouts.epelcon')
@section('title', 'POS Terminal')

@section('content')
<div x-data="pos()" class="lg:grid lg:grid-cols-3 lg:gap-5">
    {{-- Catalogue --}}
    <div class="lg:col-span-2">
        <div class="mb-4 flex items-center justify-between">
            <h1 class="text-xl font-extrabold text-slate-900">POS Terminal</h1>
            <input x-model="search" placeholder="Search items…" class="w-44 rounded-xl border-0 bg-white px-4 py-2.5 text-sm shadow-sm ring-1 ring-slate-200 sm:w-64">
        </div>

        <div class="no-scrollbar mb-4 flex gap-2 overflow-x-auto">
            <button @click="cat = null" :class="cat === null ? 'bg-slate-900 text-white' : 'bg-white text-slate-600 ring-1 ring-slate-200'" class="shrink-0 rounded-full px-4 py-2 text-xs font-bold">All</button>
            @foreach ($categories as $category)
                <button @click="cat = {{ $category->id }}" :class="cat === {{ $category->id }} ? 'bg-slate-900 text-white' : 'bg-white text-slate-600 ring-1 ring-slate-200'" class="shrink-0 rounded-full px-4 py-2 text-xs font-bold">{{ $category->name }}</button>
            @endforeach
        </div>

        <div class="grid grid-cols-2 gap-3 pb-40 sm:grid-cols-3 lg:pb-0 xl:grid-cols-4">
            <template x-for="item in filtered()" :key="item.id">
                <button @click="addToCart(item)" class="overflow-hidden rounded-2xl bg-white text-left shadow-sm ring-1 ring-slate-200 transition active:scale-95 hover:ring-indigo-400">
                    <img x-show="item.image" :src="item.image ? '{{ url('/') }}/' + item.image : ''" class="h-20 w-full object-cover" loading="lazy">
                    <div class="p-3.5">
                        <span x-show="!item.image" class="text-2xl" x-text="item.type === 'drink' ? '🍹' : '🍽'"></span>
                        <p class="mt-1.5 text-sm font-bold leading-tight text-slate-900" x-text="item.name"></p>
                        <p class="mt-1 text-sm font-extrabold text-indigo-600" x-text="fmt(item.price)"></p>
                    </div>
                </button>
            </template>
        </div>
    </div>

    {{-- Cart (desktop side panel / mobile bottom sheet trigger) --}}
    <div class="fixed inset-x-0 bottom-16 z-30 lg:static lg:z-auto">
        {{-- Mobile summary bar --}}
        <button x-show="cart.length && !cartOpen" @click="cartOpen = true"
                class="mx-4 flex w-[calc(100%-2rem)] items-center justify-between rounded-2xl bg-slate-900 px-5 py-4 text-white shadow-2xl lg:hidden">
            <span class="text-sm font-bold" x-text="cart.reduce((s, l) => s + l.qty, 0) + ' items'"></span>
            <span class="text-sm font-extrabold" x-text="'View order · ' + fmt(subtotal())"></span>
        </button>

        <div :class="cartOpen ? 'fixed inset-0 z-50 flex items-end lg:static lg:block' : 'hidden lg:block'">
            <div x-show="cartOpen" class="absolute inset-0 bg-slate-900/50 lg:hidden" @click="cartOpen = false"></div>
            <div class="relative max-h-[85vh] w-full overflow-y-auto rounded-t-3xl bg-white p-5 shadow-2xl lg:max-h-none lg:rounded-2xl lg:shadow-sm lg:ring-1 lg:ring-slate-200">
                <div class="mb-3 flex items-center justify-between">
                    <h2 class="font-extrabold text-slate-900">Current order</h2>
                    <button x-show="cartOpen" @click="cartOpen = false" class="text-slate-400 lg:hidden">✕</button>
                </div>

                <form method="POST" action="{{ route('epelcon.orders.store') }}" class="space-y-3">
                    @csrf
                    <input type="hidden" name="items" :value="JSON.stringify(cart)">

                    <div class="space-y-2">
                        <template x-for="(line, i) in cart" :key="line.id">
                            <div class="flex items-center gap-2 rounded-xl bg-slate-50 p-2.5">
                                <div class="min-w-0 flex-1">
                                    <p class="truncate text-sm font-bold text-slate-800" x-text="line.name"></p>
                                    <p class="text-xs text-slate-500" x-text="fmt(line.price) + ' each'"></p>
                                </div>
                                <div class="flex items-center gap-1.5">
                                    <button type="button" @click="line.qty > 1 ? line.qty-- : cart.splice(i, 1)" class="h-7 w-7 rounded-lg bg-white font-bold text-slate-600 ring-1 ring-slate-200">−</button>
                                    <span class="w-6 text-center text-sm font-extrabold" x-text="line.qty"></span>
                                    <button type="button" @click="line.qty++" class="h-7 w-7 rounded-lg bg-white font-bold text-slate-600 ring-1 ring-slate-200">+</button>
                                </div>
                            </div>
                        </template>
                        <p x-show="!cart.length" class="rounded-xl bg-slate-50 py-6 text-center text-sm text-slate-400">Tap items to add them to the order.</p>
                    </div>

                    <div class="grid grid-cols-2 gap-3">
                        <label><span class="mb-1 block text-xs font-bold uppercase text-slate-500">Order type</span>
                            <select name="type" x-model="type" class="w-full rounded-xl border-slate-200 text-sm">
                                <option value="dine_in">Dine-in</option>
                                <option value="room_service">Room service</option>
                                <option value="takeaway">Takeaway</option>
                                <option value="delivery">Delivery</option>
                            </select></label>
                        <label x-show="type !== 'room_service'"><span class="mb-1 block text-xs font-bold uppercase text-slate-500">Table / location</span>
                            <input name="location" placeholder="Table 4" class="w-full rounded-xl border-slate-200 text-sm"></label>
                        <label x-show="type === 'room_service'" x-cloak class="col-span-2 lg:col-span-1"><span class="mb-1 block text-xs font-bold uppercase text-slate-500">In-house guest</span>
                            <select name="booking_id" class="w-full rounded-xl border-slate-200 text-sm">
                                <option value="">—</option>
                                @foreach ($activeBookings as $ab)
                                    <option value="{{ $ab->id }}">Room {{ $ab->room->number ?? '?' }} — {{ $ab->customer->name }}</option>
                                @endforeach
                            </select></label>
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <label><span class="mb-1 block text-xs font-bold uppercase text-slate-500">Customer</span>
                            <select name="customer_id" class="w-full rounded-xl border-slate-200 text-sm">
                                <option value="">Walk-in</option>
                                @foreach ($customers as $customer)<option value="{{ $customer->id }}">{{ $customer->name }}</option>@endforeach
                            </select></label>
                        <label><span class="mb-1 block text-xs font-bold uppercase text-slate-500">Or name</span>
                            <input name="customer_name" placeholder="Guest name" class="w-full rounded-xl border-slate-200 text-sm"></label>
                    </div>
                    <label class="block"><span class="mb-1 block text-xs font-bold uppercase text-slate-500">Kitchen note</span>
                        <input name="notes" placeholder="e.g. no onions" class="w-full rounded-xl border-slate-200 text-sm"></label>

                    <div>
                        <span class="mb-1 block text-xs font-bold uppercase text-slate-500">Payment method</span>
                        <div class="grid grid-cols-3 gap-2">
                            @foreach (['cash' => '💵 Cash', 'transfer' => '🏦 Transfer', 'pos' => '💳 POS'] as $pm => $pmLabel)
                                <label class="flex cursor-pointer items-center justify-center gap-1 rounded-xl border border-slate-200 px-2 py-2.5 text-xs font-bold text-slate-600 has-[:checked]:border-indigo-500 has-[:checked]:bg-indigo-50 has-[:checked]:text-indigo-700">
                                    <input type="radio" name="payment_method" value="{{ $pm }}" class="hidden" @checked($pm === 'cash')>{{ $pmLabel }}
                                </label>
                            @endforeach
                        </div>
                    </div>

                    <div class="space-y-1 border-t border-slate-100 pt-3 text-sm">
                        <div class="flex justify-between text-slate-500"><span>Subtotal</span><span class="font-bold" x-text="fmt(subtotal())"></span></div>
                        <div class="flex justify-between text-slate-500"><span>Tax ({{ $taxPercent = \App\Models\Setting::get('tax_percent', 0) }}%)</span><span class="font-bold" x-text="fmt(subtotal() * {{ (float) $taxPercent }} / 100)"></span></div>
                        <div class="flex justify-between text-base font-extrabold text-slate-900"><span>Total</span><span x-text="fmt(subtotal() * (1 + {{ (float) $taxPercent }} / 100))"></span></div>
                    </div>

                    <button :disabled="!cart.length" :class="cart.length ? 'bg-indigo-600 hover:bg-indigo-700' : 'bg-slate-300'"
                            class="w-full rounded-xl py-3.5 text-sm font-extrabold text-white shadow-lg transition">Send order →</button>
                </form>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
function pos() {
    return {
        items: {{ Illuminate\Support\Js::from($items->map->only(['id', 'name', 'price', 'type', 'menu_category_id', 'image'])) }},
        cart: [], cat: null, search: '', type: 'dine_in', cartOpen: false,
        filtered() {
            return this.items.filter(i =>
                (this.cat === null || i.menu_category_id === this.cat) &&
                (!this.search || i.name.toLowerCase().includes(this.search.toLowerCase()))
            );
        },
        addToCart(item) {
            const line = this.cart.find(l => l.id === item.id);
            line ? line.qty++ : this.cart.push({ id: item.id, name: item.name, price: parseFloat(item.price), qty: 1 });
        },
        subtotal() { return this.cart.reduce((s, l) => s + l.price * l.qty, 0); },
        fmt(v) { return '{{ $CUR }}' + Number(v).toLocaleString(undefined, { maximumFractionDigits: 0 }); },
    };
}
</script>
@endpush
