<?php

namespace App\Http\Requests;

use App\Models\WayToPayForCompany;
use App\Traits\HasResponse;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class ProofPaymentRequest extends FormRequest
{
    use HasResponse;

    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        $rules = [
            'idclient'                  => ['required', 'numeric', 'validate_ids_exist:User'],
            'idstickets'                => ['required', 'array'],
            'idstickets.*'              => ['required_with:idstickets', 'integer'],
            'payment_ticket'            => ['required', 'array'],
            'payment_ticket.*'          => ['required', 'regex:/^\d+(\.\d{1,3})?$/'],
            'idway_to_pay_for_company'  => ['required', 'validate_ids_exist:WayToPayForCompany'],
            'idcompany'                 => ['nullable'],
            'date_admission'            => ['nullable', 'string'],
            'document_date'             => ['nullable', 'string'],
            'idbank'                    => ['nullable', 'numeric', 'validate_ids_exist:Bank'],
            'serie'                     => ['nullable', 'numeric'],
            'amount'                    => ['nullable', 'string'],
        ];

        $wayToPayForCompany = WayToPayForCompany::find(request('idway_to_pay_for_company'));
        if ($wayToPayForCompany) {
            if ($wayToPayForCompany->wayToPay->SII_fmapago == 1) {
                // Si payment_method es 1, entonces estos campos son requeridos
                $rules = array_merge($rules, [
                    'date_admission' => ['required', 'string'],
                    'document_date'  => ['required', 'string'],
                    'idbank'         => ['required', 'numeric', 'validate_ids_exist:Bank'],
                    'serie'          => ['required', 'numeric'],
                    'amount'         => ['required', 'string'],
                ]);
            }
        } else {
            throw new HttpResponseException($this->errorResponse('El método de pago seleccionado de la empresa no es válido.', 400));
        }

        return $rules;
    }

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            // Verificar la cantidad de elementos en 'idstickets' y 'payment_ticket'
            $idsticketsCount = count($this->input('idstickets', []));
            $paymentTicketCount = count($this->input('payment_ticket', []));

            if ($idsticketsCount !== $paymentTicketCount) {
                $validator->errors()->add('idstickets', 'La cantidad de elementos en idstickets y payment_ticket debe ser la misma.');
            }
        });
    }

    public function failedValidation(Validator $validator)
    {
        throw new HttpResponseException($this->errorResponse('Formato inválido.', 400, $validator->errors()));
    }
}
