@extends('layouts.app')

@section('content')
    @php
        $oldPackageItems = old('package_items', []);
        if (! is_array($oldPackageItems)) {
            $oldPackageItems = [];
        }
    @endphp

    <x-card>
        <div class="mb-6">
            <h2 class="text-2xl font-semibold text-slate-900">Tambah Menu</h2>
            <p class="text-sm text-slate-500">Isi detail menu baru.</p>
        </div>
        <form method="post" action="{{ route('menus.store') }}" enctype="multipart/form-data" class="grid gap-4 md:grid-cols-2">
            @csrf
            <x-select name="id_stand" label="Stand" required>
                <option value="">Pilih Stand</option>
                @foreach($stands as $stand)
                    <option value="{{ $stand->id }}" {{ old('id_stand') == $stand->id ? 'selected' : '' }}>{{ $stand->nama }}</option>
                @endforeach
            </x-select>

            <x-input name="nama" label="Nama" required />

            <x-select name="type_menu" label="Type Menu" required>
                <option value="">Pilih Type</option>
                @foreach(['makanan' => 'Makanan', 'minuman' => 'Minuman', 'snack' => 'Snack'] as $value => $label)
                    <option value="{{ $value }}" {{ old('type_menu') === $value ? 'selected' : '' }}>{{ $label }}</option>
                @endforeach
            </x-select>

            <x-input name="harga_pokok" label="Harga Pokok" type="number" step="0.01" :value="old('harga_pokok', 0)" />
            <x-input name="harga_jual" label="Harga Jual" type="number" step="0.01" :value="old('harga_jual', 0)" />
            <x-input name="image" label="Image" type="file" />

            <div class="md:col-span-2">
                <label class="inline-flex items-center gap-2 text-sm font-semibold text-slate-700">
                    <input type="checkbox" name="is_active" value="1" class="rounded border-slate-300" {{ old('is_active', true) ? 'checked' : '' }}>
                    Aktif
                </label>
            </div>

            <div class="md:col-span-2">
                <label class="inline-flex items-center gap-2 text-sm font-semibold text-slate-700">
                    <input type="checkbox" name="is_package" id="is-package" value="1" class="rounded border-slate-300" {{ old('is_package') ? 'checked' : '' }}>
                    Menu Paket Bukber
                </label>
                <p class="mt-1 text-xs text-slate-500">Jika aktif, menu ini akan dipecah ke beberapa stand saat print stand.</p>
            </div>

            <div id="package-box" class="md:col-span-2 rounded-xl border border-slate-200 bg-slate-50 p-4 {{ old('is_package') ? '' : 'hidden' }}">
                <div class="mb-3 flex items-center justify-between">
                    <div>
                        <p class="text-sm font-semibold text-slate-800">Komponen Paket</p>
                        <p class="text-xs text-slate-500">Pilih menu yang termasuk dalam paket.</p>
                    </div>
                    <x-button type="button" variant="secondary" id="add-package-row">Tambah Komponen</x-button>
                </div>

                <div id="package-rows" class="space-y-3">
                    @forelse($oldPackageItems as $idx => $packageItem)
                        <div class="package-row grid gap-3 rounded-lg border border-slate-200 bg-white p-3 md:grid-cols-12">
                            <div class="md:col-span-8">
                                <label class="mb-1 block text-xs font-semibold text-slate-600">Menu Komponen</label>
                                <select name="package_items[{{ $idx }}][id_menu]" class="block w-full rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-700">
                                    <option value="">Pilih menu</option>
                                    @foreach($componentMenus as $componentMenu)
                                        <option value="{{ $componentMenu->id }}" {{ (string) ($packageItem['id_menu'] ?? '') === (string) $componentMenu->id ? 'selected' : '' }}>
                                            {{ $componentMenu->nama }} ({{ ucfirst($componentMenu->type_menu) }})
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="md:col-span-3">
                                <label class="mb-1 block text-xs font-semibold text-slate-600">Qty</label>
                                <input
                                    type="number"
                                    min="1"
                                    name="package_items[{{ $idx }}][qty]"
                                    value="{{ $packageItem['qty'] ?? 1 }}"
                                    class="block w-full rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-700"
                                >
                            </div>
                            <div class="flex items-end md:col-span-1">
                                <button type="button" class="remove-package-row inline-flex w-full items-center justify-center rounded-lg border border-rose-200 px-2 py-2 text-xs font-semibold text-rose-600 hover:bg-rose-50">
                                    Hapus
                                </button>
                            </div>
                        </div>
                    @empty
                        <div class="package-row grid gap-3 rounded-lg border border-slate-200 bg-white p-3 md:grid-cols-12">
                            <div class="md:col-span-8">
                                <label class="mb-1 block text-xs font-semibold text-slate-600">Menu Komponen</label>
                                <select name="package_items[0][id_menu]" class="block w-full rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-700">
                                    <option value="">Pilih menu</option>
                                    @foreach($componentMenus as $componentMenu)
                                        <option value="{{ $componentMenu->id }}">
                                            {{ $componentMenu->nama }} ({{ ucfirst($componentMenu->type_menu) }})
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="md:col-span-3">
                                <label class="mb-1 block text-xs font-semibold text-slate-600">Qty</label>
                                <input
                                    type="number"
                                    min="1"
                                    name="package_items[0][qty]"
                                    value="1"
                                    class="block w-full rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-700"
                                >
                            </div>
                            <div class="flex items-end md:col-span-1">
                                <button type="button" class="remove-package-row inline-flex w-full items-center justify-center rounded-lg border border-rose-200 px-2 py-2 text-xs font-semibold text-rose-600 hover:bg-rose-50">
                                    Hapus
                                </button>
                            </div>
                        </div>
                    @endforelse
                </div>

                @if($errors->has('package_items') || $errors->has('package_items.*.id_menu') || $errors->has('package_items.*.qty'))
                    <p class="mt-2 text-xs text-rose-600">
                        {{ $errors->first('package_items') ?: ($errors->first('package_items.*.id_menu') ?: $errors->first('package_items.*.qty')) }}
                    </p>
                @endif
            </div>

            <div class="flex gap-3 md:col-span-2">
                <x-button type="submit">Simpan</x-button>
                <x-button href="{{ route('menus.index') }}" variant="secondary">Kembali</x-button>
            </div>
        </form>
    </x-card>

    <script>
        const packageCheckbox = document.getElementById('is-package');
        const packageBox = document.getElementById('package-box');
        const packageRows = document.getElementById('package-rows');
        const addPackageRowButton = document.getElementById('add-package-row');
        const packageOptions = @json($componentMenus->map(fn ($menu) => [
            'id' => $menu->id,
            'label' => $menu->nama . ' (' . ucfirst($menu->type_menu) . ')',
        ])->values());
        let packageIndex = packageRows.querySelectorAll('.package-row').length;

        function togglePackageBox() {
            const show = packageCheckbox.checked;
            packageBox.classList.toggle('hidden', !show);
        }

        function buildPackageSelectHtml(index) {
            const options = ['<option value="">Pilih menu</option>'];
            packageOptions.forEach((option) => {
                options.push(`<option value="${option.id}">${option.label}</option>`);
            });

            return `
                <select name="package_items[${index}][id_menu]" class="block w-full rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-700">
                    ${options.join('')}
                </select>
            `;
        }

        function createPackageRow() {
            const row = document.createElement('div');
            row.className = 'package-row grid gap-3 rounded-lg border border-slate-200 bg-white p-3 md:grid-cols-12';
            row.innerHTML = `
                <div class="md:col-span-8">
                    <label class="mb-1 block text-xs font-semibold text-slate-600">Menu Komponen</label>
                    ${buildPackageSelectHtml(packageIndex)}
                </div>
                <div class="md:col-span-3">
                    <label class="mb-1 block text-xs font-semibold text-slate-600">Qty</label>
                    <input
                        type="number"
                        min="1"
                        name="package_items[${packageIndex}][qty]"
                        value="1"
                        class="block w-full rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-700"
                    >
                </div>
                <div class="flex items-end md:col-span-1">
                    <button type="button" class="remove-package-row inline-flex w-full items-center justify-center rounded-lg border border-rose-200 px-2 py-2 text-xs font-semibold text-rose-600 hover:bg-rose-50">
                        Hapus
                    </button>
                </div>
            `;
            packageRows.appendChild(row);
            packageIndex += 1;
        }

        packageCheckbox?.addEventListener('change', togglePackageBox);
        addPackageRowButton?.addEventListener('click', createPackageRow);

        packageRows?.addEventListener('click', (event) => {
            const removeButton = event.target.closest('.remove-package-row');
            if (!removeButton) {
                return;
            }

            const row = removeButton.closest('.package-row');
            const rowCount = packageRows.querySelectorAll('.package-row').length;
            if (rowCount <= 1) {
                row.querySelector('select').value = '';
                const qtyInput = row.querySelector('input[type="number"]');
                if (qtyInput) {
                    qtyInput.value = 1;
                }
                return;
            }

            row.remove();
        });

        togglePackageBox();
    </script>
@endsection
