<?php

namespace App\Http\Requests\ClassProgress;

use App\Http\Requests\ClassProgress\ClassProgressFormRequest;

class ClassProgressStoreRequest extends ClassProgressFormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        $rules = [
            'class_section_id' => ['required', 'integer', 'exists:classSection,class_section_id'],
            'school_year' => ['nullable', 'string', 'max:20'],
            'semester' => ['nullable', 'string', 'max:20'],
            'week_start' => ['required', 'date_format:Y-m-d'],
            'week_end' => ['nullable', 'date_format:Y-m-d'],
            'support_needed' => ['nullable', 'string'],
            'flags' => ['nullable', 'array'],
            'confirm_overwrite' => ['nullable', 'boolean'],
        ];

        $sections = (array) config('progress.subject_sections', []);
        $maxFileKb = (int) config('progress.attachments.max_kb', 5120);
        $mimes = (array) config('progress.attachments.mimes', ['pdf', 'jpg', 'jpeg', 'png']);
        $mimeRule = 'mimes:' . implode(',', $mimes);

        foreach ($sections as $slug => $section) {
            $rules["covered_{$slug}"] = ['nullable', 'string'];
            $rules["homework_{$slug}"] = ['nullable', 'string'];
            $rules["unit_{$slug}"] = ['nullable', 'array'];
            $rules["unit_{$slug}.*"] = ['nullable', 'string', 'max:120'];
            $rules["chapter_{$slug}"] = ['nullable', 'array'];
            $rules["chapter_{$slug}.*"] = ['nullable', 'string', 'max:120'];
            $rules["attachment_{$slug}"] = ['nullable', 'array'];
            $rules["attachment_{$slug}.*"] = ['nullable', 'file', $mimeRule, 'max:' . $maxFileKb];
        }

        return $rules;
    }

    public function filesBySubject(): array
    {
        $sections = (array) config('progress.subject_sections', []);
        $filesBySubject = [];

        foreach ($sections as $slug => $section) {
            $filesBySubject[$slug] = $this->file("attachment_{$slug}") ?? [];
        }

        return $filesBySubject;
    }
}
