<?php
declare(strict_types=1);

namespace App\Modules\PlayerApi\Controllers\Api;

use App\Core\ApiController;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;

final class AttendanceController extends ApiController
{
    public function history(Request $request): Response
    {
        $player = App::getInstance()->currentPlayer();
        $db = App::getInstance()->db();
        $playerId = (int) $player->id;

        $page = max(1, (int) ($request->get('page') ?? 1));
        $perPage = 20;
        $offset = ($page - 1) * $perPage;

        $total = (int) ($db->selectOne(
            "SELECT COUNT(*) as cnt FROM session_attendance WHERE player_id = ?",
            [$playerId]
        )['cnt'] ?? 0);

        $records = $db->select(
            "SELECT sa.status, sa.check_in_time, sa.check_out_time, sa.is_makeup, sa.notes,
                    ts.session_date, ts.start_time, ts.end_time, ts.session_type,
                    tg.name_ar as group_name
             FROM session_attendance sa
             JOIN training_sessions ts ON ts.id = sa.session_id
             JOIN training_groups tg ON tg.id = ts.group_id
             WHERE sa.player_id = ?
             ORDER BY ts.session_date DESC, ts.start_time DESC
             LIMIT ? OFFSET ?",
            [$playerId, $perPage, $offset]
        );

        return $this->paginatedResponse($records, $total, $page, $perPage);
    }

    public function summary(Request $request): Response
    {
        $player = App::getInstance()->currentPlayer();
        $db = App::getInstance()->db();
        $playerId = (int) $player->id;

        $monthStart = date('Y-m-01');
        $monthEnd = date('Y-m-t');

        $stats = $db->selectOne(
            "SELECT
                COUNT(*) as total_sessions,
                SUM(CASE WHEN sa.status = 'present' THEN 1 ELSE 0 END) as present,
                SUM(CASE WHEN sa.status = 'absent' THEN 1 ELSE 0 END) as absent,
                SUM(CASE WHEN sa.status = 'late' THEN 1 ELSE 0 END) as late,
                SUM(CASE WHEN sa.status = 'excused' THEN 1 ELSE 0 END) as excused
             FROM session_attendance sa
             JOIN training_sessions ts ON ts.id = sa.session_id
             WHERE sa.player_id = ? AND ts.session_date BETWEEN ? AND ?",
            [$playerId, $monthStart, $monthEnd]
        );

        $totalSessions = (int) ($stats['total_sessions'] ?? 0);
        $present = (int) ($stats['present'] ?? 0);
        $late = (int) ($stats['late'] ?? 0);
        $rate = $totalSessions > 0 ? round(($present + $late) / $totalSessions * 100, 1) : 0;

        return $this->successResponse([
            'month' => date('Y-m'),
            'total_sessions' => $totalSessions,
            'present' => $present,
            'absent' => (int) ($stats['absent'] ?? 0),
            'late' => $late,
            'excused' => (int) ($stats['excused'] ?? 0),
            'attendance_rate' => $rate,
        ]);
    }
}
