<?php
declare(strict_types=1);

namespace App\Modules\PlayerAffairs\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;

class AttendanceController extends Controller
{
    public function index(Request $request): Response
    {
        $db = App::getInstance()->db();

        $academyId = (int) $request->get('academy_id', 0);
        $date = trim((string) $request->get('date', date('Y-m-d')));

        // Get all active academies for the dropdown
        $academies = $db->select(
            "SELECT a.id, a.name_ar, sd.name_ar AS discipline_name
             FROM academies a
             JOIN sport_disciplines sd ON sd.id = a.discipline_id
             WHERE a.is_active = 1
             ORDER BY a.name_ar"
        );

        $players = [];
        $existingAttendance = [];

        if ($academyId > 0) {
            // Get active players enrolled in this academy
            $players = $db->select("
                SELECT ae.id AS enrollment_id, ae.player_id,
                       p.full_name_ar, p.activity_id_number, p.card_status
                FROM academy_enrollments ae
                JOIN players p ON p.id = ae.player_id AND p.is_archived = 0
                WHERE ae.academy_id = ? AND ae.status = 'active'
                ORDER BY p.full_name_ar
            ", [$academyId]);

            // Get existing attendance records for this date and academy's players
            if (!empty($players)) {
                $playerIds = array_map(fn($p) => (int) $p['player_id'], $players);
                $placeholders = implode(',', array_fill(0, count($playerIds), '?'));
                $rows = $db->select(
                    "SELECT player_id, status, notes FROM player_attendance
                     WHERE attendance_date = ? AND player_id IN ({$placeholders})",
                    array_merge([$date], $playerIds)
                );
                foreach ($rows as $row) {
                    $existingAttendance[(int) $row['player_id']] = $row;
                }
            }
        }

        // Attendance summary for this academy/date
        $summary = null;
        if ($academyId > 0 && !empty($existingAttendance)) {
            $summary = ['present' => 0, 'absent' => 0, 'late' => 0, 'excused' => 0];
            foreach ($existingAttendance as $att) {
                $s = $att['status'] ?? 'present';
                if (isset($summary[$s])) $summary[$s]++;
            }
        }

        return $this->view('PlayerAffairs.Views.attendance', [
            'academies'          => $academies,
            'selectedAcademyId'  => $academyId,
            'selectedDate'       => $date,
            'players'            => $players,
            'existingAttendance' => $existingAttendance,
            'summary'            => $summary,
        ]);
    }

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

        $academyId = (int) $request->post('academy_id', 0);
        $date = trim((string) $request->post('date', date('Y-m-d')));
        $statuses = (array) ($request->post('status') ?? []);
        $notes = (array) ($request->post('notes') ?? []);

        if ($academyId <= 0 || empty($statuses)) {
            return $this->redirect('/attendance?academy_id=' . $academyId . '&date=' . $date)
                ->withError('بيانات غير صالحة');
        }

        $validStatuses = ['present', 'absent', 'late', 'excused'];
        $ts = date('Y-m-d H:i:s');
        $recorded = 0;

        // Get enrollment_id mapping for this academy
        $enrollments = $db->select(
            "SELECT id AS enrollment_id, player_id FROM academy_enrollments WHERE academy_id = ? AND status = 'active'",
            [$academyId]
        );
        $enrollmentMap = [];
        foreach ($enrollments as $e) {
            $enrollmentMap[(int) $e['player_id']] = (int) $e['enrollment_id'];
        }

        foreach ($statuses as $playerId => $status) {
            $playerId = (int) $playerId;
            $status = trim((string) $status);
            if (!in_array($status, $validStatuses)) continue;

            $enrollmentId = $enrollmentMap[$playerId] ?? null;
            $note = trim((string) ($notes[$playerId] ?? ''));

            // Upsert: delete existing then insert
            $db->delete('player_attendance', 'player_id = ? AND attendance_date = ? AND enrollment_id = ?', [
                $playerId, $date, $enrollmentId
            ]);

            $db->insert('player_attendance', [
                'player_id'       => $playerId,
                'enrollment_id'   => $enrollmentId,
                'attendance_date' => $date,
                'status'          => $status,
                'notes'           => $note ?: null,
                'created_at'      => $ts,
                'updated_at'      => $ts,
                'created_by'      => $employee ? (int) $employee->id : null,
            ]);
            $recorded++;
        }

        return $this->redirect('/attendance?academy_id=' . $academyId . '&date=' . $date)
            ->withSuccess('تم تسجيل الحضور بنجاح (' . $recorded . ' لاعب)');
    }
}
