<?php

namespace Modules\Enrollment\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Modules\Enrollment\Models\Enrollment;
use Modules\Academic\Models\Classroom;

class StoreEnrollmentRequest 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 [
            'student_id' => [
                'required',
                'integer',
                'exists:students,id'
            ],
            'classroom_id' => [
                'required',
                'integer',
                'exists:classrooms,id'
            ],
            'academic_year_id' => [
                'required',
                'integer',
                'exists:academic_years,id'
            ],
            'enrolled_at' => [
                'nullable',
                'date',
                'before_or_equal:today'
            ],
        ];
    }

    /**
     * Get custom validation messages.
     */
    public function messages(): array
    {
        return [
            'student_id.required' => 'Please select a student.',
            'student_id.exists' => 'Selected student does not exist.',
            'classroom_id.required' => 'Please select a classroom.',
            'classroom_id.exists' => 'Selected classroom does not exist.',
            'academic_year_id.required' => 'Please select an academic year.',
            'academic_year_id.exists' => 'Selected academic year does not exist.',
            'enrolled_at.date' => 'Please enter a valid enrollment date.',
            'enrolled_at.before_or_equal' => 'Enrollment date cannot be in the future.',
        ];
    }

    /**
     * Configure the validator instance.
     */
    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            // Check if student is active
            if ($this->student_id) {
                $student = \Modules\Students\Models\Student::find($this->student_id);
                if ($student && !$student->is_active) {
                    $validator->errors()->add('student_id', 'Cannot enroll inactive student.');
                }
            }

            // Check if classroom's academic year is active
            if ($this->classroom_id) {
                $classroom = Classroom::with('academicYear')->find($this->classroom_id);
                if ($classroom && $classroom->academicYear && !$classroom->academicYear->is_active) {
                    $validator->errors()->add('classroom_id', 'Cannot enroll in classroom with inactive academic year.');
                }
            }

            // Check if academic year is valid for the classroom
            if ($this->classroom_id && $this->academic_year_id) {
                $classroom = Classroom::find($this->classroom_id);
                if ($classroom && $classroom->academic_year_id !== (int)$this->academic_year_id) {
                    $validator->errors()->add('academic_year_id', 'Selected academic year does not match the classroom\'s academic year.');
                }
            }

            // Check for duplicate enrollment
            if ($this->student_id && $this->classroom_id && $this->academic_year_id) {
                $existingEnrollment = Enrollment::where('student_id', $this->student_id)
                    ->where('classroom_id', $this->classroom_id)
                    ->where('academic_year_id', $this->academic_year_id)
                    ->where('is_active', true)
                    ->first();

                if ($existingEnrollment) {
                    $validator->errors()->add('student_id', 'Student is already enrolled in this classroom for the selected academic year.');
                }
            }

            // Check if student is already enrolled in another classroom for the same academic year
            if ($this->student_id && $this->academic_year_id) {
                $existingEnrollment = Enrollment::where('student_id', $this->student_id)
                    ->where('academic_year_id', $this->academic_year_id)
                    ->where('is_active', true)
                    ->first();

                if ($existingEnrollment) {
                    $classroom = Classroom::find($existingEnrollment->classroom_id);
                    $validator->errors()->add('student_id', "Student is already enrolled in {$classroom->name} for this academic year.");
                }
            }

            // Check classroom capacity
            if ($this->classroom_id && $this->academic_year_id) {
                $classroom = Classroom::find($this->classroom_id);
                if ($classroom && $classroom->capacity) {
                    $currentEnrollments = Enrollment::where('classroom_id', $this->classroom_id)
                        ->where('academic_year_id', $this->academic_year_id)
                        ->where('is_active', true)
                        ->count();

                    if ($currentEnrollments >= $classroom->capacity) {
                        $validator->errors()->add('classroom_id', 'Classroom has reached its maximum capacity.');
                    }
                }
            }

            // Validate enrollment date is within academic year
            if ($this->enrolled_at && $this->academic_year_id) {
                $academicYear = \Modules\Academic\Models\AcademicYear::find($this->academic_year_id);
                if ($academicYear) {
                    $enrolledDate = \Carbon\Carbon::parse($this->enrolled_at);
                    $startDate = \Carbon\Carbon::parse($academicYear->start_date);
                    $endDate = \Carbon\Carbon::parse($academicYear->end_date);

                    if ($enrolledDate->lt($startDate) || $enrolledDate->gt($endDate)) {
                        $validator->errors()->add('enrolled_at', 'Enrollment date must be within the academic year period.');
                    }
                }
            }
        });
    }

    /**
     * Get custom attributes for validator errors.
     */
    public function attributes(): array
    {
        return [
            'student_id' => 'student',
            'classroom_id' => 'classroom',
            'academic_year_id' => 'academic year',
            'enrolled_at' => 'enrollment date',
        ];
    }

    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation(): void
    {
        // Set default enrollment date to today if not provided
        if (!$this->enrolled_at) {
            $this->merge([
                'enrolled_at' => now()->format('Y-m-d'),
            ]);
        }
    }
}
