<?php

namespace App\Services\Admin\AcademicClasses;

use App\Enums\AttendanceStatus;
use App\Models\Attendance;
use App\Models\CourseClass;
use Illuminate\Database\Eloquent\Collection;

class AttendanceService
{
    public function sessions(): Collection
    {
        return Attendance::query()
            ->select(['course_class_id', 'meeting_number', 'date'])
            ->selectRaw('COUNT(*) as total_count')
            ->selectRaw("SUM(CASE WHEN status = 'present' THEN 1 ELSE 0 END) as present_count")
            ->with('courseClass.course:id,code,name')
            ->groupBy('course_class_id', 'meeting_number', 'date')
            ->orderByDesc('date')
            ->get();
    }

    public function session(CourseClass $courseClass, int $meetingNumber): array
    {
        $existing = Attendance::query()
            ->where('course_class_id', $courseClass->id)
            ->where('meeting_number', $meetingNumber)
            ->get()
            ->keyBy('student_id');

        $roster = $courseClass->enrollments()
            ->with('student.user.profile')
            ->get()
            ->map(function ($enrollment) use ($existing) {
                $attendance = $existing->get($enrollment->student_id);

                return [
                    'student_id' => $enrollment->student_id,
                    'student' => $enrollment->student,
                    'status' => $attendance?->status?->value ?? AttendanceStatus::Absent->value,
                ];
            })
            ->values();

        return [
            'roster' => $roster,
            'date' => $existing->first()?->date?->format('Y-m-d'),
        ];
    }

    public function saveSession(int $courseClassId, int $meetingNumber, string $date, array $records): void
    {
        foreach ($records as $record) {
            Attendance::updateOrCreate(
                [
                    'course_class_id' => $courseClassId,
                    'student_id' => $record['student_id'],
                    'meeting_number' => $meetingNumber,
                ],
                [
                    'date' => $date,
                    'status' => $record['status'],
                    'recorded_at' => now(),
                ],
            );
        }
    }

    public function deleteSession(int $courseClassId, int $meetingNumber): void
    {
        Attendance::query()
            ->where('course_class_id', $courseClassId)
            ->where('meeting_number', $meetingNumber)
            ->delete();
    }
}
