<?php

namespace Koneko\VuexyContacts\Traits;

trait HasContactsAttributes
{
    /**
     * Tipos de RFC disponibles.
     */
    public const TIPO_RFC_INVALID = 0;
    public const TIPO_RFC_FISICA  = 1;
    public const TIPO_RFC_MORAL   = 2;
    public const TIPO_RFC_PUBLICO = 9;

    /**
     * Lista de nombres para cada tipo de RFC.
     */
    public static array $tipoRfcList = [
        self::TIPO_RFC_INVALID => 'RFC inválido',
        self::TIPO_RFC_FISICA  => 'Persona física',
        self::TIPO_RFC_MORAL   => 'Persona moral',
        self::TIPO_RFC_PUBLICO => 'Público en general',
    ];

    /**
     * Agrega atributos específicos al `$fillable` del modelo sin modificarlo directamente.
     *
     * @return array
     */
    public function getFillable()
    {
        return array_merge(parent::getFillable(), [
            'code',
            'parent_id',
            'agent_id',
            'company',
            'birth_date',
            'hire_date',
            'curp',
            'nss',
            'job_title',
            'rfc',
            'nombre_fiscal',
            'tipo_persona',
            'c_regimen_fiscal',
            'domicilio_fiscal',
            'c_uso_cfdi',
            'note',
            'is_partner',
            'is_employee',
            'is_prospect',
            'is_customer',
            'is_provider',
            'is_user',
        ]);
    }

    /**
     * Detecta el tipo de RFC con base en el formato de caracteres.
     */
    public function getTipoRfcAttribute(): int
    {
        $rfc = strtoupper(trim($this->attributes['rfc'] ?? ''));

        if ($rfc === 'XAXX010101000') {
            return self::TIPO_RFC_PUBLICO;
        }

        $longitud = strlen($rfc);

        if (!in_array($longitud, [12, 13])) {
            return self::TIPO_RFC_INVALID;
        }

        return ($longitud === 13) ? self::TIPO_RFC_FISICA : self::TIPO_RFC_MORAL;
    }
}