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

    new class extends Component
    {
        public $movement;

        #[Validate('required|in:in,out')]
        public $type = 'in';

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

        #[Validate('required|string|max:255')]
        public $reason = '';

        public $notes = '';

        public function mount()
        {
            $movementId = request()->route('movement');
            $this->movement = StockMovement::with('fibreType')->findOrFail($movementId);
            
            $this->type = $this->movement->type;
            $this->quantity = $this->movement->quantity;
            $this->reason = $this->movement->reason;
            $this->notes = $this->movement->notes ?? '';
        }

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

            // Get the movement and related stock
            $movement = $this->movement;
            $stock = Stock::where('fibre_type_id', $movement->fibre_type_id)->first();

            if (!$stock) {
                session()->flash('error', 'Stock introuvable pour ce type de fil.');
                return;
            }

            // Update the movement
            $movement->update([
                'type' => $validated['type'],
                'quantity' => $validated['quantity'],
                'reason' => $validated['reason'],
                'notes' => $this->notes,
            ]);

            // Recalculate all movements for this fibre type in chronological order
            $allMovements = StockMovement::where('fibre_type_id', $movement->fibre_type_id)
                ->orderBy('created_at')
                ->orderBy('id')
                ->get();

            $currentQuantity = 0;

            foreach ($allMovements as $mov) {
                $mov->quantity_before = $currentQuantity;
                
                if ($mov->type === 'in') {
                    $currentQuantity += $mov->quantity;
                } else {
                    $currentQuantity -= $mov->quantity;
                }
                
                $mov->quantity_after = $currentQuantity;
                $mov->save();
            }

            // Update the stock
            $stock->quantity = $currentQuantity;
            $stock->save();

            session()->flash('message', 'Mouvement de stock mis à jour avec succès.');

            $this->redirect(route('stock.history'));
        }
    }
?>

<x-layouts.app>
    @volt('stock.movement.edit')
        <x-app.container class="max-w-full">

            <x-elements.back-button
                class="max-w-full mx-auto mb-3"
                text="Retour à l'historique"
                :href="route('stock.history')"
            />

            <div class="flex items-center justify-between mb-3">
                <x-app.heading
                        title="Modifier le mouvement de stock"
                        description="Modifier les détails d'un mouvement de stock"
                        :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>
                    <input type="text" 
                        value="{{ $this->movement->fibreType->name }} ({{ $this->movement->fibreType->color }})" 
                        disabled
                        class="block w-full mt-1 px-3 py-2 bg-gray-100 border border-gray-300 rounded-md shadow-sm text-gray-600">
                    <p class="mt-1 text-xs text-gray-500">Le type de fil ne peut pas être modifié</p>
                </div>

                <div>
                    <label for="type" class="block mb-2 text-sm font-medium text-gray-700">Type de mouvement</label>
                    <select id="type" wire:model="type" class="block w-full mt-1 px-3 py-2 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                        <option value="in">Entrée (IN)</option>
                        <option value="out">Sortie (OUT)</option>
                    </select>
                    @error('type') <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 px-3 py-2 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>
                    <label for="reason" class="block mb-2 text-sm font-medium text-gray-700">Raison</label>
                    <input type="text" id="reason" wire:model="reason" placeholder="Raison du mouvement" class="block w-full mt-1 px-3 py-2 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                    @error('reason') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                </div>

                <div>
                    <label for="notes" class="block mb-2 text-sm font-medium text-gray-700">Notes (optionnel)</label>
                    <textarea id="notes" wire:model="notes" rows="3" placeholder="Notes supplémentaires" class="block w-full mt-1 px-3 py-2 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"></textarea>
                </div>

                <div class="bg-blue-50 border border-blue-200 rounded-md p-4">
                    <p class="text-sm text-blue-800">
                        <strong>Note importante :</strong> La modification de ce mouvement recalculera automatiquement toutes les quantités des mouvements suivants pour ce type de fil.
                    </p>
                </div>

                <div>
                    <x-button type="submit">
                        Mettre à jour
                    </x-button>
                </div>
            </form>
        </x-app.container>
    @endvolt
</x-layouts.app>

