<?php

namespace App\Http\Requests\Invoicing;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

use App\Rules\Invoicing\PostalCode;
use App\Rules\Invoicing\MoralTaxIdentifier;
use App\Rules\Invoicing\PhysicalTaxIdentifier;

use App\Rules\SAT\ValidSatCode;
use Illuminate\Support\Facades\Log;

class UpdateClientFiscalDataRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        // Variables de Control
        $session_country = session('country', 'MEX');
        $tax_country_is_mex  = $this->input('individual_country', 'MEX') === 'MEX';

        // Requested Data
        $requested_tax_id = $this->input('tax_identifier');
        $is_generic_mex = $tax_country_is_mex && $requested_tax_id === 'XAXX010101000';

        // Validaciones Dinámicas
        $tax_unique = Rule::unique('clients', 'tax_id');

        // Si viene hidden_id (modo edición), ignoramos ese ID
        if ($tax_country_is_mex && $this->filled('hidden_id'))
            $tax_unique = $tax_unique->ignore($this->input('hidden_id'));

        return [
            // Identidad Fiscal
            'legal_name'        => ['required','max:200',"regex:/^[A-Za-zÁÉÍÓÚÜÑáéíóúüñ0-9 .,'&\-\/]{3,200}$/u"],
            'email_billing'     => ['required','email','max:200'],
            'is_moral_person'   => ['required', 'boolean'],

            // Dependientes del País
            'tax_system'        => !$tax_country_is_mex
                ? ['nullable']
                : ($is_generic_mex ? ['nullable', 'string', 'in:616'] : ['required', 'string', 'max:3']),

            'individual_zip'    => !$tax_country_is_mex
                ? ['nullable', 'string', 'in:00000']
                : ($is_generic_mex ? ['nullable'] : ['required', new PostalCode($session_country)]),

            'tax_identifier'    => !$tax_country_is_mex
                ? ['nullable', 'string', 'in:XEXX010101000']
                : (
                    $is_generic_mex
                        ? ['required', 'string', 'in:XAXX010101000']
                        : [
                            'required',
                            $tax_unique, // Los RFC serán únicos solo en México (no aplica para XAXX)
                            $this->boolean('is_moral_person')
                                ? new MoralTaxIdentifier($session_country)
                                : new PhysicalTaxIdentifier($session_country),
                        ]
                ),

            'cfdi_use'           => !$tax_country_is_mex
                ? ['nullable', 'string', 'in:S01']
                : (
                    $is_generic_mex
                        ? ['nullable', 'string', 'in:S01']
                        : ['required', new ValidSatCode(table: 'catalog_items', column: 'item_key', wheres: ['catalog_code' => 'c_UsoCFDI'])]
                ),

            // Fiscal Address
            'individual_street'      => ['nullable','max:80','regex:/^[A-Za-zÀ-ÿÑñ0-9 .,#\'\-\/]{2,80}$/u'],
            'individual_ext_number'  => ['nullable','max:50','regex:/^(S\/N|SN|s\/n|sn|[A-Za-z0-9\-\/# ]{1,50})$/u'],
            'individual_int_number'  => ['nullable','max:50','regex:/^(S\/N|SN|s\/n|sn|[A-Za-z0-9\-\/# ]{1,50})$/u'],
            'individual_neighborhood'=> ['nullable','max:60','regex:/^[A-Za-zÀ-ÿÑñ0-9 .,\'()\-]{2,60}$/u'],
            'individual_city'        => ['nullable','string','max:80'],
            'individual_municipality'=> ['nullable','max:60','regex:/^[A-Za-zÀ-ÿÑñ .,\'\-]{2,60}$/u'],
            'individual_state'       => ['nullable','max:60','regex:/^[A-Za-zÀ-ÿÑñ .,\'\-]{2,60}$/u'],
            'individual_country'     => ['nullable','string','max:56'],
        ];
    }

    public function messages(): array
    {
        return [
            'tax_identifier.unique' => 'tax_id_duplicate', // Enforce special error case
            'tax_identifier.in' => __('validation.custom.foreign_tax_identifier'),
            'individual_zip.in' => __('validation.custom.foreign_individual_zip'),
            'cfdi_use.in' => __('validation.custom.foreign_cfdi_use'),
        ];
    }
}
