<?php

namespace App\Services\Assignment;

use App\Models\StudentClass;
use App\Models\TeacherClass;
use Illuminate\Support\Collection;

class AssignmentDataLoaderService
{
    public function __construct(
        private TeacherClass $teacherClass,
        private StudentClass $studentClass
    ) {}

    public function loadTeacherClasses(?string $schoolYear = null): Collection
    {
        return $this->teacherClass
            ->newQuery()
            ->with([
                'teacher:id,firstname,lastname',
            ])
            ->when(
                filled($schoolYear),
                fn ($q) => $q->where(function ($query) use ($schoolYear) {
                    $query->where('school_year', $schoolYear)
                        ->orWhereNull('school_year')
                        ->orWhere('school_year', '');
                })
            )
            ->get()
            ->map(function ($row) {
                $row->teacher_full_name = trim(
                    ((string) optional($row->teacher)->firstname) . ' ' .
                    ((string) optional($row->teacher)->lastname)
                );

                return $row;
            });
    }

    public function loadStudentClasses(?string $schoolYear = null): Collection
    {
        return $this->studentClass
            ->newQuery()
            ->with([
                'student:id,firstname,lastname,age,gender,registration_grade,photo_consent,tuition_paid,school_id,is_active',
            ])
            ->whereHas('student', fn ($q) => $q->where('is_active', 1))
            ->when(
                filled($schoolYear),
                fn ($q) => $q->where(function ($query) use ($schoolYear) {
                    $query->where('school_year', $schoolYear)
                        ->orWhereNull('school_year')
                        ->orWhere('school_year', '');
                })
            )
            ->get();
    }
}
