<?php

namespace App\Services\Parents;

use Illuminate\Support\Facades\DB;

class ParentAttendanceService
{
    public function __construct(private ParentConfigService $configService)
    {
    }

    public function listAttendance(int $parentId, ?string $schoolYear = null): array
    {
        $context = $this->configService->context();
        $selectedYear = $schoolYear ?: $context['school_year'];

        $rows = DB::table('attendance_data')
            ->select('students.firstname', 'students.lastname', 'attendance_data.date', 'attendance_data.status', 'attendance_data.reason')
            ->join('students', 'students.id', '=', 'attendance_data.student_id')
            ->where('students.parent_id', $parentId)
            ->where('attendance_data.school_year', $selectedYear)
            ->orderBy('attendance_data.date', 'desc')
            ->get()
            ->map(fn ($row) => (array) $row)
            ->all();

        $schoolYears = DB::table('attendance_data')
            ->select('school_year')
            ->distinct()
            ->orderBy('school_year', 'desc')
            ->get()
            ->map(fn ($row) => (array) $row)
            ->all();

        return [
            'attendance' => $rows,
            'schoolYears' => $schoolYears,
            'selectedYear' => $selectedYear,
        ];
    }
}
