<?php

namespace App\Livewire\Pos;

use App\Models\Product;
use App\Models\PurchaseOrder;
use App\Models\PurchaseOrderItem;
use App\Models\Supplier;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Livewire\Component;

class QuickPurchaseOrder extends Component
{
    public bool $showModal = false;
    public ?int $supplierId = null;
    public array $items = [];
    public string $notes = '';

    protected $listeners = ['openQuickPO' => 'open'];

    public function open()
    {
        $this->reset(['supplierId', 'items', 'notes']);
        $this->showModal = true;
    }

    public function addProduct(int $productId)
    {
        $product = Product::find($productId);
        
        if (!$product) return;

        // Check if product already in list
        $existingIndex = collect($this->items)->search(fn($item) => $item['product_id'] == $productId);
        
        if ($existingIndex !== false) {
            // Increment quantity
            $this->items[$existingIndex]['quantity']++;
        } else {
            // Add new item
            $this->items[] = [
                'product_id' => $productId,
                'name' => $product->name,
                'sku' => $product->sku,
                'quantity' => 1,
                'cost_price' => $product->cost_price,
            ];
        }
    }

    public function updateQuantity(int $index, int $quantity)
    {
        if ($quantity < 1) {
            $this->removeItem($index);
            return;
        }

        if (isset($this->items[$index])) {
            $this->items[$index]['quantity'] = $quantity;
        }
    }

    public function updateCost(int $index, float $cost)
    {
        if (isset($this->items[$index])) {
            $this->items[$index]['cost_price'] = max(0, $cost);
        }
    }

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

    public function createPO()
    {
        $this->validate([
            'supplierId' => 'required|exists:suppliers,id',
            'items' => 'required|array|min:1',
            'items.*.product_id' => 'required|exists:products,id',
            'items.*.quantity' => 'required|integer|min:1',
            'items.*.cost_price' => 'required|numeric|min:0',
        ]);

        DB::transaction(function () {
            // Calculate total
            $total = collect($this->items)->sum(fn($item) => 
                $item['quantity'] * $item['cost_price']
            );

            // Create PO
            $po = PurchaseOrder::create([
                'po_number' => PurchaseOrder::generatePONumber(),
                'supplier_id' => $this->supplierId,
                'branch_id' => Auth::user()->branch_id ?? 1,
                'order_date' => now(),
                'status' => 'draft',
                'total' => $total,
                'notes' => $this->notes,
                'created_by' => Auth::id(),
            ]);

            // Create PO items
            foreach ($this->items as $item) {
                PurchaseOrderItem::create([
                    'purchase_order_id' => $po->id,
                    'product_id' => $item['product_id'],
                    'quantity' => $item['quantity'],
                    'cost_price' => $item['cost_price'],
                    'received_qty' => 0,
                ]);
            }
        });

        session()->flash('success', __('Purchase Order created successfully.'));
        
        $this->showModal = false;
        $this->reset(['supplierId', 'items', 'notes']);
        
        // Refresh parent component if needed
        $this->dispatch('po-created');
    }

    public function render()
    {
        $suppliers = Supplier::active()->orderBy('name')->get();
        $products = Product::active()
            ->with('category')
            ->orderBy('name')
            ->get();

        return view('livewire.pos.quick-purchase-order', [
            'suppliers' => $suppliers,
            'products' => $products,
        ]);
    }
}
