<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    public function rules(): array
    {
        return [
            'name' => [
                'required',
                'string',
                'min:2',
                'max:100',
                'regex:/^[\pL\pM\s\'\.\-\/@]+$/u',
            ],
            'g-recaptcha-response' => [
                function ($attribute, $value, $fail) {
                    if (session('captcha_required') && strtoupper(trim($value ?? '')) !== 'ESIJIL') {
                        $fail('Kod pengesahan tidak sah. Sila masukkan ESIJIL.');
                    }
                },
            ],
        ];
    }

    public function messages(): array
    {
        return [
            'name.required' => 'Sila masukkan nama peserta.',
            'name.min' => 'Nama carian mestilah sekurang-kurangnya 2 aksara.',
            'name.max' => 'Nama carian tidak boleh melebihi 100 aksara.',
            'name.regex' => 'Nama carian mengandungi aksara yang tidak dibenarkan.',
        ];
    }

    public function searchName(): string
    {
        return preg_replace('/\s+/u', ' ', trim($this->string('name')->toString()));
    }
}
