<?php

namespace App\Services\Subjects;

use App\Models\SchoolClass;
use App\Models\SubjectCurriculum;
use Illuminate\Support\Facades\DB;

class SubjectCurriculumService
{
    public const SUBJECT_OPTIONS = [
        'islamic' => 'Islamic Studies',
        'quran' => 'Quran/Arabic',
    ];

    public function list(): array
    {
        $classes = SchoolClass::query()
            ->orderBy('class_name')
            ->get()
            ->toArray();

        $entries = DB::table('subject_curriculum_items as sci')
            ->leftJoin('classes', 'classes.id', '=', 'sci.class_id')
            ->select('sci.*', 'classes.class_name')
            ->orderBy('classes.class_name')
            ->orderBy('sci.subject')
            ->orderBy('sci.unit_number')
            ->orderBy('sci.chapter_name')
            ->get()
            ->map(fn ($r) => (array) $r)
            ->all();

        return [
            'classes' => $classes,
            'entries' => $entries,
            'subject_labels' => self::SUBJECT_OPTIONS,
        ];
    }

    public function store(array $payload): SubjectCurriculum
    {
        return SubjectCurriculum::query()->create([
            'class_id' => (int) $payload['class_id'],
            'subject' => (string) $payload['subject'],
            'unit_number' => $payload['unit_number'] !== null ? (int) $payload['unit_number'] : null,
            'unit_title' => $payload['unit_title'] !== '' ? $payload['unit_title'] : null,
            'chapter_name' => (string) $payload['chapter_name'],
        ]);
    }

    public function update(int $id, array $payload): ?SubjectCurriculum
    {
        $entry = SubjectCurriculum::query()->find($id);
        if (!$entry) {
            return null;
        }

        $entry->update([
            'class_id' => (int) $payload['class_id'],
            'subject' => (string) $payload['subject'],
            'unit_number' => $payload['unit_number'] !== null ? (int) $payload['unit_number'] : null,
            'unit_title' => $payload['unit_title'] !== '' ? $payload['unit_title'] : null,
            'chapter_name' => (string) $payload['chapter_name'],
        ]);

        return $entry;
    }

    public function delete(int $id): bool
    {
        $entry = SubjectCurriculum::query()->find($id);
        if (!$entry) {
            return false;
        }

        return (bool) $entry->delete();
    }
}
