<?php

namespace App\Services;

use App\Models\Subject;
use App\Models\SubjectAlias;
use Illuminate\Database\Eloquent\Collection;

class SubjectService
{
    public function getAllSubjects()
    {
        return Subject::orderBy('name')->get();
    }

    public function createSubject(array $data): Subject
    {
        return Subject::create($data);
    }

    public function updateSubject(Subject $subject, array $data): Subject
    {
        $subject->update($data);
        return $subject;
    }

    public function deleteSubject(Subject $subject): bool
    {
        return $subject->delete();
    }

    public function attachSubjectToClass(Subject $subject, int $schoolClassId, ?string $alias = null): void
    {
        SubjectAlias::updateOrCreate(
            ['subject_id' => $subject->id, 'school_class_id' => $schoolClassId],
            ['alias' => $alias]
        );
    }

    public function removeAliasFromClass(Subject $subject, int $schoolClassId): void
    {
        SubjectAlias::where('subject_id', $subject->id)
                   ->where('school_class_id', $schoolClassId)
                   ->update(['alias' => null]);
    }
    
    public function updateAliasForClass(Subject $subject, int $schoolClassId, ?string $alias = null): void
    {
        SubjectAlias::where('subject_id', $subject->id)
                   ->where('school_class_id', $schoolClassId)
                   ->update(['alias' => $alias]);
    }

    public function detachSubjectFromClass(Subject $subject, int $schoolClassId): void
    {
        $subject->schoolClasses()->detach($schoolClassId);
    }

    public function getSubjectsForClass(int $schoolClassId): Collection
    {
        return Subject::whereHas('schoolClasses', function ($query) use ($schoolClassId) {
            $query->where('school_class_id', $schoolClassId);
        })->with(['schoolClasses' => function ($query) use ($schoolClassId) {
            $query->where('school_class_id', $schoolClassId);
        }])->get();
    }
}