<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    public function rules(): array
    {
        $nameRegex = '/^[\pL]+([\s\'\-][\pL]+)*$/u';
        $companyRegex = '/^[\pL\d]+([\s\'\-&.,][\pL\d]+)*$/u';
        $messageRegex = '/^[\pL\d\s.,;:!?\'\"()\-\/&@#\n\r]+$/u';

        return [
            'firstName'       => ['required', 'string', 'max:50', 'regex:' . $nameRegex],
            'lastName'        => ['required', 'string', 'max:50', 'regex:' . $nameRegex],
            'email'           => ['required', 'email', 'max:255'],
            'company'         => ['nullable', 'string', 'max:100', 'regex:' . $companyRegex],
            // 'service'         => ['required', 'exists:ref_services,id'],
            'message'         => ['nullable', 'string', 'max:2000', 'regex:' . $messageRegex],
            'recaptcha_token' => ['required', 'string'],
        ];
    }

    public function messages(): array
    {
        return [
            'recaptcha_token.required' => 'reCAPTCHA verification failed. Please try again.',
            'service.exists'           => 'Please select a valid service.',
            'firstName.regex'          => 'First name may only contain letters, hyphens and apostrophes.',
            'lastName.regex'           => 'Last name may only contain letters, hyphens and apostrophes.',
            'company.regex'            => 'Company name contains invalid characters.',
            'message.regex'            => 'Project description contains invalid special characters.',
            'message.max'              => 'Message must not exceed 2000 characters.',
        ];
    }

    protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
    {
        throw new \Illuminate\Validation\ValidationException($validator,
            response()->json([
                'success' => false,
                'errors'  => $validator->errors(),
            ], 422)
        );
    }
}
