<?php

namespace App\Services\ClassPrep;

use App\Models\Configuration;
use Illuminate\Support\Facades\DB;

class ClassRosterService
{
    public function listStudentsByClass(int $classSectionId, ?string $schoolYear = null): array
    {
        $schoolYear = $schoolYear && trim($schoolYear) !== ''
            ? $schoolYear
            : (string) Configuration::getConfig('school_year');

        return DB::table('students')
            ->select(
                'students.id',
                'students.firstname',
                'students.lastname',
                'students.gender',
                'cs.class_section_name AS registration_grade'
            )
            ->join('student_class as sc', 'sc.student_id', '=', 'students.id')
            ->join('classSection as cs', 'cs.class_section_id', '=', 'sc.class_section_id')
            ->where('sc.school_year', $schoolYear)
            ->where('sc.class_section_id', $classSectionId)
            ->groupBy(
                'students.id',
                'students.firstname',
                'students.lastname',
                'students.gender',
                'cs.class_section_name'
            )
            ->orderBy('students.firstname', 'ASC')
            ->orderBy('students.lastname', 'ASC')
            ->limit(1000)
            ->get()
            ->map(fn ($row) => (array) $row)
            ->toArray();
    }
}
