<?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.adjust');

    new class extends Component
    {
        #[Validate('required|numeric|min:0')]
        public $new_quantity = '';

        public $stock;
        public $currentQuantity = 0;

        public function mount()
        {
            $stockId = request()->route('id');
            $this->stock = Stock::with('fibreType')->findOrFail($stockId);
            $this->currentQuantity = $this->stock->quantity;
            $this->new_quantity = $this->stock->quantity;
        }

        public function resetToZero()
        {
            $this->new_quantity = 0;
        }

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

            $oldQuantity = $this->stock->quantity;
            $newQuantity = (float)$validated['new_quantity'];

            // Ajuster le stock directement sans créer de mouvement
            $this->stock->adjustStock($newQuantity);

            $difference = $newQuantity - $oldQuantity;
            $message = sprintf(
                'Stock ajusté avec succès. Ancienne quantité: %s kg, Nouvelle quantité: %s kg (%s%s kg)',
                number_format($oldQuantity, 2),
                number_format($newQuantity, 2),
                $difference >= 0 ? '+' : '',
                number_format($difference, 2)
            );

            session()->flash('message', $message);
            $this->redirect(route('stocks'));
        }
    }
?>

<x-layouts.app>
    @volt('stocks.adjust')
        <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="Ajuster le stock"
                        description="Corriger la quantité de stock sans créer de mouvement (pour corrections de comptage physique)"
                        :border="false"
                    />
            </div>

            <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-6">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <svg class="h-5 w-5 text-yellow-400" viewBox="0 0 20 20" fill="currentColor">
                            <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
                        </svg>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm text-yellow-800">
                            <strong>Attention:</strong> Cette action ajuste directement le stock sans créer de mouvement dans l'historique. 
                            Utilisez cette fonctionnalité uniquement pour corriger des erreurs de comptage physique.
                        </p>
                    </div>
                </div>
            </div>

            <form wire:submit="save" class="space-y-4">
                <div class="bg-gray-50 border border-gray-200 rounded-lg p-4">
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-600 mb-1">Stock actuel</label>
                            <p class="text-lg font-semibold text-gray-900">{{ number_format($currentQuantity, 2) }} kg</p>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-600 mb-1">Type de fil</label>
                            <p class="text-lg font-semibold text-gray-900">{{ $stock->fibreType->name }}</p>
                            <p class="text-sm text-gray-600">{{ $stock->fibreType->color }}</p>
                        </div>
                    </div>
                </div>

                <div>
                    <label for="new_quantity" class="block mb-2 text-sm font-medium text-gray-700">Nouvelle quantité (kg)</label>
                    <input type="number" id="new_quantity" wire:model="new_quantity" step="0.01" min="0" placeholder="Entrez la nouvelle 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('new_quantity') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                    <p class="mt-1 text-xs text-gray-500">La quantité sera remplacée directement par cette valeur.</p>
                </div>

                @if($currentQuantity > 0)
                    <div>
                        <button type="button" wire:click="resetToZero" class="text-sm text-red-600 hover:text-red-800 underline">
                            Remettre à zéro
                        </button>
                    </div>
                @endif

                @if($new_quantity != $currentQuantity)
                    <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                        <div class="flex items-center">
                            <svg class="h-5 w-5 text-blue-400 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                            <div>
                                <p class="text-sm font-medium text-blue-800">Aperçu de l'ajustement:</p>
                                <p class="text-sm text-blue-700">
                                    @php
                                        $difference = (float)$new_quantity - $currentQuantity;
                                    @endphp
                                    Ancienne quantité: <strong>{{ number_format($currentQuantity, 2) }} kg</strong><br>
                                    Nouvelle quantité: <strong>{{ number_format($new_quantity, 2) }} kg</strong><br>
                                    Différence: <strong class="{{ $difference >= 0 ? 'text-green-600' : 'text-red-600' }}">{{ $difference >= 0 ? '+' : '' }}{{ number_format($difference, 2) }} kg</strong>
                                </p>
                            </div>
                        </div>
                    </div>
                @endif

                <div class="flex space-x-3">
                    <x-button type="submit" variant="primary">
                        Ajuster le stock
                    </x-button>
                    <x-button tag="a" href="{{ route('stocks') }}" variant="outline">
                        Annuler
                    </x-button>
                </div>
            </form>
        </x-app.container>
    @endvolt
</x-layouts.app>

