<?php

namespace App\Http\Requests\Admin;

use App\Models\MathChapter;
use Illuminate\Foundation\Http\FormRequest;

class StoreMathChapterRequest extends FormRequest
{
    public function authorize(): bool
    {
        return auth()->check();
    }

    public function rules(): array
    {
        return [
            'classgroup' => ['required', 'string', 'max:255'],
            'subject' => ['required', 'string', 'max:255'],
            'chaptername' => ['required', 'string', 'max:250'],
            'chapterorder' => ['nullable', 'integer', 'min:0', 'max:999'],
        ];
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            [$groupId] = $this->parseClassGroup();
            [$subjectId] = $this->parseSubject();

            if ($groupId <= 0) {
                $validator->errors()->add('classgroup', 'Please select a valid class group.');

                return;
            }

            if ($subjectId <= 0) {
                $validator->errors()->add('subject', 'Please select a valid subject.');

                return;
            }

            $exists = MathChapter::query()
                ->where('classgroupid', $groupId)
                ->where('subjectid', $subjectId)
                ->whereRaw('LOWER(chaptername) = ?', [strtolower(trim((string) $this->input('chaptername')))])
                ->exists();

            if ($exists) {
                $validator->errors()->add('chaptername', 'This chapter already exists for the selected subject and class group.');
            }
        });
    }

    private function parseClassGroup(): array
    {
        $value = (string) $this->input('classgroup', '');

        if (! str_contains($value, '<=>')) {
            return [0, ''];
        }

        [$id, $name] = explode('<=>', $value, 2);

        return [is_numeric($id) ? (int) $id : 0, $name];
    }

    private function parseSubject(): array
    {
        $value = (string) $this->input('subject', '');

        if (! str_contains($value, '<=>')) {
            return [0, ''];
        }

        [$id, $name] = explode('<=>', $value, 2);

        return [is_numeric($id) ? (int) $id : 0, $name];
    }
}
