<?php

namespace App\Http\Livewire\Client;

use App\Models\Client;
use Livewire\Component;
use Illuminate\Support\Str;

class CreateClient extends Component
{
    public $dni, $names, $phone, $ruc, $address;

    protected $rules = [
        'dni' => "required|max:15|unique:clients,dni",
        'names' => 'required|max:110'
    ];

    protected $messages = [
        'dni.required' => 'El DNI del cliente no puede estar vacio',
        'dni.unique' => 'El DNI del cliente ya existe',
        'dni.max' => 'El DNI del cliente maximo son 15 carácteres',
        'names.required' => 'El Nombre Completo no puede estar vacio',
        'names.max' => 'Máximo de carácteres 110',
    ];

    public function updated($propertyName)
    {
        $this->validateOnly($propertyName);
    }


    public function render()
    {
        return view('livewire.client.create-client');
    }

    // Generar DNI
    public function generate()
    {
        $this->reset(['dni']);
        $faker = \Faker\Factory::create();
        $this->dni = $faker->unique()->numerify('###-###-###-###');
        $this->validate();
    }

    // Guardar
    public function save()
    {
        $this->validate();
        Client::create([
            'dni' => Str::lower($this->dni),
            'names' =>  Str::lower($this->names),
            'phone' => Str::lower($this->phone),
            'ruc' => Str::lower($this->ruc),
            'address' => Str::lower($this->address)
        ]);
        $this->reset([
            'dni', 'names', 'phone', 'ruc', 'address'
        ]);
        $this->emitTo('client.index-client', 'render');
        $this->emit('notify', 'Cliente Agregado');
    }
}
