<?php

namespace App\Livewire\Inventory\PurchaseOrders;

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

class Edit extends Component
{
    public PurchaseOrder $purchaseOrder;
    
    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(PurchaseOrder $purchaseOrder)
    {
        $this->purchaseOrder = $purchaseOrder->load(['items.part']);
        
        $this->supplier_id = $purchaseOrder->supplier_id;
        $this->order_date = $purchaseOrder->order_date->format('Y-m-d');
        $this->expected_date = $purchaseOrder->expected_date ? $purchaseOrder->expected_date->format('Y-m-d') : '';
        $this->notes = $purchaseOrder->notes;
        $this->status = $purchaseOrder->status;
        
        // Load existing items
        foreach ($purchaseOrder->items as $item) {
            $this->items[] = [
                'id' => $item->id,
                'part_id' => $item->part_id,
                'part_name' => $item->part->name,
                'part_number' => $item->part->part_number,
                'quantity' => $item->quantity_ordered,
                'unit_cost' => $item->unit_cost,
                'total_cost' => $item->total_cost,
            ];
        }
    }

    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;
            $this->items[$existingIndex]['total_cost'] = $this->items[$existingIndex]['quantity'] * $this->unitCost;
        } else {
            // Add new item
            $this->items[] = [
                'id' => null, // New item
                '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();

        $this->purchaseOrder->update([
            'supplier_id' => $this->supplier_id,
            'order_date' => $this->order_date,
            'expected_date' => $this->expected_date ?: null,
            'status' => $this->status,
            'notes' => $this->notes,
        ]);

        // Delete existing items and recreate
        $this->purchaseOrder->items()->delete();

        foreach ($this->items as $item) {
            $this->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 updated successfully!');
        
        return $this->redirect(route('inventory.purchase-orders.show', $this->purchaseOrder), navigate: true);
    }

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

    public function render()
    {
        $suppliers = Supplier::where('is_active', true)->orderBy('name')->get();
        $parts = Part::orderBy('name')->get();

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