<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Client;

class Clients extends Component
{
    public $clients, $name, $company_name, $email, $phone, $client_id;
    public $isOpen = false;

    public function render()
    {
        $this->clients = Client::all();
        return view('livewire.clients');
    }

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

    public function store()
    {
        $this->validate([
            'name' => 'required',
            // El email es opcional, pero si lo ponen debe ser válido
            'email' => 'nullable|email', 
        ]);

        Client::updateOrCreate(['id' => $this->client_id], [
            'name' => $this->name,
            'company_name' => $this->company_name,
            'email' => $this->email,
            'phone' => $this->phone,
        ]);

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

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

    public function edit($id)
    {
        $client = Client::findOrFail($id);
        $this->client_id = $id;
        $this->name = $client->name;
        $this->company_name = $client->company_name;
        $this->email = $client->email;
        $this->phone = $client->phone;

        $this->isOpen = true;
    }

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

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

    private function resetInputFields()
    {
        $this->name = '';
        $this->company_name = '';
        $this->email = '';
        $this->phone = '';
        $this->client_id = null;
    }
}