<?php

namespace Modules\Students\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StoreStudentRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return $this->user()->hasRole('admin') || $this->user()->hasRole('teacher');
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'student_id' => [
                'nullable',
                'string',
                'max:50',
                'unique:students,student_id'
            ],
            'first_name' => [
                'required',
                'string',
                'max:100',
                'regex:/^[a-zA-Z\s\.\-\']+$/'
            ],
            'last_name' => [
                'required',
                'string',
                'max:100',
                'regex:/^[a-zA-Z\s\.\-\']+$/'
            ],
            'email' => [
                'required',
                'email',
                'max:255',
                'unique:users,email'
            ],
            'password' => [
                'nullable',
                'string',
                'min:8',
                'confirmed'
            ],
            'date_of_birth' => [
                'required',
                'date',
                'before:today',
                'after:' . now()->subYears(25)->format('Y-m-d')
            ],
            'gender' => [
                'required',
                'string',
                'in:male,female,other'
            ],
            'address' => [
                'nullable',
                'string',
                'max:500'
            ],
            'phone' => [
                'nullable',
                'string',
                'max:20',
                'regex:/^[\+]?[0-9\s\-\(\)]+$/'
            ],
            'emergency_contact' => [
                'nullable',
                'string',
                'max:20',
                'regex:/^[\+]?[0-9\s\-\(\)]+$/'
            ],
            'admission_date' => [
                'required',
                'date',
                'before_or_equal:today'
            ],
            'guardians' => [
                'nullable',
                'array',
                'max:4'
            ],
            'guardians.*.guardian_id' => [
                'required_with:guardians',
                'integer',
                'exists:guardians,id'
            ],
            'guardians.*.relationship' => [
                'required_with:guardians',
                'string',
                'in:father,mother,guardian,other'
            ],
        ];
    }

    /**
     * Get custom validation messages.
     */
    public function messages(): array
    {
        return [
            'student_id.unique' => 'This student ID is already taken.',
            'first_name.required' => 'Please enter the student\'s first name.',
            'first_name.regex' => 'First name should only contain letters, spaces, periods, hyphens, and apostrophes.',
            'last_name.required' => 'Please enter the student\'s last name.',
            'last_name.regex' => 'Last name should only contain letters, spaces, periods, hyphens, and apostrophes.',
            'email.required' => 'Please enter an email address.',
            'email.unique' => 'This email address is already registered.',
            'date_of_birth.required' => 'Please enter the date of birth.',
            'date_of_birth.before' => 'Date of birth must be in the past.',
            'date_of_birth.after' => 'Student must be under 25 years old.',
            'gender.required' => 'Please select a gender.',
            'phone.regex' => 'Please enter a valid phone number.',
            'emergency_contact.regex' => 'Please enter a valid emergency contact number.',
            'admission_date.required' => 'Please enter the admission date.',
            'admission_date.before_or_equal' => 'Admission date cannot be in the future.',
            'guardians.max' => 'A student can have maximum 4 guardians.',
            'guardians.*.guardian_id.exists' => 'Selected guardian does not exist.',
            'guardians.*.relationship.in' => 'Please select a valid relationship.',
        ];
    }

    /**
     * Configure the validator instance.
     */
    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            // Check if student is at least 3 years old
            if ($this->date_of_birth) {
                $birthDate = \Carbon\Carbon::parse($this->date_of_birth);
                $age = $birthDate->diffInYears(now());
                if ($age < 3) {
                    $validator->errors()->add('date_of_birth', 'Student must be at least 3 years old.');
                }
            }

            // Validate guardian relationships (no duplicates)
            if ($this->guardians && is_array($this->guardians)) {
                $guardianIds = collect($this->guardians)->pluck('guardian_id');
                if ($guardianIds->count() !== $guardianIds->unique()->count()) {
                    $validator->errors()->add('guardians', 'Cannot assign the same guardian multiple times.');
                }

                // Check if guardians are active
                $inactiveGuardians = \Modules\Guardians\Models\Guardian::whereIn('id', $guardianIds)
                    ->where('is_active', false)
                    ->exists();

                if ($inactiveGuardians) {
                    $validator->errors()->add('guardians', 'Cannot assign inactive guardians.');
                }
            }

            // Validate admission date is not too far in the past
            if ($this->admission_date) {
                $admissionDate = \Carbon\Carbon::parse($this->admission_date);
                if ($admissionDate->lt(now()->subYears(20))) {
                    $validator->errors()->add('admission_date', 'Admission date seems too old. Please verify.');
                }
            }
        });
    }

    /**
     * Get custom attributes for validator errors.
     */
    public function attributes(): array
    {
        return [
            'student_id' => 'student ID',
            'first_name' => 'first name',
            'last_name' => 'last name',
            'date_of_birth' => 'date of birth',
            'emergency_contact' => 'emergency contact',
            'admission_date' => 'admission date',
            'guardians.*.guardian_id' => 'guardian',
            'guardians.*.relationship' => 'relationship',
        ];
    }
}
