<?php

namespace App\Livewire\Clients;

use App\Models\Clients\Client;
use App\Livewire\Traits\HasClientValidation;
use Livewire\Component;

class Edit extends Component
{
    use HasClientValidation;
    public Client $client;
    public string $name = '';
    public string $shortname = '';
    public ?string $crm_id = null;
    public ?string $cif = null;
    public ?string $razon_social = null;
    public ?string $fecha_inicio_relacion = null;
    public array $contacts = [];
    public ?string $description = null;
    public ?string $jira = null;
    public bool $actived = true;
    public ?string $observation = null;

    public function mount(Client $client)
    {
        $this->client = $client;
        $this->name = $client->name ?? '';
        $this->shortname = $client->shortname ?? '';
        $this->crm_id = $client->crm_id;
        $this->cif = $client->cif;
        $this->razon_social = $client->razon_social;
        $this->fecha_inicio_relacion = $client->fecha_inicio_relacion?->format('Y-m-d');
        
        // Cargar contactos desde el JSON
        if (!empty($client->contacts) && is_array($client->contacts)) {
            $this->contacts = $client->contacts;
        } else {
            $this->contacts = [['name' => '', 'email' => '', 'phone' => '']];
        }
        
        $this->description = $client->description;
        $this->jira = $client->jira;
        $this->actived = $client->actived ?? true;
        $this->observation = $client->observation;
    }

    protected function rules()
    {
        return $this->getClientValidationRules();
    }

    public function update()
    {
        $this->authorize('admin.clients.edit');
        
        $validated = $this->validate();
        $validated['actived'] = $this->actived;
        $validated = $this->normalizeContacts($validated);

        $this->client->update($validated);

        session()->flash('success', 'Cliente actualizado correctamente.');

        return $this->redirect(route('clients.index'), navigate: true);
    }

    public function render()
    {
        return view('livewire.clients.edit')->layout('layouts.clean');
    }
}

