<?php

namespace App\Http\Requests\Invoicing;

use Illuminate\Foundation\Http\FormRequest;

use App\Rules\SAT\ValidSatCode;

use App\Rules\Invoicing\MoralTaxIdentifier;

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

    public function rules(): array
    {
        // Variables de Control
        $country         = session('country', 'MEX');

        return [
          // Payment dependency
            'invoice_id' => ['required','integer','exists:tax_invoices,id'],

          // Formato interno de impresión/timbrado
            'tax_branch_id' => ['required','integer','exists:tax_branches,id'],
            'tax_format_id' => ['nullable', 'integer', 'exists:tax_formats,id'],

          // Payment Context
            'cfdi_use' => ['nullable', 'string'],
            'payment_date' => ['required', 'date_format:Y-m-d\TH:i:s'],
            'payment_form'  => [
                'required',
                new ValidSatCode( table: 'catalog_items', column: 'item_key', wheres: ['catalog_code' => 'c_FormaPago'] )
            ],

            'currency'      => ['required', new ValidSatCode(table: 'catalog_items', column: 'item_key', wheres: ['catalog_code' => 'c_Moneda'])],
            'amount'       => ['required','numeric','gt:0'],
            'exchange_rate'=> ['nullable','numeric','gt:0'],

            'previous_balance'  => ['required','numeric','gte:0'],
            'amount_paid'       => ['required','numeric','gt:0'],
            'remaining_balance' => ['required','numeric','gte:0'],
            'invoice_exchange_rate' => ['nullable','numeric','gte:0'],

          // Third Account reference
            'third_party'            => ['nullable', 'array'],
            'third_party.tax_id'     => ['nullable', new MoralTaxIdentifier($country)],
            'third_party.legal_name' => ['nullable', 'string', 'max:255'],
            'third_party.tax_system' => ['nullable', new ValidSatCode( table: 'catalog_items', column: 'item_key', wheres: ['catalog_code' => 'c_RegimenFiscal'] )],
            'third_party.zip'        => ['nullable','string','max:10'],
        ];
    }
}
