<?php

namespace App\Http\Requests\Admin\Manage;

use App\Models\AcademicTerm;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;

class DuplicateCourseClassesRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('create-course-classes');
    }

    public function rules(): array
    {
        return [
            'source_academic_term_id' => ['required', 'integer', Rule::exists('academic_terms', 'id')],
            'target_academic_term_id' => ['required', 'integer', Rule::exists('academic_terms', 'id')],
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            if ($this->input('source_academic_term_id') === $this->input('target_academic_term_id')) {
                $validator->errors()->add('target_academic_term_id', 'Periode tujuan harus berbeda dari periode sumber.');

                return;
            }

            $sourceTerm = AcademicTerm::find($this->input('source_academic_term_id'));
            $targetTerm = AcademicTerm::find($this->input('target_academic_term_id'));

            if ($sourceTerm && $targetTerm && $sourceTerm->semester !== $targetTerm->semester) {
                $validator->errors()->add('target_academic_term_id', 'Periode tujuan harus semester yang sama dengan periode sumber (Ganjil ke Ganjil, Genap ke Genap).');
            }
        });
    }
}
