<x-app-layout>
    <x-slot name="header">{{ __('Add Purchase') }}</x-slot>

    {{-- Encode items for JS filtering --}}
    @php
        $itemsJson = $items->map(fn($i) => ['id'=>$i->id,'name'=>$i->name,'category'=>$i->category,'unit'=>$i->unit])->toJson();
    @endphp

    <div class="card shadow-sm">
        <div class="card-body">
            <form action="{{ route('purchases.store') }}" method="POST">
                @csrf
                <div class="row g-3 mb-2">
                    <div class="col-md-4">
                        <label class="form-label fw-semibold">{{ __('Purchase Invoice No') }}</label>
                        <input type="text" name="invoice_no" class="form-control" value="{{ old('invoice_no', $nextInvoice) }}">
                    </div>
                </div>

                <div class="row g-3">
                    {{-- Date --}}
                    <div class="col-md-4">
                        <label class="form-label" for="purchase_date">{{ __('Date') }} <span class="text-danger">*</span></label>
                        <input id="purchase_date" type="date" name="purchase_date" class="form-control"
                               value="{{ old('purchase_date', now()->format('Y-m-d')) }}" required>
                    </div>

                    {{-- Item Category --}}
                    <div class="col-md-4">
                        <label class="form-label" for="item_category">{{ __('Item Category') }}</label>
                        <select id="item_category" name="item_category" class="form-select">
                            <option value="">-- {{ __('Select Category') }} --</option>
                            @foreach($categories as $cat)
                                <option value="{{ $cat->name }}" {{ old('item_category') == $cat->name ? 'selected' : '' }}>
                                    {{ $cat->name }}
                                </option>
                            @endforeach
                        </select>
                    </div>

                    {{-- Item --}}
                    <div class="col-md-4">
                        <label class="form-label" for="item_id">{{ __('Item') }}</label>
                        <select id="item_id" name="item_id" class="form-select">
                            <option value="">-- {{ __('Select Item') }} --</option>
                            @foreach($items as $item)
                                <option value="{{ $item->id }}"
                                    data-category="{{ $item->category }}"
                                    {{ old('item_id') == $item->id ? 'selected' : '' }}>
                                    {{ $item->name }} @if($item->unit)({{ $item->unit }})@endif
                                </option>
                            @endforeach
                        </select>
                    </div>
                </div>

                <div class="row g-3 mt-1">
                    {{-- Vendor --}}
                    <div class="col-md-4">
                        <label class="form-label" for="vendor_id">{{ __('Vendor') }}</label>
                        <select id="vendor_id" name="vendor_id" class="form-select">
                            <option value="">-- {{ __('Select Vendor') }} --</option>
                            @foreach($vendors as $vendor)
                                <option value="{{ $vendor->id }}" {{ old('vendor_id') == $vendor->id ? 'selected' : '' }}>
                                    {{ $vendor->name }}
                                </option>
                            @endforeach
                        </select>
                        <div class="form-text">
                            <a href="{{ route('vendors.create') }}" target="_blank">
                                <i class="bi bi-plus-circle me-1"></i>{{ __('Add new vendor') }}
                            </a>
                        </div>
                    </div>

                    {{-- Quantity --}}
                    <div class="col-md-4">
                        <label class="form-label" for="quantity">{{ __('Quantity') }}</label>
                        <input id="quantity" type="number" step="0.01" min="0" name="quantity"
                               class="form-control" value="{{ old('quantity') }}">
                    </div>

                    {{-- Cost --}}
                    <div class="col-md-4">
                        <label class="form-label" for="cost">{{ __('Total Cost') }} <span class="text-danger">*</span></label>
                        <input id="cost" type="number" step="0.01" min="0" name="cost"
                               class="form-control" value="{{ old('cost') }}" required>
                    </div>
                </div>

                <div class="row g-3 mt-1">
                    {{-- Payment Type --}}
                    <div class="col-md-4">
                        <label class="form-label" for="payment_type">{{ __('Payment Type') }} <span class="text-danger">*</span></label>
                        <select id="payment_type" name="payment_type" class="form-select" required>
                            <option value="cash" {{ old('payment_type', 'cash') == 'cash' ? 'selected' : '' }}>
                                <i class="bi bi-cash"></i> {{ __('Cash (Paid Now)') }}
                            </option>
                            <option value="due" {{ old('payment_type') == 'due' ? 'selected' : '' }}>
                                {{ __('Due (Pay Later)') }}
                            </option>
                        </select>
                        <div id="due_note" class="form-text text-warning d-none">
                            <i class="bi bi-exclamation-triangle me-1"></i>{{ __('This will be recorded in Vendor Ledger as due.') }}
                        </div>
                    </div>

                    {{-- Notes --}}
                    <div class="col-md-8">
                        <label class="form-label" for="notes">{{ __('Notes') }}</label>
                        <input id="notes" type="text" name="notes" class="form-control" value="{{ old('notes') }}">
                    </div>
                </div>

                <div class="mt-4">
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-save me-1"></i>{{ __('Save Purchase') }}
                    </button>
                    <a href="{{ route('purchases.index') }}" class="btn btn-secondary">{{ __('Cancel') }}</a>
                </div>
            </form>
        </div>
    </div>

    <script>
    (function () {
        const categorySelect = document.getElementById('item_category');
        const itemSelect     = document.getElementById('item_id');
        const paymentSelect  = document.getElementById('payment_type');
        const dueNote        = document.getElementById('due_note');
        const allOptions     = Array.from(itemSelect.options).slice(1); // skip placeholder

        function filterItems() {
            const chosen = categorySelect.value;
            // Clear and re-add placeholder
            while (itemSelect.options.length > 1) itemSelect.remove(1);
            allOptions.forEach(opt => {
                if (!chosen || opt.dataset.category === chosen) {
                    itemSelect.add(opt.cloneNode(true));
                }
            });

            if (itemSelect.tomselect) {
                itemSelect.tomselect.clear(true);
                itemSelect.tomselect.sync();
            }
        }

        function toggleDueNote() {
            dueNote.classList.toggle('d-none', paymentSelect.value !== 'due');
        }

        categorySelect.addEventListener('change', filterItems);
        paymentSelect.addEventListener('change', toggleDueNote);

        // Init
        filterItems();
        toggleDueNote();
    })();
    </script>
</x-app-layout>
