<?php
declare(strict_types=1);

namespace App\Modules\TrainerPortal\Controllers\Api;

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

final class AttendanceController extends ApiController
{
    public function show(Request $request, int $sessionId): Response
    {
        $coach = App::getInstance()->currentCoach();
        $db = App::getInstance()->db();

        $session = $db->selectOne(
            "SELECT ts.*, tg.name_ar as group_name
             FROM training_sessions ts
             JOIN training_groups tg ON tg.id = ts.group_id
             WHERE ts.id = ? AND ts.coach_id = ?",
            [$sessionId, (int) $coach->id]
        );

        if (!$session) {
            return $this->errorResponse('الحصة غير موجودة أو لا تخصك', 404, [], ApiErrorCodes::NOT_FOUND);
        }

        $attendance = $db->select(
            "SELECT sa.player_id, sa.status, sa.check_in_time, sa.check_out_time, sa.notes,
                    p.full_name_ar as player_name
             FROM session_attendance sa
             JOIN players p ON p.id = sa.player_id
             WHERE sa.session_id = ?
             ORDER BY p.full_name_ar ASC",
            [$sessionId]
        );

        $expectedPlayers = $db->select(
            "SELECT p.id as player_id, p.full_name_ar as player_name
             FROM group_memberships gm
             JOIN players p ON p.id = gm.player_id AND p.is_archived = 0
             WHERE gm.group_id = ? AND gm.status = 'active'
             ORDER BY p.full_name_ar ASC",
            [(int) $session['group_id']]
        );

        return $this->successResponse([
            'session' => [
                'id' => (int) $session['id'],
                'group_name' => $session['group_name'],
                'session_date' => $session['session_date'],
                'start_time' => $session['start_time'],
                'end_time' => $session['end_time'],
                'status' => $session['status'],
            ],
            'expected_players' => $expectedPlayers,
            'attendance' => $attendance,
        ]);
    }

    public function mark(Request $request, int $sessionId): Response
    {
        $coach = App::getInstance()->currentCoach();
        $db = App::getInstance()->db();

        $session = $db->selectOne(
            "SELECT * FROM training_sessions WHERE id = ? AND coach_id = ?",
            [$sessionId, (int) $coach->id]
        );

        if (!$session) {
            return $this->errorResponse('الحصة غير موجودة أو لا تخصك', 404, [], ApiErrorCodes::NOT_FOUND);
        }

        $input = $request->jsonBody();
        $attendanceList = $input['attendance'] ?? [];

        if (!is_array($attendanceList) || empty($attendanceList)) {
            return $this->errorResponse('بيانات الحضور مطلوبة', 422, [], ApiErrorCodes::VALIDATION_FAILED);
        }

        $validStatuses = ['present', 'absent', 'late', 'excused'];
        $marked = 0;
        $attended = 0;

        foreach ($attendanceList as $entry) {
            $playerId = (int) ($entry['player_id'] ?? 0);
            $status = $entry['status'] ?? '';
            $notes = $entry['notes'] ?? null;

            if ($playerId <= 0 || !in_array($status, $validStatuses, true)) {
                continue;
            }

            $existing = $db->selectOne(
                "SELECT id FROM session_attendance WHERE session_id = ? AND player_id = ?",
                [$sessionId, $playerId]
            );

            if ($existing) {
                $db->update('session_attendance', [
                    'status' => $status,
                    'notes' => $notes,
                ], 'id = ?', [(int) $existing['id']]);
            } else {
                $db->insert('session_attendance', [
                    'session_id' => $sessionId,
                    'player_id' => $playerId,
                    'status' => $status,
                    'notes' => $notes,
                    'created_by' => (int) $coach->id,
                    'created_at' => date('Y-m-d H:i:s'),
                ]);
            }

            $marked++;
            if (in_array($status, ['present', 'late'], true)) {
                $attended++;
            }
        }

        $db->update('training_sessions', [
            'players_expected' => $marked,
            'players_attended' => $attended,
            'status' => 'completed',
        ], 'id = ?', [$sessionId]);

        return $this->successResponse([
            'marked' => $marked,
            'attended' => $attended,
        ]);
    }
}
