<?php

namespace App\Http\Requests;

use App\Rules\CNPJRule;
use App\Rules\CPFRule;
use Carbon\Carbon;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class ConvenioUpdateRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    protected function prepareForValidation(): void
    {
        $this->merge([
            'cpf' => str_replace(['.', '-'], '', $this->cpf)
        ]);
        $this->merge([
            'cnpj' => str_replace(['.', '-', '/'], '', $this->cnpj)
        ]);
        $this->merge([
            'cep' => str_replace('-', '', $this->cep)
        ]);
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'nome' => ['required', 'max:50', Rule::unique('convenios')->ignore($this->convenio)],
            'cpf' => ['nullable', 'required_without:cnpj', Rule::unique('convenios')->ignore($this->convenio), new CPFRule()],
            'cnpj' => ['nullable', Rule::unique('convenios')->ignore($this->convenio), new CNPJRule()],
            'tipo' => 'required|numeric',
            'tipo_beneficiario' => 'required|numeric',
            'desconto' => 'required|boolean',
            'observacoes' => 'nullable',
            'cep' => 'nullable|numeric',
            'logradouro' => 'nullable|required_with:cep|max:150',
            'bairro' => 'nullable|required_with:cep|max:50',
            'cidade' => 'nullable|required_with:cep|max:100',
            'numero' => 'nullable|numeric|required_with:cep',
            'estado' => 'nullable|required_with:cep|max:2',
            'observacoes_endereco' => 'nullable|max:100',
        ];
    }

    public function messages()
    {
        return [
            'cpf.required_without' => 'Um dos campos - CPF ou CNPJ - devem ser preenchidos',
        ];
    }
}
