<?php

namespace App\Livewire\PurchaseOrders;

use App\Models\PurchaseOrder;
use App\Models\StockEntry;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\Layout;
use Livewire\Component;

#[Layout('layouts.dashboard')]
class Receive extends Component
{
    public PurchaseOrder $purchaseOrder;

    public string $batchNumber = '';

    // Form properties
    public array $receivedQuantities = [];

    public array $unitPrices = [];

    public array $expiryDates = [];

    public ?string $receiptDate = null;

    public ?string $notes = '';

    // UI state
    public bool $loading = false;

    public bool $success = false;

    public function mount(PurchaseOrder $purchaseOrder): void
    {
        // Refresh the model to get the latest status from database
        $purchaseOrder->refresh();

        // Double-check by querying the database directly to avoid any caching issues
        $currentStatus = PurchaseOrder::where('id', $purchaseOrder->id)->value('status');

        // Check if purchase order can be received
        if ($currentStatus !== PurchaseOrder::STATUS_ACTIVE) {
            $statusLabel = match ($currentStatus) {
                PurchaseOrder::STATUS_DRAFT => 'Brouillon',
                PurchaseOrder::STATUS_ACTIVE => 'En attente',
                PurchaseOrder::STATUS_RECEIVED => 'Reçu',
                PurchaseOrder::STATUS_CANCELLED => 'Annulé',
                default => 'Inconnu',
            };

            session()->flash('error', "Seuls les bons de commande actifs peuvent être reçus. Statut actuel: {$statusLabel} ({$currentStatus})");
            $this->redirect(route('purchase-orders.show', $purchaseOrder));

            return;
        }

        $this->purchaseOrder = $purchaseOrder->load(['supplier', 'items.product']);
        $this->batchNumber = StockEntry::generateUniqueBatchNumber();
        $this->receiptDate = now()->format('Y-m-d');

        // Initialize form arrays with default values
        foreach ($this->purchaseOrder->items as $item) {
            $this->receivedQuantities[$item->id] = $item->quantity;
            $this->unitPrices[$item->id] = $item->unit_price;
            $this->expiryDates[$item->id] = null;
        }
    }

    public function rules()
    {
        return [
            'receivedQuantities' => ['required', 'array'],
            'receivedQuantities.*' => ['required', 'integer', 'min:0'],
            'unitPrices' => ['required', 'array'],
            'unitPrices.*' => ['required', 'numeric', 'min:0'],
            'receiptDate' => ['nullable', 'date'],
            'notes' => ['nullable', 'string', 'max:1000'],
        ];
    }

    public function receive(): void
    {
        $this->resetErrorBag();
        $this->validate();

        $this->loading = true;

        try {
            DB::beginTransaction();

            // Create stock entries for each received item
            foreach ($this->purchaseOrder->items as $item) {
                $receivedQuantity = (int) ($this->receivedQuantities[$item->id] ?? 0);
                $unitPrice = (float) ($this->unitPrices[$item->id] ?? $item->unit_price);

                if ($receivedQuantity > 0) {
                    // Get expiry date for this item
                    $expiryDate = $this->expiryDates[$item->id] ?: null;

                    // Create stock entry
                    StockEntry::create([
                        'reference' => StockEntry::generateUniqueReference(),
                        'product_id' => $item->product_id,
                        'supplier_id' => $this->purchaseOrder->supplier_id,
                        'purchase_order_id' => $this->purchaseOrder->id,
                        'purchase_order_item_id' => $item->id,
                        'user_id' => Auth::id(),
                        'quantity' => $receivedQuantity,
                        'remaining_quantity' => $receivedQuantity,
                        'purchase_price' => $unitPrice,
                        'batch_no' => StockEntry::generateUniqueBatchNumber(),
                        'source_type' => StockEntry::SOURCE_TYPE_PURCHASE,
                        'status' => StockEntry::STATUS_COMPLETED,
                        'expiry_date' => $expiryDate,
                        'notes' => "Réception du bon de commande {$this->purchaseOrder->reference}",
                    ]);

                    // Update product stock
                    $item->product->increment('current_stock', $receivedQuantity);

                    // Update received quantity and unit price in purchase order item
                    $item->update([
                        'received_quantity' => $receivedQuantity,
                        'unit_price' => $unitPrice,
                    ]);
                }
            }

            // Update purchase order status to received
            $this->purchaseOrder->update(['status' => PurchaseOrder::STATUS_RECEIVED]);

            DB::commit();

            $this->success = true;

            // Redirect to purchase order show page after success
            $this->js("
                setTimeout(() => {
                    window.location.href = '".route('purchase-orders.show', $this->purchaseOrder)."';
                }, 2000);
            ");

        } catch (\Exception $e) {
            DB::rollBack();
            report($e);
            $this->addError('error', 'Une erreur est survenue: '.$e->getMessage());
        } finally {
            $this->loading = false;
        }
    }

    public function render(): \Illuminate\Contracts\View\View
    {
        return view('livewire.purchase-orders.receive');
    }
}
