<?php

namespace App\Livewire\Inventory\PurchaseOrders;

use App\Models\Part;
use App\Models\PurchaseOrder;
use App\Models\Supplier;
use Livewire\Component;

class Create extends Component
{
    public $supplier_id = '';
    public $order_date;
    public $expected_date = '';
    public $notes = '';
    public $status = 'draft';

    // Items
    public $items = [];
    public $selectedPart = '';
    public $quantity = 1;
    public $unitCost = '';

    protected $rules = [
        'supplier_id' => 'required|exists:suppliers,id',
        'order_date' => 'required|date',
        'expected_date' => 'nullable|date|after:order_date',
        'notes' => 'nullable|string|max:1000',
        'status' => 'required|in:draft,pending,ordered',
        'items' => 'required|array|min:1',
        'items.*.part_id' => 'required|exists:parts,id',
        'items.*.quantity' => 'required|integer|min:1',
        'items.*.unit_cost' => 'required|numeric|min:0',
    ];

    public function mount()
    {
        $this->order_date = now()->format('Y-m-d');
        
        // Pre-select part if passed in URL
        if (request()->has('part_id')) {
            $partId = request()->get('part_id');
            $part = Part::find($partId);
            if ($part) {
                $this->selectedPart = $partId;
                $this->unitCost = $part->cost_price;
                // Pre-fill supplier if part has one
                if ($part->supplier_id) {
                    $this->supplier_id = $part->supplier_id;
                }
            }
        }
    }

    public function updatedSupplierId()
    {
        // Clear selected part when supplier changes
        $this->selectedPart = '';
        $this->unitCost = '';
    }

    public function addItem()
    {
        $this->validate([
            'selectedPart' => 'required|exists:parts,id',
            'quantity' => 'required|integer|min:1',
            'unitCost' => 'required|numeric|min:0',
        ]);

        $part = Part::find($this->selectedPart);
        
        // Check if part already exists in items
        $existingIndex = collect($this->items)->search(function ($item) {
            return $item['part_id'] == $this->selectedPart;
        });

        if ($existingIndex !== false) {
            // Update existing item
            $this->items[$existingIndex]['quantity'] += $this->quantity;
            $this->items[$existingIndex]['unit_cost'] = $this->unitCost;
        } else {
            // Add new item
            $this->items[] = [
                'part_id' => $this->selectedPart,
                'part_name' => $part->name,
                'part_number' => $part->part_number,
                'quantity' => $this->quantity,
                'unit_cost' => $this->unitCost,
                'total_cost' => $this->quantity * $this->unitCost,
            ];
        }

        // Reset form
        $this->reset(['selectedPart', 'quantity', 'unitCost']);
    }

    public function removeItem($index)
    {
        unset($this->items[$index]);
        $this->items = array_values($this->items);
    }

    public function updatedSelectedPart()
    {
        if ($this->selectedPart) {
            $part = Part::find($this->selectedPart);
            $this->unitCost = $part->cost_price ?? '';
        }
    }

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

        $purchaseOrder = PurchaseOrder::create([
            'po_number' => $this->generateOrderNumber(),
            'supplier_id' => $this->supplier_id,
            'order_date' => $this->order_date,
            'expected_date' => $this->expected_date ?: null,
            'status' => $this->status,
            'notes' => $this->notes,
            'approved_by' => auth()->id(),
        ]);

        foreach ($this->items as $item) {
            $purchaseOrder->items()->create([
                'part_id' => $item['part_id'],
                'quantity_ordered' => $item['quantity'],
                'unit_cost' => $item['unit_cost'],
                'total_cost' => $item['quantity'] * $item['unit_cost'],
            ]);
        }

        session()->flash('success', 'Purchase order created successfully!');
        
        return $this->redirect(route('inventory.purchase-orders.show', $purchaseOrder), navigate: true);
    }

    private function generateOrderNumber()
    {
        $year = date('Y');
        $lastOrder = PurchaseOrder::whereYear('created_at', $year)
            ->orderBy('id', 'desc')
            ->first();

        $sequence = $lastOrder ? (int) substr($lastOrder->po_number, -4) + 1 : 1;
        
        return 'PO-' . $year . '-' . str_pad($sequence, 4, '0', STR_PAD_LEFT);
    }

    public function getTotalAmount()
    {
        return collect($this->items)->sum('total_cost');
    }

    public function render()
    {
        $suppliers = Supplier::where('is_active', true)->orderBy('name')->get();
        
        // Filter parts by selected supplier
        $partsQuery = Part::orderBy('name');
        if ($this->supplier_id) {
            $partsQuery->where('supplier_id', $this->supplier_id);
        }
        $parts = $partsQuery->get();

        return view('livewire.inventory.purchase-orders.create', [
            'suppliers' => $suppliers,
            'parts' => $parts,
        ]);
    }
}
