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

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

        #[Validate('required|exists:fibre_types,id')]
        public $fibre_type_id = '';

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

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

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

        #[Validate('required|date')]
        public $creation_date = '';

        // Removed status handling

        public $clients;
        public $fibreTypes;
        public $availableStock = 0;

        public function mount()
        {
            $this->clients = Client::all();
            $this->fibreTypes = FibreType::all();
            $this->creation_date = now()->toDateString();
        }

        public function updatedFibreTypeId()
        {
            if ($this->fibre_type_id) {
                $stock = \App\Models\Stock::where('fibre_type_id', $this->fibre_type_id)->first();
                $this->availableStock = $stock ? $stock->quantity : 0;
                $this->recalculateTotal();
            } else {
                $this->availableStock = 0;
            }
        }

        public function updatedQuantity()
        {
            $this->recalculateTotal();
        }

        public function updatedUnitPrice()
        {
            $this->recalculateTotal();
        }

        protected function recalculateTotal()
        {
            if ($this->quantity && $this->unit_price) {
                $this->total_price = (float)$this->unit_price * (float)$this->quantity;
            }
        }

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

            // Check if there's enough stock
            $stock = \App\Models\Stock::where('fibre_type_id', $validated['fibre_type_id'])->first();
            
            if (!$stock) {
                session()->flash('error', 'No stock available for this fibre type.');
                return;
            }

            if ($stock->quantity < $validated['quantity']) {
                session()->flash('error', 'Insufficient stock. Available: ' . number_format($stock->quantity, 2) . ' kg, Requested: ' . number_format($validated['quantity'], 2) . ' kg');
                return;
            }

            // Normalize and ensure total price matches unit_price * quantity
            $payload = [
                'client_id' => $validated['client_id'],
                'fibre_type_id' => $validated['fibre_type_id'],
                'quantity' => $validated['quantity'],
                'unit_price' => $validated['unit_price'],
                'total_price' => (float)$validated['unit_price'] * (float)$validated['quantity'],
                'creation_date' => $validated['creation_date'],
                // no status
            ];

            // Create the order
            $order = Order::create($payload);

            // Record the stock movement
            $quantityBefore = $stock->quantity;
            $stock->quantity -= $validated['quantity'];
            $stock->save();

            \App\Models\StockMovement::create([
                'fibre_type_id' => $validated['fibre_type_id'],
                'type' => 'out',
                'quantity' => $validated['quantity'],
                'quantity_before' => $quantityBefore,
                'quantity_after' => $stock->quantity,
                'reason' => 'Order #' . $order->id,
                'reference_type' => 'order',
                'reference_id' => $order->id,
                'notes' => 'Stock reduction for order',
            ]);

            session()->flash('message', 'Order created successfully. Stock reduced by ' . number_format($validated['quantity'], 2) . ' kg.');

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

<x-layouts.app>
    @volt('orders.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 commandes"
                :href="route('orders')"
            />

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

            <form wire:submit="save" class="space-y-4">
                <div>
                    <label for="client_id" class="block mb-2 text-sm font-medium text-gray-700">Client</label>
                    <div x-data="{ 
                        open: false, 
                        search: '',
                        clients: @js($this->clients->map(fn($c) => ['id' => $c->id, 'name' => $c->firstname . ' ' . $c->lastname])),
                        get selectedClient() {
                            return $wire.get('client_id') || '';
                        },
                        set selectedClient(value) {
                            $wire.set('client_id', value);
                        },
                        get filteredClients() {
                            if (!this.search) return this.clients;
                            const searchLower = this.search.toLowerCase();
                            return this.clients.filter(client => 
                                client.name.toLowerCase().includes(searchLower)
                            );
                        },
                        get selectedClientName() {
                            const client = this.clients.find(c => c.id == this.selectedClient);
                            return client ? client.name : 'Sélectionner un client';
                        }
                    }" 
                    x-on:click.outside="open = false"
                    class="relative">
                        <input type="hidden" wire:model="client_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="selectedClientName" 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 client..."
                                    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="selectedClient = ''; open = false"
                                        :class="selectedClient == '' ? '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 client
                                    </button>
                                </li>
                                <template x-for="client in filteredClients" :key="client.id">
                                    <li>
                                        <button type="button"
                                            x-on:click="selectedClient = client.id; open = false"
                                            :class="selectedClient == client.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="client.name"></span>
                                        </button>
                                    </li>
                                </template>
                                <li x-show="filteredClients.length === 0" class="px-4 py-2 text-sm text-gray-500">
                                    Aucun client trouvé
                                </li>
                            </ul>
                        </div>
                    </div>
                    @error('client_id') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                </div>

                <div>
                    <label for="fibre_type_id" class="block mb-2 text-sm font-medium text-gray-700">Fibre Type</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
                    
                    @if($this->fibre_type_id && $this->availableStock > 0)
                        <div class="mt-2 p-2 bg-green-100 border border-green-200 rounded-md">
                            <p class="text-sm text-green-800">
                                <strong>Stock disponible:</strong> {{ number_format($this->availableStock, 2) }} kg
                            </p>
                        </div>
                    @elseif($this->fibre_type_id && $this->availableStock == 0)
                        <div class="mt-2 p-2 bg-red-100 border border-red-200 rounded-md">
                            <p class="text-sm text-red-800">
                                <strong>Aucun stock disponible</strong> pour ce type de fil
                            </p>
                        </div>
                    @endif
                </div>

                <div>
                    <label for="unit_price" class="block mb-2 text-sm font-medium text-gray-700">Prix unitaire (DT/kg)</label>
                    <input type="number" id="unit_price" wire:model="unit_price" step="0.01" min="0.01" 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('unit_price') <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">Quantity (kg)</label>
                    <input type="number" id="quantity" wire:model="quantity" step="0.01" min="0.01" 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
                    @if($this->fibre_type_id && $this->availableStock > 0)
                        <p class="mt-1 text-xs text-gray-500">Maximum: {{ number_format($this->availableStock, 2) }} kg</p>
                    @endif
                </div>

                <div>
                    <label for="total_price" class="block mb-2 text-sm font-medium text-gray-700">Total Prix</label>
                    <input type="number" id="total_price" wire:model="total_price" step="0.01" min="0.01" readonly class="block w-full mt-1 border-gray-300 rounded-md shadow-sm bg-gray-100 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                    @error('total_price') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                </div>

                <div>
                    <label for="creation_date" class="block mb-2 text-sm font-medium text-gray-700">Date de création</label>
                    <input type="date" id="creation_date" wire:model="creation_date" 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('creation_date') <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>
