<?php

namespace App\Livewire\PurchaseOrders;

use App\Models\Product;
use Livewire\Attributes\Layout;
use Livewire\Component;

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

    //Form variables
    public $product_id;
    public $quantity = 1;
    public $unit = 'Pièce';
    public $unit_price = 0;

    //utils
    public $products;
    public $loading = false;

    public function rules()
    {
        return [
            'product_id' => 'required|exists:products,id',
            'quantity' => 'required|numeric|min:1',
            'unit_price' => 'required|numeric|min:1',
            'unit' => 'required|string|max:255',
        ];
    }


    public function mount($purchaseOrder)
    {
        $this->purchaseOrder = $purchaseOrder;
        $this->products = Product::where('status', Product::STATUS_ACTIVE)->get();
    }

    public function updatedProductId()
    {
        if ($this->product_id) {
            $product = Product::find($this->product_id);
            if($product && $purchaseUnit = $product->purchaseUnit){
                $this->unit = $purchaseUnit->name;
                $this->unit_price = $product->purchase_price;
            }
        }
    }

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

        $this->loading = true;

        $this->purchaseOrder->items()->create([
            'product_id' => $this->product_id,
            'quantity' => $this->quantity,
            'unit' => $this->unit,
            'unit_price' => $this->unit_price,
            'total_price' => $this->unit_price * $this->quantity,
        ]);

        $this->loading = false;
        $this->quantity = 1;
        $this->unit_price = 0;
        $this->unit = 'Pièce';
        $this->product_id = null;
        $this->dispatch('purchase-order-item-added');
        $this->dispatch('clear-input-select-product_id');
    }

    /**
     * Render the component
     *
     * @return \Illuminate\Contracts\View\View
     */
    public function render(): \Illuminate\Contracts\View\View
    {
        return view('livewire.purchase-orders.add-item');
    }
};

