<?php

namespace App\Livewire\Traits;

trait HasClientValidation
{
    /**
     * Obtiene el ID del cliente para la regla unique (null para Create)
     */
    protected function getClientId(): ?int
    {
        return $this->client->id ?? null;
    }

    /**
     * Obtiene las reglas de validación para clientes
     */
    protected function getClientValidationRules(): array
    {
        $clientId = $this->getClientId();
        $uniqueShortname = $clientId 
            ? "unique:clients,shortname,{$clientId}"
            : 'unique:clients,shortname';
        $uniqueCrmId = $clientId
            ? "unique:clients,crm_id,{$clientId}"
            : 'unique:clients,crm_id';

        return [
            'name' => 'required|string|max:200',
            'shortname' => "required|string|max:50|{$uniqueShortname}",
            'crm_id' => "nullable|string|max:100|{$uniqueCrmId}",
            'cif' => 'nullable|string|max:20',
            'razon_social' => 'nullable|string|max:200',
            'fecha_inicio_relacion' => 'nullable|date',
            'contacts' => 'array',
            'contacts.*.name' => 'required_with:contacts.*|string|max:200',
            'contacts.*.email' => 'nullable|email|max:200',
            'contacts.*.phone' => 'nullable|string|max:50',
            'description' => 'nullable|string',
            'jira' => 'nullable|string|max:200',
            'actived' => 'sometimes|accepted',
            'observation' => 'nullable|string',
        ];
    }

    /**
     * Filtra y normaliza los contactos antes de guardar
     */
    protected function normalizeContacts(array $validated): array
    {
        // Filtrar contactos vacíos
        if (!empty($validated['contacts'])) {
            $validated['contacts'] = array_filter($validated['contacts'], function($contact) {
                return !empty($contact['name']) || !empty($contact['email']) || !empty($contact['phone']);
            });
            $validated['contacts'] = array_values($validated['contacts']); // Reindexar
        }

        // Si no hay contactos válidos, establecer como null
        if (empty($validated['contacts'])) {
            $validated['contacts'] = null;
        }

        return $validated;
    }

    /**
     * Agrega un nuevo contacto al array
     */
    public function addContact()
    {
        $this->contacts[] = [
            'name' => '',
            'email' => '',
            'phone' => '',
        ];
    }

    /**
     * Elimina un contacto del array
     */
    public function removeContact($index)
    {
        unset($this->contacts[$index]);
        $this->contacts = array_values($this->contacts); // Reindexar array
    }
}

