<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rules\Password;

class RegisterRequest 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.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        $rules = [
            'name' => ['required', 'string', 'max:191', 'regex:/^[a-zA-Z\s]+$/'],
            'email' => ['required', 'string', 'email', 'max:191', 'unique:users,email'],
            'username' => ['required', 'string', 'max:191', 'min:3', 'alpha_dash', 'unique:users,username'],
            'password' => [
                'required',
                'string',
                'confirmed',
                Password::min(8)
                    ->mixedCase()
                    ->numbers()
                    ->symbols()
            ],
            'role' => ['required', 'string', 'exists:roles,name', 'not_in:Super Manager,Manager'],
            'terms' => ['required', 'accepted'],
        ];

        // Add role-specific validation rules
        $roleRules = $this->getRoleSpecificRules();
        $rules = array_merge($rules, $roleRules);

        return $rules;
    }

    /**
     * Get custom messages for validator errors.
     *
     * @return array<string, string>
     */
    public function messages(): array
    {
        return [
            'name.required' => 'Please enter your full name.',
            'name.regex' => 'Name can only contain letters and spaces.',
            'email.required' => 'Please enter your email address.',
            'email.email' => 'Please enter a valid email address.',
            'email.unique' => 'This email is already registered.',
            'username.required' => 'Please choose a username.',
            'username.alpha_dash' => 'Username can only contain letters, numbers, dashes, and underscores.',
            'username.unique' => 'This username is already taken.',
            'password.required' => 'Please create a password.',
            'password.confirmed' => 'Password confirmation does not match.',
            'role.required' => 'Please select a role.',
            'role.not_in' => 'Invalid role selection.',
            'terms.required' => 'You must accept the terms and conditions.',
        ];
    }

    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation(): void
    {
        $this->merge([
            'name' => strip_tags(trim($this->name)),
            'email' => strtolower(trim($this->email)),
            'username' => strtolower(trim($this->username)),
        ]);
    }

    /**
     * Configure the validator instance.
     *
     * @param \Illuminate\Validation\Validator $validator
     */
    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            // Prevent Super Manager and Manager role registration
            if (in_array($this->role, ['Super Manager', 'Manager'])) {
                $validator->errors()->add('role', 'This role cannot be selected during registration.');
            }
        });
    }

    /**
     * Get role-specific validation rules.
     *
     * @return array
     */
    protected function getRoleSpecificRules(): array
    {
        $role = $this->input('role');

        if (!$role) {
            return [];
        }

        $rules = [
            'Members' => [
                'phone' => ['nullable', 'string', 'max:20'],
                'address' => ['nullable', 'string', 'max:500'],
                'emergency_contact_name' => ['nullable', 'string', 'max:191'],
                'emergency_contact_phone' => ['nullable', 'string', 'max:20'],
            ],
            'Trainers' => [
                'certification' => ['nullable', 'string', 'max:191'],
                'specialization' => ['nullable', 'string', 'max:191'],
                'experience_years' => ['nullable', 'integer', 'min:0', 'max:50'],
                'bio' => ['nullable', 'string', 'max:1000'],
            ],
            'Trainees' => [
                'fitness_level' => ['nullable', 'string', 'in:beginner,intermediate,advanced'],
                'goals' => ['nullable', 'string', 'max:1000'],
                'medical_conditions' => ['nullable', 'string', 'max:1000'],
                'trainer_preference' => ['nullable', 'string', 'max:191'],
            ],
            'Mentor' => [
                'expertise_areas' => ['nullable', 'string', 'max:1000'],
                'mentoring_experience' => ['nullable', 'string', 'max:191'],
                'availability' => ['nullable', 'string', 'max:100'],
                'bio' => ['nullable', 'string', 'max:1000'],
            ],
            'Mentee' => [
                'learning_goals' => ['nullable', 'string', 'max:1000'],
                'experience_level' => ['nullable', 'string', 'in:beginner,intermediate,advanced'],
                'mentor_preference' => ['nullable', 'string', 'max:191'],
                'bio' => ['nullable', 'string', 'max:1000'],
            ],
            'Partners' => [
                'company_name' => ['required', 'string', 'max:191'],
                'partnership_type' => ['nullable', 'string', 'max:100'],
                'contact_person' => ['nullable', 'string', 'max:191'],
                'address' => ['nullable', 'string', 'max:500'],
            ],
            'Contributor' => [
                'contribution_type' => ['nullable', 'string', 'max:100'],
                'portfolio_url' => ['nullable', 'url', 'max:500'],
                'skills' => ['nullable', 'string', 'max:1000'],
                'bio' => ['nullable', 'string', 'max:1000'],
            ],
            'Health Marketor' => [
                'marketing_focus' => ['nullable', 'string', 'max:191'],
                'target_audience' => ['nullable', 'string', 'max:191'],
                'campaign_experience' => ['nullable', 'string', 'max:191'],
                'bio' => ['nullable', 'string', 'max:1000'],
            ],
        ];

        return $rules[$role] ?? [];
    }
}
