<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\SportsActivity\Services\TrainingAttendanceService;

class TrainingAttendanceController extends Controller
{
    public function index(Request $request): Response
    {
        $db = App::getInstance()->db();
        $date = trim((string) $request->get('date', date('Y-m-d')));
        $disciplineId = trim((string) $request->get('discipline_id', ''));

        $where = "g.status = 'active' AND g.is_archived = 0";
        $params = [];

        if ($disciplineId !== '') {
            $where .= " AND p.discipline_id = ?";
            $params[] = (int) $disciplineId;
        }

        $dayOfWeek = (int) date('w', strtotime($date));
        $groups = $db->select(
            "SELECT DISTINCT g.id, g.name_ar, g.code, p.name_ar as program_name,
                    d.name_ar as discipline_name, c.full_name_ar as coach_name,
                    gs.start_time, gs.end_time, fu.name_ar as unit_name,
                    g.current_count,
                    (SELECT COUNT(*) FROM sa_training_attendance ta
                     WHERE ta.group_id = g.id AND ta.session_date = ?) as attendance_recorded
             FROM sa_groups g
             JOIN sa_programs p ON p.id = g.program_id
             JOIN sa_disciplines d ON d.id = p.discipline_id
             LEFT JOIN sa_coaches c ON c.id = g.coach_id
             JOIN sa_group_schedule gs ON gs.group_id = g.id AND gs.day_of_week = ? AND gs.is_active = 1
             LEFT JOIN sa_facility_units fu ON fu.id = gs.facility_unit_id
             WHERE {$where}
             ORDER BY gs.start_time ASC, g.name_ar ASC",
            array_merge([$date, $dayOfWeek], $params)
        );

        $disciplines = $db->select(
            "SELECT id, name_ar FROM sa_disciplines WHERE is_archived = 0 AND is_active = 1 ORDER BY name_ar"
        );

        return $this->view('SportsActivity.Views.training-attendance.index', [
            'groups'      => $groups,
            'date'        => $date,
            'disciplines' => $disciplines,
            'filters'     => ['discipline_id' => $disciplineId],
        ]);
    }

    public function record(Request $request, string $groupId): Response
    {
        $db = App::getInstance()->db();
        $date = trim((string) $request->get('date', date('Y-m-d')));

        $group = $db->selectOne(
            "SELECT g.*, p.name_ar as program_name, d.name_ar as discipline_name,
                    c.full_name_ar as coach_name
             FROM sa_groups g
             JOIN sa_programs p ON p.id = g.program_id
             JOIN sa_disciplines d ON d.id = p.discipline_id
             LEFT JOIN sa_coaches c ON c.id = g.coach_id
             WHERE g.id = ?",
            [(int) $groupId]
        );
        if (!$group) {
            return $this->redirect('/sa/training-attendance')->withError('المجموعة غير موجودة');
        }

        $sessions = TrainingAttendanceService::getGroupSessionsForDate((int) $groupId, $date);
        $players = TrainingAttendanceService::getActivePlayers((int) $groupId);
        $existingAttendance = TrainingAttendanceService::getExistingAttendance((int) $groupId, $date);

        return $this->view('SportsActivity.Views.training-attendance.record', [
            'group'              => $group,
            'date'               => $date,
            'sessions'           => $sessions,
            'players'            => $players,
            'existingAttendance' => $existingAttendance,
        ]);
    }

    public function store(Request $request, string $groupId): Response
    {
        $date = trim((string) $request->post('session_date', date('Y-m-d')));
        $playerIds = $request->post('player_ids', []);
        $statuses = $request->post('statuses', []);

        if (!is_array($playerIds) || !is_array($statuses)) {
            return $this->redirect("/sa/training-attendance/record/{$groupId}?date={$date}")
                ->withError('بيانات غير صالحة');
        }

        $attendanceData = [];
        foreach ($playerIds as $i => $pid) {
            $attendanceData[] = [
                'player_id' => (int) $pid,
                'status'    => $statuses[$i] ?? 'absent',
            ];
        }

        $employeeId = (int) (App::getInstance()->session()->get('employee_id') ?? 0);
        $result = TrainingAttendanceService::recordBulk((int) $groupId, $date, $attendanceData, $employeeId);

        if (!$result['success']) {
            return $this->redirect("/sa/training-attendance/record/{$groupId}?date={$date}")
                ->withError($result['error']);
        }

        return $this->redirect("/sa/training-attendance?date={$date}")
            ->withSuccess("تم تسجيل حضور {$result['recorded']} لاعب بنجاح");
    }

    public function report(Request $request): Response
    {
        $db = App::getInstance()->db();

        $groupId = trim((string) $request->get('group_id', ''));
        $playerId = trim((string) $request->get('player_id', ''));
        $dateFrom = trim((string) $request->get('date_from', date('Y-m-01')));
        $dateTo = trim((string) $request->get('date_to', date('Y-m-d')));

        $records = [];
        $summary = null;

        $hasFilter = $groupId !== '' || $playerId !== '';

        if ($hasFilter) {
            $where = "ta.session_date BETWEEN ? AND ?";
            $params = [$dateFrom, $dateTo];

            if ($groupId !== '') {
                $where .= " AND ta.group_id = ?";
                $params[] = (int) $groupId;
            }
            if ($playerId !== '') {
                $where .= " AND ta.player_id = ?";
                $params[] = (int) $playerId;
            }

            $records = $db->select(
                "SELECT ta.*, sp.full_name_ar as player_name, g.name_ar as group_name
                 FROM sa_training_attendance ta
                 JOIN sa_players sp ON sp.id = ta.player_id
                 JOIN sa_groups g ON g.id = ta.group_id
                 WHERE {$where}
                 ORDER BY ta.session_date DESC, sp.full_name_ar ASC
                 LIMIT 500",
                $params
            );

            $summary = $db->selectOne(
                "SELECT
                    COUNT(*) as total,
                    SUM(CASE WHEN ta.status = 'present' THEN 1 ELSE 0 END) as present_count,
                    SUM(CASE WHEN ta.status = 'absent' THEN 1 ELSE 0 END) as absent_count,
                    SUM(CASE WHEN ta.status = 'excused' THEN 1 ELSE 0 END) as excused_count,
                    SUM(CASE WHEN ta.status = 'late' THEN 1 ELSE 0 END) as late_count,
                    SUM(CASE WHEN ta.status = 'makeup' THEN 1 ELSE 0 END) as makeup_count
                 FROM sa_training_attendance ta WHERE {$where}",
                $params
            );
        }

        $groups = $db->select(
            "SELECT id, name_ar FROM sa_groups WHERE status = 'active' AND is_archived = 0 ORDER BY name_ar"
        );

        return $this->view('SportsActivity.Views.training-attendance.report', [
            'records'  => $records,
            'summary'  => $summary,
            'groups'   => $groups,
            'filters'  => [
                'group_id'  => $groupId,
                'player_id' => $playerId,
                'date_from' => $dateFrom,
                'date_to'   => $dateTo,
            ],
        ]);
    }
}
