<?php

namespace Modules\Academic\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        $academicYear = $this->route('academic_year');

        return [
            'name' => [
                'required',
                'string',
                'max:255',
                'unique:academic_years,name,' . $academicYear->id
            ],
            'start_date' => [
                'required',
                'date'
            ],
            'end_date' => [
                'required',
                'date',
                'after:start_date'
            ],
            'is_active' => [
                'boolean'
            ],
        ];
    }

    /**
     * Get custom validation messages.
     */
    public function messages(): array
    {
        return [
            'name.required' => 'Please enter the academic year name.',
            'name.unique' => 'An academic year with this name already exists.',
            'start_date.required' => 'Please select the start date.',
            'end_date.required' => 'Please select the end date.',
            'end_date.after' => 'End date must be after the start date.',
        ];
    }

    /**
     * Configure the validator instance.
     */
    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            $academicYear = $this->route('academic_year');

            // Check if the date range overlaps with other academic years
            if ($this->start_date && $this->end_date) {
                $overlapping = \Modules\Academic\Models\AcademicYear::where('id', '!=', $academicYear->id)
                    ->where(function ($query) {
                        $query->whereBetween('start_date', [$this->start_date, $this->end_date])
                              ->orWhereBetween('end_date', [$this->start_date, $this->end_date])
                              ->orWhere(function ($q) {
                                  $q->where('start_date', '<=', $this->start_date)
                                    ->where('end_date', '>=', $this->end_date);
                              });
                    })->exists();

                if ($overlapping) {
                    $validator->errors()->add('start_date', 'The date range overlaps with another academic year.');
                }
            }

            // Validate academic year duration
            if ($this->start_date && $this->end_date) {
                $startDate = \Carbon\Carbon::parse($this->start_date);
                $endDate = \Carbon\Carbon::parse($this->end_date);
                $monthsDiff = $startDate->diffInMonths($endDate);

                if ($monthsDiff < 6) {
                    $validator->errors()->add('end_date', 'Academic year should be at least 6 months long.');
                }

                if ($monthsDiff > 18) {
                    $validator->errors()->add('end_date', 'Academic year should not exceed 18 months.');
                }
            }

            // Check if academic year has active enrollments when changing dates
            if ($this->start_date !== $academicYear->start_date || $this->end_date !== $academicYear->end_date) {
                $hasActiveEnrollments = \Illuminate\Support\Facades\DB::table('enrollments')
                    ->join('classrooms', 'enrollments.classroom_id', '=', 'classrooms.id')
                    ->where('classrooms.academic_year_id', $academicYear->id)
                    ->where('enrollments.is_active', true)
                    ->exists();

                if ($hasActiveEnrollments) {
                    $validator->errors()->add('start_date', 'Cannot change dates for academic year with active enrollments.');
                }
            }
        });
    }
}
