<?php

namespace App\Modules\Dashboard\Controllers;

use App\Core\BaseApiController;
use App\Modules\Auth\Services\AuthService;
use App\Modules\Dashboard\Services\DashboardScheduleService;
use App\Modules\Attendance\Entities\AttendanceSession;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Dashboard Attendance API (e.g. live progress for current lesson).
 */
class DashboardAttendanceController extends BaseApiController
{
    /**
     * GET /api/dashboard/attendance/progress/current
     *
     * Returns live attendance progress for the current schedule (if any).
     * expected_total = students in class; present/late from attendance_sessions today; absent = expected - (present + late).
     */
    public function progressCurrent(): ResponseInterface
    {
        $authService = new AuthService();
        $userContext = $authService->currentUser();
        $scheduleService = new DashboardScheduleService();

        $current = $scheduleService->getCurrentSchedule($userContext);

        if (empty($current['is_active_now']) || empty($current['schedule_id'])) {
            return $this->successResponse(['active' => false], 'No active schedule');
        }

        $scheduleId = (int) $current['schedule_id'];
        $classId    = (int) ($current['class_id'] ?? 0);
        $tz         = new \DateTimeZone('Asia/Jakarta');
        $today      = (new \DateTimeImmutable('now', $tz))->format('Y-m-d');

        $db = \Config\Database::connect();

        $expectedTotal = 0;
        if ($classId > 0) {
            $expectedTotal = $db->table('students')->where('class_id', $classId)->countAllResults();
        }

        $presentTotal = $db->table('attendance_sessions')
            ->where('schedule_id', $scheduleId)
            ->where('attendance_date', $today)
            ->where('status', AttendanceSession::STATUS_PRESENT)
            ->countAllResults();

        $lateTotal = $db->table('attendance_sessions')
            ->where('schedule_id', $scheduleId)
            ->where('attendance_date', $today)
            ->where('status', AttendanceSession::STATUS_LATE)
            ->countAllResults();

        $absentTotal = $expectedTotal - ($presentTotal + $lateTotal);
        if ($absentTotal < 0) {
            $absentTotal = 0;
        }

        $data = [
            'active'          => true,
            'subject_name'    => (string) ($current['subject_name'] ?? '-'),
            'class_name'      => (string) ($current['class_name'] ?? '-'),
            'expected_total'  => $expectedTotal,
            'present_total'   => $presentTotal,
            'late_total'      => $lateTotal,
            'absent_total'    => $absentTotal,
        ];

        return $this->successResponse($data, 'Attendance progress');
    }
}
