<?php

namespace Modules\Guardians\Http\Requests;

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

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

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            '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'
            ],
            'phone' => [
                'nullable',
                'string',
                'max:20',
                'regex:/^[\+]?[0-9\s\-\(\)]+$/'
            ],
            'address' => [
                'nullable',
                'string',
                'max:500'
            ],
            'occupation' => [
                'nullable',
                'string',
                'max:255'
            ],
            'students' => [
                'nullable',
                'array'
            ],
            'students.*.student_id' => [
                'required_with:students',
                'integer',
                'exists:students,id'
            ],
            'students.*.relationship' => [
                'required_with:students',
                'string',
                'in:father,mother,guardian,other'
            ],
        ];
    }

    /**
     * Get custom validation messages.
     */
    public function messages(): array
    {
        return [
            'first_name.required' => 'Please enter the guardian\'s first name.',
            'first_name.regex' => 'First name should only contain letters, spaces, periods, hyphens, and apostrophes.',
            'last_name.required' => 'Please enter the guardian\'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.',
            'phone.regex' => 'Please enter a valid phone number.',
            'students.*.student_id.exists' => 'Selected student does not exist.',
            'students.*.relationship.in' => 'Please select a valid relationship type.',
        ];
    }

    /**
     * Configure the validator instance.
     */
    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            // Check if students are active
            if ($this->students && is_array($this->students)) {
                $studentIds = collect($this->students)->pluck('student_id')->filter();

                $inactiveStudents = \Modules\Students\Models\Student::whereIn('id', $studentIds)
                    ->where('is_active', false)
                    ->exists();

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

                // Check for duplicate student assignments
                $duplicateStudents = collect($this->students)
                    ->pluck('student_id')
                    ->duplicates();

                if ($duplicateStudents->isNotEmpty()) {
                    $validator->errors()->add('students', 'Cannot assign the same student multiple times.');
                }

                // Check if students already have guardians (optional business rule)
                foreach ($this->students as $index => $studentData) {
                    if (isset($studentData['student_id'])) {
                        $existingGuardians = \Illuminate\Support\Facades\DB::table('student_guardians')
                            ->where('student_id', $studentData['student_id'])
                            ->count();

                        // Allow maximum 2 guardians per student
                        if ($existingGuardians >= 2) {
                            $validator->errors()->add(
                                "students.{$index}.student_id",
                                'This student already has the maximum number of guardians (2).'
                            );
                        }
                    }
                }
            }

            // Validate phone number format more strictly
            if ($this->phone) {
                $cleanPhone = preg_replace('/[^\d]/', '', $this->phone);
                if (strlen($cleanPhone) < 10 || strlen($cleanPhone) > 15) {
                    $validator->errors()->add('phone', 'Phone number must be between 10 and 15 digits.');
                }
            }
        });
    }

    /**
     * Get custom attributes for validator errors.
     */
    public function attributes(): array
    {
        return [
            'first_name' => 'first name',
            'last_name' => 'last name',
            'students.*.student_id' => 'student',
            'students.*.relationship' => 'relationship',
        ];
    }
}
