<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use App\Models\Visitor;

class VisitorRegistrationRequest 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
    {
        // Get visit ID from route
        $visitId = $this->route('id');

        // Check if main visitor already exists with images
        $existingMainVisitor = Visitor::where('visit_id', $visitId)
            ->where('is_main_visitor', true)
            ->first();

        // Build rules array
        // NOTE: Image validation is handled in the controller because PHP converts
        // dot notation (mainVisitor.idFrontImage) to underscores (mainVisitor_idFrontImage)
        // which causes validation mismatches
        $rules = [
            // Main Visitor
            'mainVisitor.name' => 'required|string|min:2|max:255',
            'mainVisitor.email' => 'required|email|max:255',
            'mainVisitor.phone' => ['required', 'regex:/^01[0125][0-9]{8}$/'],
            'mainVisitor.companyName' => 'nullable|string|max:255',

            // Additional Visitors (optional)
            'additionalVisitors' => 'nullable|array|max:10',
            'additionalVisitors.*.name' => 'required|string|min:2|max:255',
            'additionalVisitors.*.email' => 'required|email|max:255',
            'additionalVisitors.*.phone' => ['required', 'regex:/^01[0125][0-9]{8}$/'],
            'additionalVisitors.*.companyName' => 'nullable|string|max:255',
        ];

        return $rules;
    }

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'mainVisitor.name.required' => 'Visitor name is required',
            'mainVisitor.email.required' => 'Visitor email is required',
            'mainVisitor.email.email' => 'Please provide a valid email address',
            'mainVisitor.phone.required' => 'Phone number is required',
            'mainVisitor.phone.regex' => 'Phone number must be a valid Egyptian mobile number (e.g., 01012345678)',
            'mainVisitor.idFrontImage.required' => 'Front ID image is required',
            'mainVisitor.idFrontImage.max' => 'ID front image must not exceed 5MB',
            'mainVisitor.idBackImage.required' => 'Back ID image is required',
            'mainVisitor.idBackImage.max' => 'ID back image must not exceed 5MB',
            'additionalVisitors.max' => 'Maximum 10 additional visitors allowed',
            'additionalVisitors.*.phone.regex' => 'Phone number must be a valid Egyptian mobile number',
            'additionalVisitors.*.idFrontImage.max' => 'ID front image must not exceed 5MB',
            'additionalVisitors.*.idBackImage.max' => 'ID back image must not exceed 5MB',
        ];
    }
}
