<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'student_name' => ['required', 'string', 'regex:/^[a-zA-Z\s]+$/', 'max:100'],
            'parent_name' => ['required', 'string', 'regex:/^[a-zA-Z\s]+$/', 'max:100'],
            'email' => ['required', 'email', 'max:255'],
            'phone' => ['required', 'digits:10'],
            'eventid' => ['required', 'exists:events,Id'],
        ];
    }

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'student_name.required' => 'Student name is required.',
            'student_name.string' => 'Student name must be a string.',
            'student_name.regex' => 'Student name may only contain letters and spaces.',
            'student_name.max' => 'Student name cannot exceed 100 characters.',

            'parent_name.required' => 'Parent name is required.',
            'parent_name.string' => 'Parent name must be a string.',
            'parent_name.regex' => 'Parent name may only contain letters and spaces.',
            'parent_name.max' => 'Parent name cannot exceed 100 characters.',

            'email.required' => 'Email is required.',
            'email.email' => 'Please provide a valid email address.',
            'email.max' => 'Email cannot exceed 255 characters.',

            'phone.required' => 'Phone number is required.',
            'phone.digits' => 'Phone number must be exactly 10 digits.',

            'eventid.required' => 'Please select an event.',
            'eventid.exists' => 'The selected event does not exist.',
        ];
    }

    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation(): void
    {
        $this->merge([
            'student_name' => trim($this->student_name),
            'parent_name' => trim($this->parent_name),
            'email' => strtolower(trim($this->email)),
            'phone' => preg_replace('/[^0-9]/', '', $this->phone),
        ]);
    }
}
