<?php

namespace Modules\Results\Http\Requests;

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

class StoreResultRequest 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' => [
                'required',
                'integer',
                'exists:students,id'
            ],
            'subject_id' => [
                'required',
                'integer',
                'exists:subjects,id'
            ],
            'classroom_id' => [
                'required',
                'integer',
                'exists:classrooms,id'
            ],
            'academic_year_id' => [
                'required',
                'integer',
                'exists:academic_years,id'
            ],
            'exam_type_id' => [
                'required',
                'integer',
                'exists:exam_types,id'
            ],
            'marks' => [
                'required',
                'integer',
                'min:0',
                'max:100'
            ],
            'grade' => [
                'nullable',
                'string',
                'max:5'
            ],
            'points' => [
                'nullable',
                'integer',
                'min:0',
                'max:12'
            ],
        ];
    }

    /**
     * Get custom validation messages.
     */
    public function messages(): array
    {
        return [
            'student_id.required' => 'Please select a student.',
            'student_id.exists' => 'The selected student does not exist.',
            'subject_id.required' => 'Please select a subject.',
            'subject_id.exists' => 'The selected subject does not exist.',
            'classroom_id.required' => 'Please select a classroom.',
            'classroom_id.exists' => 'The selected classroom does not exist.',
            'academic_year_id.required' => 'Please select an academic year.',
            'academic_year_id.exists' => 'The selected academic year does not exist.',
            'exam_type_id.required' => 'Please select an exam type.',
            'exam_type_id.exists' => 'The selected exam type does not exist.',
            'marks.required' => 'Please enter the marks.',
            'marks.integer' => 'Marks must be a whole number.',
            'marks.min' => 'Marks cannot be less than 0.',
            'marks.max' => 'Marks cannot be more than 100.',
        ];
    }

    /**
     * Configure the validator instance.
     */
    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            // Check if the student is enrolled in the classroom for the academic year
            if ($this->student_id && $this->classroom_id && $this->academic_year_id) {
                $enrollment = \Modules\Enrollment\Models\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)
                    ->exists();

                if (!$enrollment) {
                    $validator->errors()->add('student_id', 'The student is not enrolled in the selected classroom for this academic year.');
                }
            }

            // Check if the subject is assigned to the classroom
            if ($this->subject_id && $this->classroom_id) {
                $subjectAssigned = \Illuminate\Support\Facades\DB::table('classroom_subjects')
                    ->where('classroom_id', $this->classroom_id)
                    ->where('subject_id', $this->subject_id)
                    ->exists();

                if (!$subjectAssigned) {
                    $validator->errors()->add('subject_id', 'The subject is not assigned to the selected classroom.');
                }
            }

            // Check if exam type belongs to the academic year
            if ($this->exam_type_id && $this->academic_year_id) {
                $examTypeValid = \Modules\Academic\Models\ExamType::where('id', $this->exam_type_id)
                    ->where('academic_year_id', $this->academic_year_id)
                    ->where('is_active', true)
                    ->exists();

                if (!$examTypeValid) {
                    $validator->errors()->add('exam_type_id', 'The exam type does not belong to the selected academic year.');
                }
            }

            // For teachers, check if they can enter results for this subject in this classroom
            if ($this->user()->hasRole('teacher')) {
                $canEnterResult = \Illuminate\Support\Facades\DB::table('classroom_subjects')
                    ->where('classroom_id', $this->classroom_id)
                    ->where('subject_id', $this->subject_id)
                    ->where('teacher_id', $this->user()->id)
                    ->exists();

                if (!$canEnterResult) {
                    $validator->errors()->add('subject_id', 'You are not authorized to enter results for this subject in this classroom.');
                }
            }
        });
    }
}
