<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Product;
use App\Models\Unit;

class Products extends Component
{
    public $products, $name, $unit_id, $price_usd, $product_id;
    public $isOpen = false; // Para abrir/cerrar el formulario (modal)

    public function render()
    {
        $this->products = Product::all();
        return view('livewire.products', [
            'units' => Unit::all()
        ]);
    }

    public function create()
    {
        $this->resetInputFields();
        $this->isOpen = true;
    }

    public function store()
    {
        $this->validate([
            'name' => 'required',
            'unit_id' => 'required',
            'price_usd' => 'required|numeric',
        ]);

        Product::updateOrCreate(['id' => $this->product_id], [
            'name' => $this->name,
            'unit_id' => $this->unit_id,
            'price_usd' => $this->price_usd,
        ]);

        session()->flash('message', $this->product_id ? 'Producto Actualizado.' : 'Producto Creado.');

        $this->isOpen = false;
        $this->resetInputFields();
    }

    public function edit($id)
    {
        $product = Product::findOrFail($id);
        $this->product_id = $id;
        $this->name = $product->name;
        $this->unit_id = $product->unit_id;
        $this->price_usd = $product->price_usd;

        $this->isOpen = true;
    }

    public function delete($id)
    {
        Product::find($id)->delete();
        session()->flash('message', 'Producto Eliminado.');
    }

    public function closeModal()
    {
        $this->isOpen = false;
    }

    private function resetInputFields()
    {
        $this->name = '';
        $this->unit_id = '';
        $this->price_usd = '';
        $this->product_id = null;
    }
}