<?php

namespace App\Http\Requests;

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

class FuncionarioUpdateRequest 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([
            'rg' => str_replace(['.', '-'], '', $this->rg)
        ]);
        $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:150', Rule::unique('funcionarios')->ignore($this->funcionario)],
            'funcao' => 'required|max:50',
            'rg' => 'required|max:10',
            'cnh' => 'nullable|max:10',
            'cpf' => ['required', Rule::unique('funcionarios')->ignore($this->funcionario), new CPFRule()],
            'sexo' => 'required|numeric',
            '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',
            
            'telefone.*.numero' => 'nullable|regex:/^\(\d{2}\) \d{4,5}-\d{4}$/',
            'telefone.0.numero' => 'required',
            'email.*.endereco' => 'nullable|email',
        ];
    }

    public function attributes()
    {
        return [
            'funcao' => 'função',
            'email.*.endereco' => 'e-mail',
        ];
    }

    public function messages()
    {
        return [
            'telefone.regex' => 'O campo telefone deve ser um telefone válido',
        ];
    }
}
