<?php
declare(strict_types=1);

namespace App\Modules\Sessions\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Sessions\Models\SessionAttendance;
use App\Modules\Sessions\Services\SessionManagementService;

class SessionAttendanceController extends Controller
{
    public function form(Request $request, string $id): Response
    {
        $this->authorize('session.attendance');

        $db = App::getInstance()->db();

        $session = $db->selectOne(
            "SELECT ts.*,
                    tg.name_ar AS group_name,
                    a.name_ar AS academy_name,
                    c.full_name_ar AS coach_name
             FROM training_sessions ts
             LEFT JOIN training_groups tg ON tg.id = ts.group_id
             LEFT JOIN academies a ON a.id = ts.academy_id
             LEFT JOIN coaches c ON c.id = ts.coach_id
             WHERE ts.id = ?",
            [(int) $id]
        );

        if (!$session) {
            return $this->redirect('/sessions')->withError('الحصة غير موجودة');
        }

        if ($session['status'] === 'cancelled') {
            return $this->redirect('/sessions/' . $id)->withError('لا يمكن تسجيل حضور لحصة ملغاة');
        }

        // Get players from group memberships
        $players = $db->select(
            "SELECT gm.player_id, gm.enrollment_id, p.full_name_ar AS player_name, p.phone
             FROM group_memberships gm
             LEFT JOIN players p ON p.id = gm.player_id
             WHERE gm.group_id = ? AND gm.status = 'active'
             ORDER BY p.full_name_ar ASC",
            [(int) $session['group_id']]
        );

        // Get existing attendance records for this session
        $existingAttendance = $db->select(
            "SELECT player_id, status, check_in_time FROM session_attendance WHERE session_id = ?",
            [(int) $id]
        );

        $attendanceMap = [];
        foreach ($existingAttendance as $att) {
            $attendanceMap[(int) $att['player_id']] = $att;
        }

        return $this->view('Sessions.Views.attendance', [
            'session'        => $session,
            'players'        => $players,
            'attendanceMap'  => $attendanceMap,
            'statuses'       => SessionAttendance::getStatuses(),
        ]);
    }

    public function save(Request $request, string $id): Response
    {
        $this->authorize('session.attendance');

        $db = App::getInstance()->db();

        $session = $db->selectOne(
            "SELECT id, status, group_id FROM training_sessions WHERE id = ?",
            [(int) $id]
        );

        if (!$session) {
            return $this->redirect('/sessions')->withError('الحصة غير موجودة');
        }

        if ($session['status'] === 'cancelled') {
            return $this->redirect('/sessions/' . $id)->withError('لا يمكن تسجيل حضور لحصة ملغاة');
        }

        // Update session status to in_progress if it was scheduled
        if ($session['status'] === 'scheduled') {
            $db->update('training_sessions', [
                'status' => 'in_progress',
            ], 'id = ?', [(int) $id]);
        }

        // Build attendance data from POST
        $playerIds = $request->post('player_ids', []);
        $statuses = $request->post('statuses', []);
        $checkInTimes = $request->post('check_in_times', []);
        $enrollmentIds = $request->post('enrollment_ids', []);

        if (!is_array($playerIds)) {
            return $this->redirect('/sessions/' . $id . '/attendance')->withError('بيانات غير صالحة');
        }

        $attendanceData = [];
        foreach ($playerIds as $index => $playerId) {
            $attendanceData[] = [
                'player_id'     => (int) $playerId,
                'status'        => $statuses[$index] ?? 'present',
                'check_in_time' => !empty($checkInTimes[$index]) ? $checkInTimes[$index] : null,
                'enrollment_id' => !empty($enrollmentIds[$index]) ? (int) $enrollmentIds[$index] : null,
            ];
        }

        SessionManagementService::recordAttendance((int) $id, $attendanceData);

        return $this->redirect('/sessions/' . $id)->withSuccess('تم تسجيل الحضور بنجاح');
    }
}
