<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| SMI Core Periods
| Premium Admin Attendance Center
|--------------------------------------------------------------------------
| File: public_html/student-gateway/admin/attendance.php
|--------------------------------------------------------------------------
*/

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/admin-auth.php';

$pdo = db();

if (function_exists('requireAdmin')) {
    requireAdmin();

if (isPost()) { requireCsrf(); }
} elseif (function_exists('requireAdminLogin')) {
    requireAdminLogin();
}

$admin = function_exists('currentAdmin') ? currentAdmin($pdo) : null;

/*
|--------------------------------------------------------------------------
| Safe Helpers
|--------------------------------------------------------------------------
*/

if (!function_exists('e')) {
    function e($value): string
    {
        return htmlspecialchars((string)($value ?? ''), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

if (!function_exists('safeOne')) {
    function safeOne(PDO $pdo, string $sql, array $params = []): ?array
    {
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            return $row ?: null;
        } catch (Throwable $e) {
            return null;
        }
    }
}

if (!function_exists('safeAll')) {
    function safeAll(PDO $pdo, string $sql, array $params = []): array
    {
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        } catch (Throwable $e) {
            return [];
        }
    }
}

if (!function_exists('safeCount')) {
    function safeCount(PDO $pdo, string $sql, array $params = []): int
    {
        try {
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            return (int)$stmt->fetchColumn();
        } catch (Throwable $e) {
            return 0;
        }
    }
}

if (!function_exists('tableExists')) {
    function tableExists(PDO $pdo, string $table): bool
    {
        try {
            $stmt = $pdo->prepare("
                SELECT COUNT(*)
                FROM information_schema.TABLES
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = ?
            ");
            $stmt->execute([$table]);
            return (int)$stmt->fetchColumn() > 0;
        } catch (Throwable $e) {
            return false;
        }
    }
}

if (!function_exists('columnExists')) {
    function columnExists(PDO $pdo, string $table, string $column): bool
    {
        try {
            $stmt = $pdo->prepare("
                SELECT COUNT(*)
                FROM information_schema.COLUMNS
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = ?
                  AND COLUMN_NAME = ?
            ");
            $stmt->execute([$table, $column]);
            return (int)$stmt->fetchColumn() > 0;
        } catch (Throwable $e) {
            return false;
        }
    }
}

if (!function_exists('formatDateNice')) {
    function formatDateNice($date): string
    {
        if (empty($date) || $date === '0000-00-00') {
            return 'N/A';
        }

        $time = strtotime((string)$date);
        return $time ? date('M d, Y', $time) : 'N/A';
    }
}

if (!function_exists('formatTimeNice')) {
    function formatTimeNice($time): string
    {
        if (empty($time)) {
            return 'N/A';
        }

        $stamp = strtotime((string)$time);
        return $stamp ? date('h:i A', $stamp) : (string)$time;
    }
}

if (!function_exists('dayName')) {
    function dayName($date): string
    {
        if (empty($date)) {
            return 'N/A';
        }

        $time = strtotime((string)$date);
        return $time ? date('l', $time) : 'N/A';
    }
}

if (!function_exists('generateAttendanceCode')) {
    function generateAttendanceCode(): string
    {
        return 'ATT-' . str_pad((string)random_int(0, 99999), 5, '0', STR_PAD_LEFT);
    }
}

if (!function_exists('generateQrToken')) {
    function generateQrToken(): string
    {
        return bin2hex(random_bytes(32));
    }
}

if (!function_exists('appBaseUrl')) {
    function appBaseUrl(): string
    {
        if (defined('APP_URL')) {
            return rtrim((string)APP_URL, '/');
        }

        return 'https://smi-platform.org/student-gateway';
    }
}

if (!function_exists('statusClass')) {
    function statusClass(string $status): string
    {
        switch ($status) {
            case 'present':
                return 'present';
            case 'late':
                return 'late';
            case 'excused':
                return 'excused';
            case 'absent':
            default:
                return 'absent';
        }
    }
}

if (!function_exists('statusLabel')) {
    function statusLabel(string $status): string
    {
        switch ($status) {
            case 'present':
                return 'Present';
            case 'late':
                return 'Late';
            case 'excused':
                return 'Excused';
            case 'absent':
            default:
                return 'Absent';
        }
    }
}

if (!function_exists('statusIcon')) {
    function statusIcon(string $status): string
    {
        switch ($status) {
            case 'present':
                return '✅';
            case 'late':
                return '⏰';
            case 'excused':
                return '🟡';
            case 'absent':
            default:
                return '❌';
        }
    }
}

if (!function_exists('attendancePoints')) {
    function attendancePoints(string $status): float
    {
        switch ($status) {
            case 'present':
                return 0.50;
            case 'late':
                return 0.25;
            case 'excused':
                return 0.50;
            case 'absent':
            default:
                return 0.00;
        }
    }
}

/*
|--------------------------------------------------------------------------
| Flash
|--------------------------------------------------------------------------
*/

$successMessage = (string)($_SESSION['success'] ?? '');
$errorMessage = (string)($_SESSION['error'] ?? '');

unset($_SESSION['success'], $_SESSION['error']);

function setSuccess(string $message): void
{
    $_SESSION['success'] = $message;
}

function setError(string $message): void
{
    $_SESSION['error'] = $message;
}

/*
|--------------------------------------------------------------------------
| Attendance Rules
|--------------------------------------------------------------------------
*/

$attendanceDurationHours = 2;
$presentWindowMinutes = 10;

$presentPoint = 0.50;
$latePoint = 0.25;
$excusedPoint = 0.50;
$absentPoint = 0.00;

$monthlyAttendanceDays = 20;
$monthlyAttendanceTotal = 10.00;

/*
|--------------------------------------------------------------------------
| Filters
|--------------------------------------------------------------------------
*/

$today = date('Y-m-d');

$selectedDate = trim((string)($_GET['date'] ?? $today));
if ($selectedDate === '') {
    $selectedDate = $today;
}

$selectedCourseId = (int)($_GET['course_id'] ?? 0);
$selectedSessionId = (int)($_GET['session_id'] ?? 0);
$courseSearch = trim((string)($_GET['course_search'] ?? ''));

$currentMonth = (int)date('m', strtotime($selectedDate));
$currentYear = (int)date('Y', strtotime($selectedDate));

/*
|--------------------------------------------------------------------------
| Required Tables
|--------------------------------------------------------------------------
*/

$requiredTables = [
    'core_courses',
    'core_teachers',
    'core_course_students',
    'core_sessions',
    'core_attendance_sessions',
    'core_attendance',
    'students',
];

foreach ($requiredTables as $table) {
    if (!tableExists($pdo, $table)) {
        die('Missing required table: ' . e($table));
    }
}

/*
|--------------------------------------------------------------------------
| Courses For Admin
|--------------------------------------------------------------------------
*/

$courseWhere = "1=1";
$courseParams = [];

if ($courseSearch !== '') {
    $courseWhere .= "
        AND (
            c.title LIKE ?
            OR c.course_code LIKE ?
            OR c.code LIKE ?
            OR c.level LIKE ?
        )
    ";

    $like = $courseSearch . '%';

    $courseParams = [
        $like,
        $like,
        $like,
        $like
    ];
}

$courses = safeAll(
    $pdo,
    "
    SELECT
        c.*,
        t.full_name AS teacher_full_name,
        t.name AS teacher_name,
        t.email AS teacher_email
    FROM core_courses c
    LEFT JOIN core_teachers t
        ON t.id = c.teacher_id
    WHERE $courseWhere
    ORDER BY
        c.id DESC
    ",
    $courseParams
);

/*
|--------------------------------------------------------------------------
| Selected Course
|--------------------------------------------------------------------------
*/

$selectedCourse = null;

if ($selectedCourseId > 0) {
    $selectedCourse = safeOne(
        $pdo,
        "
        SELECT
            c.*,
            t.full_name AS teacher_full_name,
            t.name AS teacher_name,
            t.email AS teacher_email
        FROM core_courses c
        LEFT JOIN core_teachers t
            ON t.id = c.teacher_id
        WHERE c.id = ?
        LIMIT 1
        ",
        [$selectedCourseId]
    );

    if (!$selectedCourse) {
        $selectedCourseId = 0;
    }
}

/*
|--------------------------------------------------------------------------
| POST Actions
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $action = (string)($_POST['action'] ?? '');

    /*
    |--------------------------------------------------------------------------
    | Create / Reset Attendance Session
    |--------------------------------------------------------------------------
    */

    if ($action === 'create_session') {

        try {

            $courseId = (int)($_POST['course_id'] ?? 0);
            $sessionDate = trim((string)($_POST['session_date'] ?? $today));
            $sessionTime = trim((string)($_POST['session_time'] ?? date('H:i')));
            $sessionTitle = trim((string)($_POST['session_title'] ?? ''));

            if ($courseId <= 0) {
                throw new Exception('Please choose a course first.');
            }

            if (strlen($sessionTime) === 5) {
                $sessionTime .= ':00';
            }

            $course = safeOne(
                $pdo,
                "
                SELECT *
                FROM core_courses
                WHERE id = ?
                LIMIT 1
                ",
                [$courseId]
            );

            if (!$course) {
                throw new Exception('Selected course was not found.');
            }

            $teacherId = (int)($course['teacher_id'] ?? 0);

            if ($sessionTitle === '') {
                $sessionTitle = 'Attendance - ' . date('M d, Y', strtotime($sessionDate));
            }

            /*
            |--------------------------------------------------------------------------
            | Find Existing Session Same Course + Date + Time
            |--------------------------------------------------------------------------
            */

            $existingSession = safeOne(
                $pdo,
                "
                SELECT *
                FROM core_sessions
                WHERE course_id = ?
                  AND session_date = ?
                  AND session_time = ?
                LIMIT 1
                ",
                [
                    $courseId,
                    $sessionDate,
                    $sessionTime
                ]
            );

            if ($existingSession) {

                $sessionId = (int)$existingSession['id'];

                $updateColumns = [];
                $updateValues = [];

                if (columnExists($pdo, 'core_sessions', 'title')) {
                    $updateColumns[] = 'title = ?';
                    $updateValues[] = $sessionTitle;
                }

                if (columnExists($pdo, 'core_sessions', 'teacher_id')) {
                    $updateColumns[] = 'teacher_id = ?';
                    $updateValues[] = $teacherId;
                }

                if (columnExists($pdo, 'core_sessions', 'status')) {
                    $updateColumns[] = 'status = ?';
                    $updateValues[] = 'active';
                }

                if (columnExists($pdo, 'core_sessions', 'updated_at')) {
                    $updateColumns[] = 'updated_at = NOW()';
                }

                if ($updateColumns) {
                    $updateValues[] = $sessionId;

                    $stmt = $pdo->prepare("
                        UPDATE core_sessions
                        SET " . implode(', ', $updateColumns) . "
                        WHERE id = ?
                    ");

                    $stmt->execute($updateValues);
                }

            } else {

                $columns = [];
                $values = [];

                $columns[] = 'course_id';
                $values[] = $courseId;

                if (columnExists($pdo, 'core_sessions', 'teacher_id')) {
                    $columns[] = 'teacher_id';
                    $values[] = $teacherId;
                }

                if (columnExists($pdo, 'core_sessions', 'title')) {
                    $columns[] = 'title';
                    $values[] = $sessionTitle;
                }

                if (columnExists($pdo, 'core_sessions', 'session_date')) {
                    $columns[] = 'session_date';
                    $values[] = $sessionDate;
                }

                if (columnExists($pdo, 'core_sessions', 'session_time')) {
                    $columns[] = 'session_time';
                    $values[] = $sessionTime;
                }

                if (columnExists($pdo, 'core_sessions', 'status')) {
                    $columns[] = 'status';
                    $values[] = 'active';
                }

                if (columnExists($pdo, 'core_sessions', 'type')) {
                    $columns[] = 'type';
                    $values[] = 'attendance';
                }

                if (columnExists($pdo, 'core_sessions', 'created_at')) {
                    $columns[] = 'created_at';
                    $values[] = date('Y-m-d H:i:s');
                }

                $placeholders = implode(',', array_fill(0, count($columns), '?'));

                $stmt = $pdo->prepare("
                    INSERT INTO core_sessions (
                        " . implode(',', $columns) . "
                    )
                    VALUES (
                        $placeholders
                    )
                ");

                $stmt->execute($values);

                $sessionId = (int)$pdo->lastInsertId();
            }

            /*
            |--------------------------------------------------------------------------
            | Disable Old Active Codes
            |--------------------------------------------------------------------------
            */

            $pdo->prepare("
                UPDATE core_attendance_sessions
                SET is_active = 0
                WHERE session_id = ?
            ")->execute([$sessionId]);

            /*
            |--------------------------------------------------------------------------
            | Create New ATT-00000 Code + QR Token
            |--------------------------------------------------------------------------
            */

            $attendanceCode = generateAttendanceCode();
            $qrToken = generateQrToken();

            $createdAt = date('Y-m-d H:i:s');

            $expiresAt = date(
                'Y-m-d H:i:s',
                strtotime('+' . $attendanceDurationHours . ' hours')
            );

            $columns = [];
            $values = [];

            $columns[] = 'session_id';
            $values[] = $sessionId;

            if (columnExists($pdo, 'core_attendance_sessions', 'course_id')) {
                $columns[] = 'course_id';
                $values[] = $courseId;
            }

            if (columnExists($pdo, 'core_attendance_sessions', 'teacher_id')) {
                $columns[] = 'teacher_id';
                $values[] = $teacherId;
            }

            $columns[] = 'current_code';
            $values[] = $attendanceCode;

            $columns[] = 'qr_token';
            $values[] = $qrToken;

            $columns[] = 'is_active';
            $values[] = 1;

            if (columnExists($pdo, 'core_attendance_sessions', 'expires_at')) {
                $columns[] = 'expires_at';
                $values[] = $expiresAt;
            }

            if (columnExists($pdo, 'core_attendance_sessions', 'created_at')) {
                $columns[] = 'created_at';
                $values[] = $createdAt;
            }

            $placeholders = implode(',', array_fill(0, count($columns), '?'));

            $stmt = $pdo->prepare("
                INSERT INTO core_attendance_sessions (
                    " . implode(',', $columns) . "
                )
                VALUES (
                    $placeholders
                )
            ");

            $stmt->execute($values);

            setSuccess('Attendance created successfully. Code: ' . $attendanceCode);

            header(
                'Location: attendance.php?date=' .
                urlencode($sessionDate) .
                '&course_id=' .
                (int)$courseId .
                '&session_id=' .
                (int)$sessionId
            );

            exit;

        } catch (Throwable $e) {

            setError('Create Attendance Error: ' . $e->getMessage());

            header('Location: attendance.php');
            exit;
        }
    }

    /*
    |--------------------------------------------------------------------------
    | Manual Attendance Save
    |--------------------------------------------------------------------------
    */

    if ($action === 'manual_attendance') {

        try {

            $sessionId = (int)($_POST['session_id'] ?? 0);
            $studentId = (int)($_POST['student_id'] ?? 0);
            $status = strtolower(trim((string)($_POST['status'] ?? 'absent')));

            if (!in_array($status, ['present', 'late', 'excused', 'absent'], true)) {
                $status = 'absent';
            }

            $session = safeOne(
                $pdo,
                "
                SELECT *
                FROM core_sessions
                WHERE id = ?
                LIMIT 1
                ",
                [$sessionId]
            );

            if (!$session) {
                throw new Exception('Session not found.');
            }

            $courseId = (int)($session['course_id'] ?? 0);

            $enrolled = safeCount(
                $pdo,
                "
                SELECT COUNT(*)
                FROM core_course_students
                WHERE course_id = ?
                  AND student_id = ?
                  AND status IN ('active','approved','enrolled')
                ",
                [
                    $courseId,
                    $studentId
                ]
            );

            if ($enrolled <= 0) {
                throw new Exception('Student is not enrolled in this course.');
            }

            $points = attendancePoints($status);

            $attendanceSession = safeOne(
                $pdo,
                "
                SELECT *
                FROM core_attendance_sessions
                WHERE session_id = ?
                  AND is_active = 1
                ORDER BY id DESC
                LIMIT 1
                ",
                [$sessionId]
            );

            $attendanceSessionId = (int)($attendanceSession['id'] ?? 0);

            $existing = safeOne(
                $pdo,
                "
                SELECT *
                FROM core_attendance
                WHERE student_id = ?
                  AND session_id = ?
                LIMIT 1
                ",
                [
                    $studentId,
                    $sessionId
                ]
            );

            if ($existing) {

                $columns = [
                    'status = ?',
                    'points_awarded = ?',
                    'submitted_at = NOW()'
                ];

                $values = [
                    $status,
                    $points
                ];

                if (columnExists($pdo, 'core_attendance', 'attendance_session_id')) {
                    $columns[] = 'attendance_session_id = ?';
                    $values[] = $attendanceSessionId;
                }

                if (columnExists($pdo, 'core_attendance', 'updated_at')) {
                    $columns[] = 'updated_at = NOW()';
                }

                $values[] = (int)$existing['id'];

                $stmt = $pdo->prepare("
                    UPDATE core_attendance
                    SET " . implode(', ', $columns) . "
                    WHERE id = ?
                ");

                $stmt->execute($values);

            } else {

                $columns = [];
                $values = [];

                $columns[] = 'student_id';
                $values[] = $studentId;

                $columns[] = 'course_id';
                $values[] = $courseId;

                $columns[] = 'session_id';
                $values[] = $sessionId;

                if (columnExists($pdo, 'core_attendance', 'attendance_session_id')) {
                    $columns[] = 'attendance_session_id';
                    $values[] = $attendanceSessionId;
                }

                $columns[] = 'status';
                $values[] = $status;

                $columns[] = 'points_awarded';
                $values[] = $points;

                if (columnExists($pdo, 'core_attendance', 'attendance_minutes')) {
                    $columns[] = 'attendance_minutes';
                    $values[] = 0;
                }

                if (columnExists($pdo, 'core_attendance', 'submitted_at')) {
                    $columns[] = 'submitted_at';
                    $values[] = date('Y-m-d H:i:s');
                }

                if (columnExists($pdo, 'core_attendance', 'created_at')) {
                    $columns[] = 'created_at';
                    $values[] = date('Y-m-d H:i:s');
                }

                $placeholders = implode(',', array_fill(0, count($columns), '?'));

                $stmt = $pdo->prepare("
                    INSERT INTO core_attendance (
                        " . implode(',', $columns) . "
                    )
                    VALUES (
                        $placeholders
                    )
                ");

                $stmt->execute($values);
            }

            setSuccess('Student attendance updated successfully.');

            header(
                'Location: attendance.php?date=' .
                urlencode((string)($session['session_date'] ?? $today)) .
                '&course_id=' .
                (int)$courseId .
                '&session_id=' .
                (int)$sessionId .
                '#review-status'
            );

            exit;

        } catch (Throwable $e) {

            setError('Manual Attendance Error: ' . $e->getMessage());
            header('Location: attendance.php');
            exit;
        }
    }
}

/*
|--------------------------------------------------------------------------
| Load Sessions For Selected Date / Course
|--------------------------------------------------------------------------
*/

$where = "
    MONTH(s.session_date) = ?
    AND YEAR(s.session_date) = ?
";

$params = [
    $currentMonth,
    $currentYear
];

if ($selectedDate !== '') {
    $where .= " AND s.session_date = ? ";
    $params[] = $selectedDate;
}

if ($selectedCourseId > 0) {
    $where .= " AND s.course_id = ? ";
    $params[] = $selectedCourseId;
}

$sessions = safeAll(
    $pdo,
    "
    SELECT
        s.*,
        c.title AS course_title,
        c.level AS course_level,
        c.course_code,
        t.full_name AS teacher_full_name,
        t.name AS teacher_name
    FROM core_sessions s
    INNER JOIN core_courses c
        ON c.id = s.course_id
    LEFT JOIN core_teachers t
        ON t.id = c.teacher_id
    WHERE $where
    ORDER BY
        s.session_date DESC,
        s.session_time DESC,
        s.id DESC
    ",
    $params
);

/*
|--------------------------------------------------------------------------
| Selected Session
|--------------------------------------------------------------------------
*/

$selectedSession = null;

if ($selectedSessionId > 0) {
    $selectedSession = safeOne(
        $pdo,
        "
        SELECT
            s.*,
            c.title AS course_title,
            c.level AS course_level,
            c.course_code,
            t.full_name AS teacher_full_name,
            t.name AS teacher_name
        FROM core_sessions s
        INNER JOIN core_courses c
            ON c.id = s.course_id
        LEFT JOIN core_teachers t
            ON t.id = c.teacher_id
        WHERE s.id = ?
        LIMIT 1
        ",
        [$selectedSessionId]
    );
}

/*
|--------------------------------------------------------------------------
| Active Attendance Code
|--------------------------------------------------------------------------
*/

$attendanceSession = null;

if ($selectedSession) {
    $attendanceSession = safeOne(
        $pdo,
        "
        SELECT *
        FROM core_attendance_sessions
        WHERE session_id = ?
          AND is_active = 1
        ORDER BY id DESC
        LIMIT 1
        ",
        [
            (int)$selectedSession['id']
        ]
    );

    if (
        $attendanceSession &&
        !empty($attendanceSession['expires_at']) &&
        strtotime((string)$attendanceSession['expires_at']) < time()
    ) {
        $pdo->prepare("
            UPDATE core_attendance_sessions
            SET is_active = 0
            WHERE id = ?
        ")->execute([
            (int)$attendanceSession['id']
        ]);

        $attendanceSession = null;
    }
}

/*
|--------------------------------------------------------------------------
| QR URL / QR Image
|--------------------------------------------------------------------------
*/

$qrUrl = '';
$qrImage = '';

if ($attendanceSession && $selectedSession) {
    $qrUrl =
        appBaseUrl()
        .
        '/student/submit-attendance.php'
        .
        '?course_id='
        .
        (int)$selectedSession['course_id']
        .
        '&token='
        .
        urlencode(
            (string)(
                $attendanceSession['qr_token']
                ??
                ''
            )
        );

    $qrImage =
        'https://api.qrserver.com/v1/create-qr-code/?size=500x500&data='
        .
        urlencode($qrUrl);
}

/*
|--------------------------------------------------------------------------
| Students For Selected Course
|--------------------------------------------------------------------------
*/

$students = [];

if ($selectedSession) {
    $students = safeAll(
        $pdo,
        "
        SELECT
            s.id,
            s.full_name,
            s.final_level,
            cs.status AS enrollment_status
        FROM core_course_students cs
        INNER JOIN students s
            ON s.id = cs.student_id
        WHERE cs.course_id = ?
          AND cs.status IN ('active','approved','enrolled')
        ORDER BY s.full_name ASC
        ",
        [
            (int)$selectedSession['course_id']
        ]
    );
}

/*
|--------------------------------------------------------------------------
| Daily Attendance Rows
|--------------------------------------------------------------------------
*/

$attendanceRows = [];

if ($selectedSession) {
    $attendanceRows = safeAll(
        $pdo,
        "
        SELECT *
        FROM core_attendance
        WHERE session_id = ?
        ",
        [
            (int)$selectedSession['id']
        ]
    );
}

$attendanceMap = [];

foreach ($attendanceRows as $row) {
    $attendanceMap[(int)$row['student_id']] = $row;
}

/*
|--------------------------------------------------------------------------
| Monthly Attendance Grades
|--------------------------------------------------------------------------
*/

$monthlyRows = [];

if ($selectedSession) {
    $monthlyRows = safeAll(
        $pdo,
        "
        SELECT
            student_id,
            SUM(points_awarded) AS monthly_points,
            COUNT(*) AS records_count,
            SUM(CASE WHEN status = 'present' THEN 1 ELSE 0 END) AS present_count,
            SUM(CASE WHEN status = 'late' THEN 1 ELSE 0 END) AS late_count,
            SUM(CASE WHEN status = 'excused' THEN 1 ELSE 0 END) AS excused_count,
            SUM(CASE WHEN status = 'absent' THEN 1 ELSE 0 END) AS absent_count
        FROM core_attendance
        WHERE course_id = ?
          AND MONTH(submitted_at) = ?
          AND YEAR(submitted_at) = ?
        GROUP BY student_id
        ",
        [
            (int)$selectedSession['course_id'],
            $currentMonth,
            $currentYear
        ]
    );
}

$monthlyMap = [];

foreach ($monthlyRows as $row) {
    $monthlyMap[(int)$row['student_id']] = $row;
}

/*
|--------------------------------------------------------------------------
| Session Summary
|--------------------------------------------------------------------------
*/

$totalStudents = count($students);

$presentCount = 0;
$lateCount = 0;
$excusedCount = 0;
$absentCount = 0;
$totalAttendancePoints = 0.00;

foreach ($students as $student) {
    $studentId = (int)($student['id'] ?? 0);

    $attendance = $attendanceMap[$studentId] ?? null;

    $status = strtolower(
        (string)(
            $attendance['status']
            ??
            'absent'
        )
    );

    $points = (float)(
        $attendance['points_awarded']
        ??
        0
    );

    $totalAttendancePoints += $points;

    if ($status === 'present') {
        $presentCount++;
    } elseif ($status === 'late') {
        $lateCount++;
    } elseif ($status === 'excused') {
        $excusedCount++;
    } else {
        $absentCount++;
    }
}

$attendanceRate = $totalStudents > 0
    ? (int)round((($presentCount + $lateCount + $excusedCount) / $totalStudents) * 100)
    : 0;

$sessionSummary = [
    'total_students' => $totalStudents,
    'present' => $presentCount,
    'late' => $lateCount,
    'excused' => $excusedCount,
    'absent' => $absentCount,
    'attendance_rate' => $attendanceRate,
    'attendance_points' => $totalAttendancePoints,
];

$countdownSeconds = 0;

if (
    $attendanceSession &&
    !empty($attendanceSession['expires_at'])
) {
    $countdownSeconds = max(
        0,
        strtotime((string)$attendanceSession['expires_at']) - time()
    );
}

$pageTitle = 'SMI Core Attendance Center';


?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title><?php echo e($pageTitle); ?></title>

<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">

<style>
:root{
    --blue:#2563eb;
    --blue-dark:#1d4ed8;
    --indigo:#312e81;
    --purple:#7c3aed;
    --green:#059669;
    --orange:#f97316;
    --red:#dc2626;
    --yellow:#ca8a04;
    --text:#0f172a;
    --muted:#64748b;
    --line:#e2e8f0;
    --bg:#f6f8fc;
    --card:#ffffff;
    --shadow:0 24px 70px rgba(15,23,42,.09);
    --soft-shadow:0 12px 35px rgba(15,23,42,.06);
}

*{
    box-sizing:border-box;
    margin:0;
    padding:0;
}

body{
    min-height:100vh;
    font-family:'Inter',sans-serif;
    color:var(--text);
    background:
        radial-gradient(circle at top left,rgba(37,99,235,.14),transparent 30%),
        radial-gradient(circle at top right,rgba(124,58,237,.10),transparent 34%),
        linear-gradient(135deg,#fbfdff,#eef5ff);
}

a{
    text-decoration:none;
    color:inherit;
}

.app{
    width:100%;
    max-width:1720px;
    margin:0 auto;
    padding:18px;
}

.topbar{
    display:flex;
    align-items:flex-start;
    justify-content:space-between;
    gap:18px;
    margin-bottom:18px;
}

.page-title{
    font-size:38px;
    font-weight:900;
    letter-spacing:-1px;
    line-height:1.1;
}

.page-subtitle{
    margin-top:8px;
    max-width:850px;
    color:var(--muted);
    font-size:14px;
    line-height:1.8;
    font-weight:750;
}

.top-actions{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
}

.btn{
    border:0;
    border-radius:16px;
    padding:13px 17px;
    font-family:inherit;
    font-size:13px;
    font-weight:900;
    cursor:pointer;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:8px;
    transition:.22s ease;
    white-space:nowrap;
}

.btn:hover{
    transform:translateY(-2px);
}

.btn-primary{
    color:#fff;
    background:linear-gradient(135deg,var(--blue),var(--blue-dark));
    box-shadow:0 14px 30px rgba(37,99,235,.20);
}

.btn-light{
    color:var(--blue-dark);
    background:#fff;
    border:1px solid #bfdbfe;
}

.btn-danger{
    color:#fff;
    background:linear-gradient(135deg,var(--red),#ef4444);
}

.btn-small{
    padding:10px 12px;
    border-radius:13px;
    font-size:12px;
}

.alert{
    padding:15px 17px;
    border-radius:18px;
    margin-bottom:16px;
    font-size:13px;
    font-weight:850;
    line-height:1.7;
}

.alert-success{
    background:#ecfdf5;
    color:#047857;
    border:1px solid #a7f3d0;
}

.alert-error{
    background:#fef2f2;
    color:#b91c1c;
    border:1px solid #fecaca;
}

.hero{
    position:relative;
    overflow:hidden;
    border-radius:34px;
    padding:28px;
    color:#fff;
    background:
        radial-gradient(circle at 12% 10%,rgba(255,255,255,.18),transparent 28%),
        linear-gradient(135deg,#0f172a,#1d4ed8,#312e81);
    box-shadow:0 30px 75px rgba(37,99,235,.24);
    margin-bottom:18px;
}

.hero::after{
    content:"ATT";
    position:absolute;
    right:24px;
    bottom:-28px;
    font-size:120px;
    font-weight:900;
    letter-spacing:-7px;
    color:rgba(255,255,255,.06);
}

.hero h2{
    position:relative;
    z-index:2;
    font-size:31px;
    font-weight:900;
    margin-bottom:9px;
}

.hero p{
    position:relative;
    z-index:2;
    max-width:850px;
    color:#dbeafe;
    font-size:14px;
    line-height:1.85;
    font-weight:750;
}

.hero-stats{
    position:relative;
    z-index:2;
    display:grid;
    grid-template-columns:repeat(6,1fr);
    gap:12px;
    margin-top:22px;
}

.hero-stat{
    background:rgba(255,255,255,.14);
    border:1px solid rgba(255,255,255,.20);
    border-radius:21px;
    padding:16px;
    backdrop-filter:blur(12px);
}

.hero-stat span{
    display:block;
    color:#bfdbfe;
    font-size:11px;
    font-weight:900;
    margin-bottom:6px;
}

.hero-stat strong{
    display:block;
    font-size:25px;
    font-weight:900;
}

.panel{
    background:#fff;
    border:1px solid var(--line);
    border-radius:28px;
    padding:18px;
    box-shadow:var(--soft-shadow);
    margin-bottom:18px;
}

.panel-head{
    display:flex;
    align-items:flex-end;
    justify-content:space-between;
    gap:16px;
    margin-bottom:15px;
}

.panel-title{
    font-size:20px;
    font-weight:900;
    letter-spacing:-.3px;
}

.panel-subtitle{
    margin-top:5px;
    color:var(--muted);
    font-size:12px;
    font-weight:750;
    line-height:1.7;
}

.grid-filter{
    display:grid;
    grid-template-columns:1.25fr 1fr 1fr auto;
    gap:12px;
}

.grid-create{
    display:grid;
    grid-template-columns:1fr 1.2fr 1fr 1fr auto;
    gap:12px;
}

.input,
.select{
    width:100%;
    min-height:50px;
    border:1px solid #d1d5db;
    border-radius:16px;
    padding:0 14px;
    font-family:inherit;
    font-size:14px;
    font-weight:800;
    background:#fff;
    outline:none;
}

.input:focus,
.select:focus{
    border-color:#2563eb;
    box-shadow:0 0 0 4px rgba(37,99,235,.10);
}

.session-shell{
    display:grid;
    grid-template-columns:1fr;
    gap:18px;
}

.code-stage{
    position:relative;
    overflow:hidden;
    background:#fff;
    border:1px solid var(--line);
    border-radius:36px;
    box-shadow:var(--shadow);
}

.code-stage-head{
    padding:24px;
    color:#fff;
    background:
        radial-gradient(circle at top left,rgba(255,255,255,.18),transparent 30%),
        linear-gradient(135deg,#0f172a,#1d4ed8,#312e81);
    display:flex;
    justify-content:space-between;
    gap:18px;
    align-items:flex-start;
    flex-wrap:wrap;
}

.code-stage-head h3{
    font-size:28px;
    font-weight:900;
    margin-bottom:8px;
}

.code-stage-head p{
    color:#dbeafe;
    font-size:13px;
    line-height:1.8;
    font-weight:750;
}

.session-meta-grid{
    display:grid;
    grid-template-columns:repeat(4,1fr);
    gap:10px;
    margin-top:18px;
}

.meta-pill{
    background:rgba(255,255,255,.14);
    border:1px solid rgba(255,255,255,.20);
    border-radius:18px;
    padding:12px;
}

.meta-pill span{
    display:block;
    color:#bfdbfe;
    font-size:10px;
    font-weight:900;
    margin-bottom:5px;
}

.meta-pill strong{
    display:block;
    font-size:13px;
    font-weight:900;
}

.countdown-box{
    min-width:220px;
    background:rgba(255,255,255,.14);
    border:1px solid rgba(255,255,255,.20);
    border-radius:24px;
    padding:18px;
    text-align:center;
}

.countdown-box span{
    display:block;
    color:#bfdbfe;
    font-size:11px;
    font-weight:900;
    margin-bottom:8px;
}

.countdown-box strong{
    font-size:32px;
    font-weight:900;
    letter-spacing:-.5px;
}

.center-code{
    padding:34px;
    text-align:center;
}

.big-code-label{
    color:var(--muted);
    font-size:12px;
    font-weight:900;
    margin-bottom:12px;
}

.big-code{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    padding:28px 50px;
    border-radius:32px;
    color:#fff;
    background:linear-gradient(135deg,#0f172a,#2563eb,#312e81);
    font-size:70px;
    font-weight:900;
    letter-spacing:4px;
    box-shadow:0 26px 70px rgba(37,99,235,.25);
    margin-bottom:20px;
}

.code-actions{
    display:flex;
    align-items:center;
    justify-content:center;
    gap:10px;
    flex-wrap:wrap;
}

.qr-modal{
    display:none;
    position:fixed;
    inset:0;
    z-index:1000;
    background:rgba(15,23,42,.74);
    backdrop-filter:blur(12px);
    align-items:center;
    justify-content:center;
    padding:20px;
}

.qr-modal.active{
    display:flex;
}

.qr-modal-card{
    width:100%;
    max-width:560px;
    background:#fff;
    border-radius:34px;
    padding:24px;
    text-align:center;
    box-shadow:0 30px 90px rgba(0,0,0,.28);
}

.qr-modal-card h3{
    font-size:24px;
    font-weight:900;
    margin-bottom:8px;
}

.qr-modal-card p{
    color:var(--muted);
    font-size:13px;
    font-weight:750;
    line-height:1.7;
    margin-bottom:16px;
}

.qr-image{
    border:1px solid var(--line);
    border-radius:26px;
    padding:14px;
    background:#f8fafc;
    margin-bottom:16px;
}

.qr-image img{
    width:100%;
    max-width:420px;
    display:block;
    margin:auto;
    border-radius:18px;
}

.review-toggle{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:12px;
    margin-bottom:18px;
}

.review-btn{
    padding:16px;
    border-radius:22px;
    border:1px solid var(--line);
    background:#fff;
    cursor:pointer;
    font-weight:900;
    color:var(--muted);
}

.review-btn.active{
    background:#eff6ff;
    color:#1d4ed8;
    border-color:#bfdbfe;
}

.review-section{
    display:none;
}

.review-section.active{
    display:block;
}

.student-panel{
    background:#fff;
    border:1px solid var(--line);
    border-radius:32px;
    box-shadow:var(--shadow);
    overflow:hidden;
}

.student-head{
    padding:20px;
    border-bottom:1px solid var(--line);
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:14px;
    flex-wrap:wrap;
}

.student-head h3{
    font-size:22px;
    font-weight:900;
}

.student-head p{
    color:var(--muted);
    font-size:12px;
    font-weight:750;
    margin-top:4px;
}

.student-search{
    max-width:320px;
}

.stats-grid{
    display:grid;
    grid-template-columns:repeat(6,1fr);
    gap:10px;
    padding:18px;
    border-bottom:1px solid var(--line);
    background:#fbfdff;
}

.stat-box{
    border-radius:18px;
    padding:14px;
    background:#fff;
    border:1px solid #edf2f7;
}

.stat-box span{
    display:block;
    color:var(--muted);
    font-size:10px;
    font-weight:900;
    margin-bottom:5px;
}

.stat-box strong{
    font-size:22px;
    font-weight:900;
}

.table-wrap{
    overflow-x:auto;
}

.students-table{
    width:100%;
    border-collapse:collapse;
    min-width:850px;
}

.students-table th{
    text-align:left;
    padding:14px 15px;
    background:#f8fafc;
    color:#64748b;
    font-size:11px;
    font-weight:900;
    border-bottom:1px solid var(--line);
}

.students-table td{
    padding:14px 15px;
    border-bottom:1px solid #f1f5f9;
    vertical-align:middle;
    font-size:13px;
    font-weight:750;
}

.student-name{
    font-weight:900;
}

.status-badge{
    display:inline-flex;
    align-items:center;
    gap:6px;
    padding:8px 11px;
    border-radius:999px;
    font-size:11px;
    font-weight:900;
    border:1px solid transparent;
}

.status-present{
    background:#ecfdf5;
    color:#047857;
    border-color:#a7f3d0;
}

.status-late{
    background:#fff7ed;
    color:#c2410c;
    border-color:#fed7aa;
}

.status-excused{
    background:#fefce8;
    color:#a16207;
    border-color:#fde68a;
}

.status-absent{
    background:#fef2f2;
    color:#b91c1c;
    border-color:#fecaca;
}

.manual-form{
    display:flex;
    gap:8px;
    align-items:center;
}

.manual-form .select{
    min-width:130px;
    min-height:42px;
}

.empty-state{
    background:#fff;
    border:1px dashed #cbd5e1;
    border-radius:30px;
    padding:50px 24px;
    text-align:center;
    color:#64748b;
    font-size:14px;
    font-weight:850;
    line-height:1.8;
    box-shadow:var(--soft-shadow);
}

@media(max-width:1350px){
    .hero-stats,
    .stats-grid{
        grid-template-columns:repeat(3,1fr);
    }

    .session-meta-grid{
        grid-template-columns:repeat(2,1fr);
    }

    .big-code{
        font-size:54px;
    }
}

@media(max-width:850px){
    .topbar{
        flex-direction:column;
    }

    .grid-filter,
    .grid-create{
        grid-template-columns:1fr;
    }

    .hero-stats,
    .stats-grid,
    .session-meta-grid,
    .review-toggle{
        grid-template-columns:1fr;
    }

    .page-title{
        font-size:30px;
    }

    .hero h2{
        font-size:26px;
    }

    .big-code{
        width:100%;
        font-size:40px;
        padding:22px;
    }
}
</style>
</head>

<body>

<div class="app">

    <div class="topbar">

        <div>
            <div class="page-title">
                Core Attendance Center
            </div>

            <div class="page-subtitle">
                Premium attendance control system for SMI Core Periods.
                Create attendance sessions, display ATT codes, manage students,
                review daily attendance, and track monthly attendance grades.
            </div>
        </div>

        <div class="top-actions">
            <a href="dashboard.php" class="btn btn-light">
                Dashboard
            </a>

            <a href="attendance-reports.php" class="btn btn-primary">
                Reports
            </a>
        </div>

    </div>

    <?php if ($successMessage): ?>
        <div class="alert alert-success">
            <?php echo e($successMessage); ?>
        </div>
    <?php endif; ?>

    <?php if ($errorMessage): ?>
        <div class="alert alert-error">
            <?php echo e($errorMessage); ?>
        </div>
    <?php endif; ?>

    <section class="hero">

        <h2>
            Academic Attendance Dashboard
        </h2>

        <p>
            ATT codes stay active for two hours only.
            Present students receive 0.50 points,
            late students receive 0.25 points,
            and excused students receive full attendance points.
        </p>

        <div class="hero-stats">

            <div class="hero-stat">
                <span>Total Students</span>
                <strong><?php echo e((string)$sessionSummary['total_students']); ?></strong>
            </div>

            <div class="hero-stat">
                <span>Present</span>
                <strong><?php echo e((string)$sessionSummary['present']); ?></strong>
            </div>

            <div class="hero-stat">
                <span>Late</span>
                <strong><?php echo e((string)$sessionSummary['late']); ?></strong>
            </div>

            <div class="hero-stat">
                <span>Excused</span>
                <strong><?php echo e((string)$sessionSummary['excused']); ?></strong>
            </div>

            <div class="hero-stat">
                <span>Absent</span>
                <strong><?php echo e((string)$sessionSummary['absent']); ?></strong>
            </div>

            <div class="hero-stat">
                <span>Attendance Rate</span>
                <strong><?php echo e((string)$sessionSummary['attendance_rate']); ?>%</strong>
            </div>

        </div>

    </section>

    <section class="panel">

        <div class="panel-head">

            <div>
                <div class="panel-title">
                    Search Attendance Sessions
                </div>

                <div class="panel-subtitle">
                    Search courses by first letters, filter by date,
                    and load one attendance session only.
                </div>
            </div>

        </div>

        <form method="GET" class="grid-filter">

            <input
                type="text"
                name="course_search"
                value="<?php echo e($courseSearch); ?>"
                class="input"
                placeholder="Search course by first letters...">

            <input
                type="date"
                name="date"
                value="<?php echo e($selectedDate); ?>"
                class="input">

            <select name="course_id" class="select">

                <option value="0">
                    All Courses
                </option>

                <?php foreach ($courses as $course): ?>

                    <option
                        value="<?php echo (int)($course['id'] ?? 0); ?>"
                        <?php echo $selectedCourseId === (int)($course['id'] ?? 0) ? 'selected' : ''; ?>>

                        <?php
                        echo e(
                            (string)($course['title'] ?? 'Course')
                            .
                            ' — '
                            .
                            (string)($course['teacher_full_name'] ?? $course['teacher_name'] ?? 'No Teacher')
                        );
                        ?>

                    </option>

                <?php endforeach; ?>

            </select>

            <button type="submit" class="btn btn-primary">
                Search
            </button>

        </form>

        <?php if ($sessions): ?>

            <form method="GET" class="grid-filter" style="margin-top:12px;">

                <input type="hidden" name="course_search" value="<?php echo e($courseSearch); ?>">

                <input type="hidden" name="date" value="<?php echo e($selectedDate); ?>">

                <input type="hidden" name="course_id" value="<?php echo (int)$selectedCourseId; ?>">

                <select name="session_id" class="select">

                    <option value="0">
                        Choose Session
                    </option>

                    <?php foreach ($sessions as $session): ?>

                        <option
                            value="<?php echo (int)($session['id'] ?? 0); ?>"
                            <?php echo $selectedSessionId === (int)($session['id'] ?? 0) ? 'selected' : ''; ?>>

                            <?php
                            echo e(
                                (string)($session['title'] ?? 'Attendance')
                                .
                                ' | '
                                .
                                dayName($session['session_date'] ?? '')
                                .
                                ' | '
                                .
                                formatDateNice($session['session_date'] ?? '')
                                .
                                ' | '
                                .
                                formatTimeNice($session['session_time'] ?? '')
                            );
                            ?>

                        </option>

                    <?php endforeach; ?>

                </select>

                <button type="submit" class="btn btn-primary">
                    Load Session
                </button>

            </form>

        <?php endif; ?>

    </section>

    <section class="panel">

        <div class="panel-head">

            <div>
                <div class="panel-title">
                    Create Attendance Session
                </div>

                <div class="panel-subtitle">
                    Create attendance, generate ATT-00000 code,
                    and activate QR attendance.
                </div>
            </div>

        </div>

        <form method="POST" class="grid-create">
<?php echo csrfField(); ?>

            <input type="hidden" name="action" value="create_session">

            <select name="course_id" class="select" required>

                <option value="">
                    Choose Course
                </option>

                <?php foreach ($courses as $course): ?>

                    <option
                        value="<?php echo (int)($course['id'] ?? 0); ?>"
                        <?php echo $selectedCourseId === (int)($course['id'] ?? 0) ? 'selected' : ''; ?>>

                        <?php
                        echo e(
                            (string)($course['title'] ?? 'Course')
                            .
                            ' — '
                            .
                            (string)($course['level'] ?? 'Level')
                        );
                        ?>

                    </option>

                <?php endforeach; ?>

            </select>

            <input
                type="text"
                name="session_title"
                class="input"
                placeholder="Session Name">

            <input
                type="date"
                name="session_date"
                value="<?php echo e($selectedDate); ?>"
                class="input"
                required>

            <input
                type="time"
                name="session_time"
                value="<?php echo e(date('H:i')); ?>"
                class="input"
                required>

            <button type="submit" class="btn btn-primary">
                Create Attendance
            </button>

        </form>

    </section>

    <?php if ($selectedSession && $attendanceSession): ?>

        <section class="session-shell">

            <section class="code-stage">

                <div class="code-stage-head">

                    <div>

                        <h3>
                            <?php echo e((string)($selectedSession['title'] ?? 'Attendance Session')); ?>
                        </h3>

                        <p>
                            <?php echo e((string)($selectedSession['course_title'] ?? 'Course')); ?>
                            —
                            <?php echo e((string)($selectedSession['course_level'] ?? 'General')); ?>
                        </p>

                        <div class="session-meta-grid">

                            <div class="meta-pill">
                                <span>Day</span>
                                <strong>
                                    <?php echo e(dayName($selectedSession['session_date'] ?? '')); ?>
                                </strong>
                            </div>

                            <div class="meta-pill">
                                <span>Date</span>
                                <strong>
                                    <?php echo e(formatDateNice($selectedSession['session_date'] ?? '')); ?>
                                </strong>
                            </div>

                            <div class="meta-pill">
                                <span>Time</span>
                                <strong>
                                    <?php echo e(formatTimeNice($selectedSession['session_time'] ?? '')); ?>
                                </strong>
                            </div>

                            <div class="meta-pill">
                                <span>Teacher</span>
                                <strong>
                                    <?php
                                    echo e(
                                        (string)(
                                            $selectedSession['teacher_full_name']
                                            ??
                                            $selectedSession['teacher_name']
                                            ??
                                            'No Teacher'
                                        )
                                    );
                                    ?>
                                </strong>
                            </div>

                        </div>

                    </div>

                    <div class="countdown-box">

                        <span>
                            Remaining Time
                        </span>

                        <strong id="countdown">
                            00:00:00
                        </strong>

                    </div>

                </div>

                <div class="center-code">

                    <div class="big-code-label">
                        STUDENT ATTENDANCE CODE
                    </div>

                    <div class="big-code">
                        <?php echo e((string)($attendanceSession['current_code'] ?? 'ATT-00000')); ?>
                    </div>

                    <div class="code-actions">

                        <button
                            type="button"
                            class="btn btn-primary"
                            onclick="openQrModal()">

                            Show QR & Code

                        </button>

                        <form method="POST">
<?php echo csrfField(); ?>

                            <input type="hidden" name="action" value="create_session">

                            <input type="hidden" name="course_id" value="<?php echo (int)$selectedSession['course_id']; ?>">

                            <input type="hidden" name="session_title" value="<?php echo e((string)$selectedSession['title']); ?>">

                            <input type="hidden" name="session_date" value="<?php echo e((string)$selectedSession['session_date']); ?>">

                            <input type="hidden" name="session_time" value="<?php echo e((string)$selectedSession['session_time']); ?>">

                            <button type="submit" class="btn btn-danger">
                                Reset Code
                            </button>

                        </form>

                    </div>

                </div>

            </section>

            <section class="student-panel" id="review-status">

                <div class="student-head">

                    <div>

                        <h3>
                            Review Status
                        </h3>

                        <p>
                            Daily attendance review and monthly attendance grades.
                        </p>

                    </div>

                    <input
                        type="text"
                        id="studentSearch"
                        class="input student-search"
                        placeholder="Search student...">

                </div>

                <div class="review-toggle">

                    <button
                        class="review-btn active"
                        onclick="showReviewSection('dailyReview', this)"
                        type="button">

                        Daily Attendance

                    </button>

                    <button
                        class="review-btn"
                        onclick="showReviewSection('monthlyReview', this)"
                        type="button">

                        Monthly Grades

                    </button>

                </div>

                <div id="dailyReview" class="review-section active">

                    <div class="stats-grid">

                        <div class="stat-box">
                            <span>Students</span>
                            <strong><?php echo e((string)$sessionSummary['total_students']); ?></strong>
                        </div>

                        <div class="stat-box">
                            <span>Present</span>
                            <strong><?php echo e((string)$sessionSummary['present']); ?></strong>
                        </div>

                        <div class="stat-box">
                            <span>Late</span>
                            <strong><?php echo e((string)$sessionSummary['late']); ?></strong>
                        </div>

                        <div class="stat-box">
                            <span>Excused</span>
                            <strong><?php echo e((string)$sessionSummary['excused']); ?></strong>
                        </div>

                        <div class="stat-box">
                            <span>Absent</span>
                            <strong><?php echo e((string)$sessionSummary['absent']); ?></strong>
                        </div>

                        <div class="stat-box">
                            <span>Rate</span>
                            <strong><?php echo e((string)$sessionSummary['attendance_rate']); ?>%</strong>
                        </div>

                    </div>

                    <div class="table-wrap">

                        <table class="students-table" id="studentsTable">

                            <thead>

                                <tr>

                                    <th>Student Name</th>

                                    <th>Status</th>

                                    <th>Points</th>

                                    <th>Submitted Time</th>

                                    <th>Manual Control</th>

                                </tr>

                            </thead>

                            <tbody>

                                <?php foreach ($students as $student): ?>

                                    <?php
                                    $studentId = (int)($student['id'] ?? 0);

                                    $attendance = $attendanceMap[$studentId] ?? null;

                                    $status = strtolower(
                                        (string)(
                                            $attendance['status']
                                            ??
                                            'absent'
                                        )
                                    );

                                    $points = (float)(
                                        $attendance['points_awarded']
                                        ??
                                        0
                                    );
                                    ?>

                                    <tr>

                                        <td>
                                            <div class="student-name">
                                                <?php echo e((string)($student['full_name'] ?? 'Student')); ?>
                                            </div>
                                        </td>

                                        <td>

                                            <span class="status-badge status-<?php echo e(statusClass($status)); ?>">

                                                <?php echo e(statusIcon($status)); ?>

                                                <?php echo e(statusLabel($status)); ?>

                                            </span>

                                        </td>

                                        <td>
                                            <strong>
                                                <?php echo e(number_format($points, 2)); ?>
                                            </strong>
                                        </td>

                                        <td>
                                            <?php echo e((string)($attendance['submitted_at'] ?? '--')); ?>
                                        </td>

                                        <td>

                                            <form method="POST" class="manual-form">
<?php echo csrfField(); ?>

                                                <input type="hidden" name="action" value="manual_attendance">

                                                <input type="hidden" name="session_id" value="<?php echo (int)$selectedSession['id']; ?>">

                                                <input type="hidden" name="student_id" value="<?php echo (int)$studentId; ?>">

                                                <select name="status" class="select">

                                                    <option value="present" <?php echo $status === 'present' ? 'selected' : ''; ?>>
                                                        Present
                                                    </option>

                                                    <option value="late" <?php echo $status === 'late' ? 'selected' : ''; ?>>
                                                        Late
                                                    </option>

                                                    <option value="excused" <?php echo $status === 'excused' ? 'selected' : ''; ?>>
                                                        Excused
                                                    </option>

                                                    <option value="absent" <?php echo $status === 'absent' ? 'selected' : ''; ?>>
                                                        Absent
                                                    </option>

                                                </select>

                                                <button type="submit" class="btn btn-primary btn-small">
                                                    Save
                                                </button>

                                            </form>

                                        </td>

                                    </tr>

                                <?php endforeach; ?>

                            </tbody>

                        </table>

                    </div>

                </div>

                <div id="monthlyReview" class="review-section">

                    <div class="table-wrap">

                        <table class="students-table">

                            <thead>

                                <tr>

                                    <th>Student Name</th>

                                    <th>Monthly Points</th>

                                    <th>Present</th>

                                    <th>Late</th>

                                    <th>Excused</th>

                                    <th>Absent</th>

                                </tr>

                            </thead>

                            <tbody>

                                <?php foreach ($students as $student): ?>

                                    <?php
                                    $studentId = (int)($student['id'] ?? 0);

                                    $monthly = $monthlyMap[$studentId] ?? [];
                                    ?>

                                    <tr>

                                        <td>
                                            <div class="student-name">
                                                <?php echo e((string)($student['full_name'] ?? 'Student')); ?>
                                            </div>
                                        </td>

                                        <td>
                                            <strong>
                                                <?php
                                                echo e(
                                                    number_format(
                                                        (float)($monthly['monthly_points'] ?? 0),
                                                        2
                                                    )
                                                );
                                                ?>
                                                /
                                                <?php echo e(number_format($monthlyAttendanceTotal, 2)); ?>
                                            </strong>
                                        </td>

                                        <td>
                                            <?php echo e((string)($monthly['present_count'] ?? 0)); ?>
                                        </td>

                                        <td>
                                            <?php echo e((string)($monthly['late_count'] ?? 0)); ?>
                                        </td>

                                        <td>
                                            <?php echo e((string)($monthly['excused_count'] ?? 0)); ?>
                                        </td>

                                        <td>
                                            <?php echo e((string)($monthly['absent_count'] ?? 0)); ?>
                                        </td>

                                    </tr>

                                <?php endforeach; ?>

                            </tbody>

                        </table>

                    </div>

                </div>

            </section>

        </section>

    <?php else: ?>

        <div class="empty-state">

            Create or load one attendance session to display
            the live ATT code, QR attendance, daily review,
            and monthly attendance grades.

        </div>

    <?php endif; ?>

</div>

<div class="qr-modal" id="qrModal">

    <div class="qr-modal-card">

        <h3>
            Scan QR Attendance
        </h3>

        <p>
            Students can scan this QR code or enter the ATT code manually.
        </p>

        <?php if ($qrImage !== ''): ?>

            <div class="qr-image">

                <img src="<?php echo e($qrImage); ?>" alt="QR Attendance">

            </div>

        <?php endif; ?>

        <div class="big-code" style="font-size:42px;padding:18px 28px;">
            <?php echo e((string)($attendanceSession['current_code'] ?? 'ATT-00000')); ?>
        </div>

        <div style="margin-top:14px;">

            <button class="btn btn-danger" onclick="closeQrModal()">
                Close
            </button>

        </div>

    </div>

</div>

<script>
function openQrModal() {
    document.getElementById('qrModal').classList.add('active');
}

function closeQrModal() {
    document.getElementById('qrModal').classList.remove('active');
}

function showReviewSection(id, btn) {

    document.querySelectorAll('.review-section').forEach(function(el){
        el.classList.remove('active');
    });

    document.querySelectorAll('.review-btn').forEach(function(el){
        el.classList.remove('active');
    });

    document.getElementById(id).classList.add('active');

    btn.classList.add('active');
}

const studentSearch = document.getElementById('studentSearch');
const studentsTable = document.getElementById('studentsTable');

if (studentSearch && studentsTable) {

    studentSearch.addEventListener('input', function () {

        const query = this.value.toLowerCase().trim();

        const rows = studentsTable.querySelectorAll('tbody tr');

        rows.forEach(function (row) {

            const text = row.innerText.toLowerCase();

            row.style.display = text.includes(query)
                ? ''
                : 'none';
        });
    });
}

let countdownSeconds = <?php echo (int)$countdownSeconds; ?>;

function updateCountdown() {

    if (countdownSeconds < 0) {
        countdownSeconds = 0;
    }

    const hours = Math.floor(countdownSeconds / 3600);
    const minutes = Math.floor((countdownSeconds % 3600) / 60);
    const seconds = countdownSeconds % 60;

    const formatted =
        String(hours).padStart(2, '0')
        + ':'
        + String(minutes).padStart(2, '0')
        + ':'
        + String(seconds).padStart(2, '0');

    const el = document.getElementById('countdown');

    if (el) {
        el.innerText = formatted;
    }

    if (countdownSeconds > 0) {
        countdownSeconds--;
    }
}

updateCountdown();

setInterval(updateCountdown, 1000);
</script>

</body>
</html>