<?php
    use function Laravel\Folio\{middleware, name};
    use Livewire\Attributes\Validate;
    use Livewire\Volt\Component;
    use App\Models\Stock;
    use App\Models\FibreType;
    middleware('auth');
    name('stocks.create');

    new class extends Component
    {
        #[Validate('required|exists:fibre_types,id')]
        public $fibre_type_id = '';

        #[Validate('required|numeric|min:0')]
        public $quantity = '';

        public $fibreTypes;

        public function mount()
        {
            $this->fibreTypes = FibreType::all();
        }

        public function save()
        {
            $validated = $this->validate();

            // Get or create stock entry
            $stock = \App\Models\Stock::where('fibre_type_id', $validated['fibre_type_id'])->first();
            
            if (!$stock) {
                $stock = \App\Models\Stock::create([
                    'fibre_type_id' => $validated['fibre_type_id'],
                    'quantity' => 0
                ]);
            }

            $quantityBefore = $stock->quantity;
            $stock->quantity += $validated['quantity'];
            $stock->save();

            // Record the movement
            \App\Models\StockMovement::create([
                'fibre_type_id' => $validated['fibre_type_id'],
                'type' => 'in',
                'quantity' => $validated['quantity'],
                'quantity_before' => $quantityBefore,
                'quantity_after' => $stock->quantity,
                'reason' => 'Stock addition',
                'reference_type' => 'stock_adjustment',
                'reference_id' => null,
                'notes' => 'Manual stock addition',
            ]);

            session()->flash('message', 'Stock entry created successfully.');

            $this->redirect(route('stocks'));
        }
    }
?>

<x-layouts.app>
    @volt('stocks.create')
        <x-app.container class="max-w-full">

            <x-elements.back-button
                class="max-w-full mx-auto mb-3"
                text="Retour à la liste des stocks"
                :href="route('stocks')"
            />

            <div class="flex items-center justify-between mb-3">
                <x-app.heading
                        title="Nouvelle entrée de stock"
                        description=""
                        :border="false"
                    />
            </div>

            <form wire:submit="save" class="space-y-4">
                <div>
                    <label for="fibre_type_id" class="block mb-2 text-sm font-medium text-gray-700">Type de fil</label>
                    <div x-data="{ 
                        open: false, 
                        search: '',
                        fibreTypes: @js($this->fibreTypes->map(fn($ft) => ['id' => $ft->id, 'name' => $ft->name . ' (' . $ft->color . ')'])),
                        get selectedFibreType() {
                            return $wire.get('fibre_type_id') || '';
                        },
                        set selectedFibreType(value) {
                            $wire.set('fibre_type_id', value);
                        },
                        get filteredFibreTypes() {
                            if (!this.search) return this.fibreTypes;
                            const searchLower = this.search.toLowerCase();
                            return this.fibreTypes.filter(fibreType => 
                                fibreType.name.toLowerCase().includes(searchLower)
                            );
                        },
                        get selectedFibreTypeName() {
                            const fibreType = this.fibreTypes.find(ft => ft.id == this.selectedFibreType);
                            return fibreType ? fibreType.name : 'Sélectionner un type de fil';
                        }
                    }" 
                    x-on:click.outside="open = false"
                    class="relative">
                        <input type="hidden" wire:model="fibre_type_id" />
                        <button type="button" 
                            x-on:click="open = !open"
                            class="block w-full mt-1 px-3 py-2 text-left bg-white border border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                            <span x-text="selectedFibreTypeName" class="block truncate"></span>
                        </button>
                        
                        <div x-show="open" 
                            x-transition
                            x-cloak
                            class="absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-auto">
                            <div class="p-2 sticky top-0 bg-white border-b border-gray-200">
                                <input type="text" 
                                    x-model="search"
                                    x-on:click.stop
                                    placeholder="Rechercher un type de fil..."
                                    class="block w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                            </div>
                            <ul class="py-1">
                                <li>
                                    <button type="button"
                                        x-on:click="selectedFibreType = ''; open = false"
                                        :class="selectedFibreType == '' ? 'bg-indigo-50 text-indigo-700' : 'text-gray-900 hover:bg-gray-50'"
                                        class="block w-full px-4 py-2 text-left text-sm">
                                        Sélectionner un type de fil
                                    </button>
                                </li>
                                <template x-for="fibreType in filteredFibreTypes" :key="fibreType.id">
                                    <li>
                                        <button type="button"
                                            x-on:click="selectedFibreType = fibreType.id; open = false"
                                            :class="selectedFibreType == fibreType.id ? 'bg-indigo-50 text-indigo-700' : 'text-gray-900 hover:bg-gray-50'"
                                            class="block w-full px-4 py-2 text-left text-sm">
                                            <span x-text="fibreType.name"></span>
                                        </button>
                                    </li>
                                </template>
                                <li x-show="filteredFibreTypes.length === 0" class="px-4 py-2 text-sm text-gray-500">
                                    Aucun type de fil trouvé
                                </li>
                            </ul>
                        </div>
                    </div>
                    @error('fibre_type_id') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                </div>

                <div>
                    <label for="quantity" class="block mb-2 text-sm font-medium text-gray-700">Quantité (kg)</label>
                    <input type="number" id="quantity" wire:model="quantity" step="0.01" min="0" placeholder="Entrez la quantité en kilogrammes" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                    @error('quantity') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                </div>

                <div>
                    <x-button type="submit">
                        Créer
                    </x-button>
                </div>
            </form>
        </x-app.container>
    @endvolt
</x-layouts.app>
