<?php

namespace App\Http\Requests\Admin\Manage;

use App\Services\Admin\Manage\CourseRegistrationService;
use App\Services\Admin\Master\AcademicTermService;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class CourseRegistrationRequest extends FormRequest
{
    public function authorize(): bool
    {
        if (! $this->routeIs('student.*')) {
            return $this->user()->can('create-course-registrations');
        }

        $student = $this->user()->student;

        if (! $student) {
            return false;
        }

        $term = app(AcademicTermService::class)->getActive();

        if (! $term) {
            return false;
        }

        $service = app(CourseRegistrationService::class);
        $submission = $service->currentSubmission($student, $term);

        if (! $service->canSubmit($submission)) {
            return false;
        }

        return $service->paymentStatus($student, $term)['is_paid'];
    }

    public function rules(): array
    {
        if ($this->routeIs('student.*')) {
            $student = $this->user()->student;
            $term = app(AcademicTermService::class)->getActive();
            $allowedIds = $student && $term
                ? app(CourseRegistrationService::class)->allowedCourseClassIds($student, $term)
                : [];

            return [
                'course_class_ids' => ['required', 'array', 'min:1'],
                'course_class_ids.*' => ['integer', Rule::in($allowedIds)],
                'signature' => ['required', 'image', 'max:2048'],
            ];
        }

        return [
            'student_id' => ['required', 'integer', Rule::exists('students', 'id')],
            'academic_term_id' => ['required', 'integer', Rule::exists('academic_terms', 'id')],
            'course_class_ids' => ['required', 'array', 'min:1'],
            'course_class_ids.*' => [
                'integer',
                Rule::exists('course_classes', 'id'),
                Rule::unique('course_registrations', 'course_class_id')
                    ->where('student_id', $this->input('student_id')),
            ],
        ];
    }

    public function attributes(): array
    {
        return [
            'course_class_ids' => 'mata kuliah',
        ];
    }
}
