<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| SMI Core Periods
| Premium Attendance Page
|--------------------------------------------------------------------------
*/

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

$pdo = db();

requireStudent();

$student = currentStudent($pdo);

if (!$student) {
    studentLogout();
    redirectTo('login.php');
}

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

if ($studentId <= 0) {
    studentLogout();
    redirectTo('login.php');
}

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

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

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('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('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('formatCoreDate')) {
    function formatCoreDate($date): string
    {
        if (empty($date) || $date === '0000-00-00' || $date === '0000-00-00 00:00:00') {
            return 'N/A';
        }

        $time = strtotime((string)$date);

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

if (!function_exists('safeUcfirst')) {
    function safeUcfirst($value, string $fallback = 'General'): string
    {
        $value = trim((string)($value ?? ''));

        if ($value === '') {
            return $fallback;
        }

        return ucfirst($value);
    }
}

if (!function_exists('attendanceStatusLabel')) {
    function attendanceStatusLabel(string $status): string
    {
        switch ($status) {
            case 'late':
                return 'Late';

            case 'absent':
                return 'Absent';

            case 'excused':
                return 'Excused';

            default:
                return 'Present';
        }
    }
}

if (!function_exists('attendanceStatusIcon')) {
    function attendanceStatusIcon(string $status): string
    {
        switch ($status) {
            case 'late':
                return '⏰';

            case 'absent':
                return '❌';

            case 'excused':
                return '🟡';

            default:
                return '✅';
        }
    }
}

if (!function_exists('attendanceStatusClass')) {
    function attendanceStatusClass(string $status): string
    {
        switch ($status) {
            case 'late':
                return 'late';

            case 'absent':
                return 'absent';

            case 'excused':
                return 'excused';

            default:
                return 'present';
        }
    }
}

/*
|--------------------------------------------------------------------------
| Student Data
|--------------------------------------------------------------------------
*/

$studentName = (string)($student['full_name'] ?? 'Student');
$studentCode = (string)($student['student_code'] ?? 'N/A');

$studentCard = (string)(
    $student['student_card_number']
    ?? $student['student_card']
    ?? $student['card_number']
    ?? 'N/A'
);

$studentLevel = safeUcfirst(
    $student['final_level']
    ?? $student['secondary_level']
    ?? $student['level']
    ?? 'General'
);

/*
|--------------------------------------------------------------------------
| Course Context
|--------------------------------------------------------------------------
*/

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

if ($courseId <= 0) {
    redirectTo('dashboard.php');
}

$validStatuses = [
    'active',
    'approved',
    'enrolled',
    'completed',
];

$course = null;

if (
    tableExists($pdo, 'core_courses') &&
    tableExists($pdo, 'core_course_students')
) {
    $placeholders = implode(',', array_fill(0, count($validStatuses), '?'));

    $params = array_merge(
        [
            $courseId,
            $studentId
        ],
        $validStatuses
    );

    $course = safeOne(
        $pdo,
        "
        SELECT
            c.*,
            cs.status AS enrollment_status
        FROM core_courses c
        INNER JOIN core_course_students cs
            ON cs.course_id = c.id
        WHERE c.id = ?
          AND cs.student_id = ?
          AND cs.status IN ($placeholders)
        LIMIT 1
        ",
        $params
    );
}

if (!$course) {
    redirectTo('dashboard.php');
}

$courseTitle = (string)($course['title'] ?? 'Core Course');

$courseCode = (string)(
    $course['course_code']
    ?? $course['code']
    ?? ('COURSE-' . $courseId)
);

$courseLevel = safeUcfirst(
    $course['level']
    ?? 'General'
);

/*
|--------------------------------------------------------------------------
| Attendance Records
|--------------------------------------------------------------------------
*/

$attendanceRecords = [];

if (
    tableExists($pdo, 'core_attendance') &&
    tableExists($pdo, 'core_sessions')
) {
    $hasAttendanceCourseId = columnExists($pdo, 'core_attendance', 'course_id');
    $hasAttendanceSessionId = columnExists($pdo, 'core_attendance', 'session_id');
    $hasSessionCourseId = columnExists($pdo, 'core_sessions', 'course_id');

    if ($hasAttendanceCourseId && $hasAttendanceSessionId) {
        $attendanceRecords = safeAll(
            $pdo,
            "
            SELECT
                a.*,
                s.title AS session_title,
                s.session_date,
                s.session_time
            FROM core_attendance a
            LEFT JOIN core_sessions s
                ON s.id = a.session_id
            WHERE a.student_id = ?
              AND a.course_id = ?
            ORDER BY
                s.session_date DESC,
                s.session_time DESC,
                a.id DESC
            LIMIT 120
            ",
            [
                $studentId,
                $courseId
            ]
        );
    } elseif ($hasAttendanceSessionId && $hasSessionCourseId) {
        $attendanceRecords = safeAll(
            $pdo,
            "
            SELECT
                a.*,
                s.title AS session_title,
                s.session_date,
                s.session_time
            FROM core_attendance a
            INNER JOIN core_sessions s
                ON s.id = a.session_id
            WHERE a.student_id = ?
              AND s.course_id = ?
            ORDER BY
                s.session_date DESC,
                s.session_time DESC,
                a.id DESC
            LIMIT 120
            ",
            [
                $studentId,
                $courseId
            ]
        );
    }
}

/*
|--------------------------------------------------------------------------
| Attendance Statistics
|--------------------------------------------------------------------------
*/

$presentCount = 0;
$lateCount = 0;
$absentCount = 0;
$excusedCount = 0;
$totalMinutes = 0;
$totalPoints = 0;

foreach ($attendanceRecords as $record) {
    $status = strtolower((string)($record['status'] ?? 'present'));

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

    $totalMinutes += (int)(
        $record['attendance_minutes']
        ?? $record['minutes_spent']
        ?? 0
    );

    $totalPoints += (int)(
        $record['points_awarded']
        ?? 0
    );
}

$totalSessions = count($attendanceRecords);

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

$circleLength = 314;
$circleOffset = $circleLength - ($circleLength * ($attendanceRate / 100));

$averageMinutes = $totalSessions > 0
    ? (int)round($totalMinutes / $totalSessions)
    : 0;

?>

<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8">

<meta
name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0">

<title>Attendance | SMI Core Periods</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;
    --green:#059669;
    --orange:#f97316;
    --red:#dc2626;
    --yellow:#ca8a04;
    --bg:#f6f8fc;
    --card:#ffffff;
    --text:#0f172a;
    --muted:#64748b;
    --line:#e2e8f0;
    --shadow:0 22px 60px rgba(15,23,42,.09);
    --soft-shadow:0 12px 28px rgba(15,23,42,.055);
}

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

html{
    scroll-behavior:smooth;
}

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 34%),
        radial-gradient(circle at top right,rgba(14,165,233,.10),transparent 30%),
        linear-gradient(135deg,#fbfdff,#f1f5fb);
    padding-bottom:92px;
}

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

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

.topbar{
    position:sticky;
    top:0;
    z-index:30;
    padding:10px 0 12px;
    margin-bottom:4px;
    background:rgba(246,248,252,.88);
    backdrop-filter:blur(18px);
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
}

.brand{
    display:flex;
    align-items:center;
    gap:11px;
    min-width:0;
}

.logo{
    width:58px;
    height:58px;
    border-radius:18px;
    background:linear-gradient(135deg,#2563eb,#312e81);
    color:#fff;
    display:flex;
    align-items:center;
    justify-content:center;
    font-weight:950;
    box-shadow:0 14px 28px rgba(37,99,235,.18);
    flex-shrink:0;
}

.brand-text{
    min-width:0;
}

.brand-text strong{
    display:block;
    font-size:16px;
    font-weight:950;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
}

.brand-text span{
    display:block;
    margin-top:3px;
    color:var(--muted);
    font-size:12px;
    font-weight:850;
}

.back-btn{
    min-height:42px;
    padding:0 14px;
    border-radius:15px;
    background:#ffffff;
    border:1px solid var(--line);
    color:var(--blue-dark);
    box-shadow:var(--soft-shadow);
    display:flex;
    align-items:center;
    justify-content:center;
    font-size:12px;
    font-weight:950;
}

.hero{
    position:relative;
    overflow:hidden;
    border-radius:34px;
    padding:25px;
    color:#ffffff;
    background:
        radial-gradient(circle at 10% 8%,rgba(255,255,255,.18),transparent 28%),
        radial-gradient(circle at 90% 16%,rgba(14,165,233,.22),transparent 30%),
        linear-gradient(135deg,#1e3a8a,#2563eb 52%,#312e81);
    box-shadow:0 28px 70px rgba(37,99,235,.28);
    margin-bottom:16px;
}

.hero::after{
    content:"SMI";
    position:absolute;
    right:20px;
    bottom:-22px;
    font-size:92px;
    font-weight:950;
    letter-spacing:-5px;
    color:rgba(255,255,255,.07);
}

.hero-inner{
    position:relative;
    z-index:2;
}

.hero-kicker{
    display:inline-flex;
    align-items:center;
    gap:8px;
    padding:8px 12px;
    border-radius:999px;
    background:rgba(255,255,255,.14);
    border:1px solid rgba(255,255,255,.22);
    color:#eff6ff;
    font-size:11px;
    font-weight:950;
    margin-bottom:14px;
}

.hero h1{
    font-size:31px;
    line-height:1.12;
    font-weight:950;
    letter-spacing:-.8px;
    margin-bottom:8px;
}

.hero p{
    max-width:620px;
    color:#dbeafe;
    font-size:13px;
    line-height:1.75;
    font-weight:750;
}

.student-strip{
    margin-top:16px;
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:10px;
}

.student-box{
    padding:14px;
    border-radius:22px;
    background:rgba(255,255,255,.14);
    border:1px solid rgba(255,255,255,.22);
    backdrop-filter:blur(12px);
}

.student-box span{
    display:block;
    color:#bfdbfe;
    font-size:11px;
    font-weight:950;
    margin-bottom:6px;
}

.student-box strong{
    display:block;
    font-size:15px;
    font-weight:950;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
}

.smart-stats{
    display:grid;
    grid-template-columns:.95fr 1.05fr;
    gap:14px;
    margin-bottom:16px;
}

.main-score{
    background:rgba(255,255,255,.96);
    border:1px solid rgba(226,232,240,.92);
    border-radius:34px;
    padding:22px;
    box-shadow:var(--soft-shadow);
    display:flex;
    align-items:center;
    justify-content:center;
    min-height:226px;
}

.score-ring{
    position:relative;
    width:176px;
    height:176px;
}

.score-ring svg{
    width:100%;
    height:100%;
    transform:rotate(-90deg);
}

.bg-circle{
    fill:none;
    stroke:#e5e7eb;
    stroke-width:9;
}

.progress-circle{
    fill:none;
    stroke:url(#scoreGradient);
    stroke-width:9;
    stroke-linecap:round;
    transition:1s ease;
}

.score-center{
    position:absolute;
    inset:0;
    display:flex;
    align-items:center;
    justify-content:center;
    flex-direction:column;
}

.score-center strong{
    font-size:34px;
    font-weight:950;
    color:#0f172a;
    line-height:1;
}

.score-center span{
    margin-top:7px;
    color:#64748b;
    font-size:12px;
    font-weight:900;
}

.mini-cards{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:12px;
}

.mini-card{
    position:relative;
    overflow:hidden;
    min-height:107px;
    padding:17px;
    border-radius:27px;
    color:#ffffff;
    box-shadow:0 16px 36px rgba(15,23,42,.10);
}

.mini-card::after{
    content:"";
    position:absolute;
    width:95px;
    height:95px;
    border-radius:50%;
    background:rgba(255,255,255,.16);
    right:-35px;
    top:-35px;
}

.mini-card span,
.mini-card strong,
.mini-card small{
    position:relative;
    z-index:2;
}

.mini-card span{
    display:block;
    font-size:25px;
    margin-bottom:9px;
}

.mini-card strong{
    display:block;
    font-size:27px;
    font-weight:950;
    line-height:1;
}

.mini-card small{
    display:block;
    margin-top:7px;
    font-size:12px;
    opacity:.92;
    font-weight:850;
}

.mini-card.present{
    background:linear-gradient(135deg,#059669,#10b981);
}

.mini-card.late{
    background:linear-gradient(135deg,#f97316,#fb923c);
}

.mini-card.absent{
    background:linear-gradient(135deg,#dc2626,#ef4444);
}

.mini-card.sessions{
    background:linear-gradient(135deg,#2563eb,#60a5fa);
}

.mini-card.minutes{
    background:linear-gradient(135deg,#7c3aed,#a78bfa);
}

.mini-card.points{
    background:linear-gradient(135deg,#ca8a04,#facc15);
}

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

.glass-button{
    min-height:82px;
    padding:18px;
    border-radius:26px;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    background:rgba(255,255,255,.96);
    border:1px solid rgba(226,232,240,.95);
    box-shadow:var(--soft-shadow);
    transition:.25s ease;
}

.glass-button:hover{
    transform:translateY(-3px);
    box-shadow:var(--shadow);
}

.glass-button.primary{
    background:linear-gradient(135deg,#2563eb,#1d4ed8);
    color:#ffffff;
    border-color:rgba(255,255,255,.18);
}

.glass-button strong{
    display:block;
    font-size:15px;
    font-weight:950;
    margin-bottom:5px;
}

.glass-button small{
    display:block;
    color:var(--muted);
    font-size:12px;
    font-weight:800;
}

.glass-button.primary small{
    color:#dbeafe;
}

.arrow{
    width:34px;
    height:34px;
    border-radius:13px;
    display:flex;
    align-items:center;
    justify-content:center;
    background:#eff6ff;
    color:#1d4ed8;
    font-weight:950;
    flex-shrink:0;
}

.glass-button.primary .arrow{
    background:rgba(255,255,255,.15);
    color:#ffffff;
}

.section-head{
    display:flex;
    align-items:flex-end;
    justify-content:space-between;
    gap:12px;
    margin:20px 2px 13px;
}

.section-head h2{
    font-size:21px;
    font-weight:950;
    letter-spacing:-.3px;
}

.section-head p{
    color:#64748b;
    font-size:12px;
    font-weight:850;
    margin-top:4px;
}

.timeline{
    position:relative;
    display:grid;
    gap:12px;
}

.session-card{
    position:relative;
    background:rgba(255,255,255,.97);
    border:1px solid rgba(226,232,240,.96);
    border-radius:26px;
    padding:15px;
    box-shadow:var(--soft-shadow);
    display:grid;
    grid-template-columns:auto 1fr auto;
    gap:13px;
    align-items:flex-start;
    transition:.25s ease;
}

.session-card:hover{
    transform:translateY(-2px);
    box-shadow:var(--shadow);
}

.timeline-dot{
    width:52px;
    height:52px;
    border-radius:19px;
    display:flex;
    align-items:center;
    justify-content:center;
    font-size:21px;
    flex-shrink:0;
}

.timeline-dot.present{
    background:#ecfdf5;
    color:#047857;
    border:1px solid #a7f3d0;
}

.timeline-dot.late{
    background:#fff7ed;
    color:#c2410c;
    border:1px solid #fed7aa;
}

.timeline-dot.absent{
    background:#fef2f2;
    color:#dc2626;
    border:1px solid #fecaca;
}

.timeline-dot.excused{
    background:#fefce8;
    color:#a16207;
    border:1px solid #fde68a;
}

.timeline-content{
    min-width:0;
}

.session-title{
    font-size:15px;
    font-weight:950;
    line-height:1.45;
    margin-bottom:8px;
}

.timeline-info{
    display:flex;
    flex-wrap:wrap;
    gap:8px;
}

.info-chip{
    display:inline-flex;
    align-items:center;
    gap:5px;
    padding:7px 9px;
    border-radius:999px;
    background:#f8fafc;
    border:1px solid #edf2f7;
    color:#64748b;
    font-size:11px;
    font-weight:850;
}

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

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

.info-chip.absent{
    background:#fef2f2;
    color:#dc2626;
    border-color:#fecaca;
}

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

.points-badge{
    white-space:nowrap;
    padding:9px 13px;
    border-radius:999px;
    background:#eff6ff;
    border:1px solid #bfdbfe;
    color:#1d4ed8;
    font-size:12px;
    font-weight:950;
}

.empty{
    text-align:center;
    background:#ffffff;
    border:1px dashed #cbd5e1;
    border-radius:26px;
    padding:34px 20px;
    color:#64748b;
    font-size:14px;
    font-weight:850;
    line-height:1.8;
}

.bottom-nav{
    position:fixed;
    left:50%;
    bottom:14px;
    transform:translateX(-50%);
    width:calc(100% - 28px);
    max-width:520px;
    background:rgba(255,255,255,.94);
    border:1px solid rgba(226,232,240,.95);
    box-shadow:0 20px 55px rgba(15,23,42,.18);
    backdrop-filter:blur(18px);
    border-radius:24px;
    padding:8px;
    z-index:80;
    display:grid;
    grid-template-columns:repeat(5,1fr);
    gap:6px;
}

.bottom-nav a{
    display:flex;
    flex-direction:column;
    align-items:center;
    justify-content:center;
    gap:4px;
    padding:9px 4px;
    border-radius:18px;
    color:#64748b;
    font-size:11px;
    font-weight:900;
}

.bottom-nav a.active{
    background:#eff6ff;
    color:#1d4ed8;
}

.bottom-nav span{
    font-size:18px;
}

@media(max-width:760px){
    .smart-stats{
        grid-template-columns:1fr;
    }

    .main-score{
        min-height:auto;
    }

    .student-strip{
        grid-template-columns:1fr;
    }

    .action-buttons{
        grid-template-columns:1fr;
    }
}

@media(max-width:540px){
    .app{
        padding:11px;
    }

    .hero{
        border-radius:29px;
        padding:22px;
    }

    .hero h1{
        font-size:27px;
    }

    .score-ring{
        width:158px;
        height:158px;
    }

    .mini-cards{
        gap:10px;
    }

    .mini-card{
        border-radius:24px;
        padding:15px;
        min-height:100px;
    }

    .section-head{
        align-items:flex-start;
        flex-direction:column;
    }

    .session-card{
        grid-template-columns:auto 1fr;
    }

    .points-badge{
        grid-column:1 / -1;
        width:max-content;
        margin-inline-start:65px;
    }
}
</style>

</head>

<body>

<div class="app">

    <header class="topbar">

        <div class="brand">

            <div class="logo">
                SMI
            </div>

            <div class="brand-text">
                <strong>Core Attendance</strong>
                <span><?php echo e($courseTitle); ?></span>
            </div>

        </div>

        <a href="dashboard.php?course_id=<?php echo (int)$courseId; ?>" class="back-btn">
            Course
        </a>

    </header>

    <section class="hero">

        <div class="hero-inner">

            <div class="hero-kicker">
                📌 Core Course Attendance
            </div>

            <h1>
                <?php echo e($studentName); ?>
            </h1>

            <p>
                Review your attendance performance, session consistency,
                learning minutes, and participation record for
                <?php echo e($courseTitle); ?>.
            </p>

            <div class="student-strip">

                <div class="student-box">
                    <span>Student Code</span>
                    <strong><?php echo e($studentCode); ?></strong>
                </div>

                <div class="student-box">
                    <span>Student Card</span>
                    <strong><?php echo e($studentCard); ?></strong>
                </div>

                <div class="student-box">
                    <span>Course Code</span>
                    <strong><?php echo e($courseCode); ?></strong>
                </div>

                <div class="student-box">
                    <span>Core Level</span>
                    <strong><?php echo e($courseLevel); ?></strong>
                </div>

            </div>

        </div>

    </section>

    <section class="smart-stats">

        <div class="main-score">

            <div class="score-ring">

                <svg viewBox="0 0 120 120">

                    <defs>
                        <linearGradient id="scoreGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                            <stop offset="0%" stop-color="#2563eb" />
                            <stop offset="100%" stop-color="#60a5fa" />
                        </linearGradient>
                    </defs>

                    <circle
                        cx="60"
                        cy="60"
                        r="50"
                        class="bg-circle"
                    />

                    <circle
                        cx="60"
                        cy="60"
                        r="50"
                        class="progress-circle"
                        style="
                            stroke-dasharray:<?php echo e((string)$circleLength); ?>;
                            stroke-dashoffset:<?php echo e((string)$circleOffset); ?>;
                        "
                    />

                </svg>

                <div class="score-center">
                    <strong><?php echo e((string)$attendanceRate); ?>%</strong>
                    <span>Attendance Rate</span>
                </div>

            </div>

        </div>

        <div class="mini-cards">

            <div class="mini-card present">
                <span>✅</span>
                <strong><?php echo e((string)$presentCount); ?></strong>
                <small>Present</small>
            </div>

            <div class="mini-card late">
                <span>⏰</span>
                <strong><?php echo e((string)$lateCount); ?></strong>
                <small>Late</small>
            </div>

            <div class="mini-card absent">
                <span>❌</span>
                <strong><?php echo e((string)$absentCount); ?></strong>
                <small>Absent</small>
            </div>

            <div class="mini-card sessions">
                <span>📚</span>
                <strong><?php echo e((string)$totalSessions); ?></strong>
                <small>Total Sessions</small>
            </div>

            <div class="mini-card minutes">
                <span>⏱</span>
                <strong><?php echo e((string)$totalMinutes); ?></strong>
                <small>Total Minutes</small>
            </div>

            <div class="mini-card points">
                <span>⭐</span>
                <strong><?php echo e((string)$totalPoints); ?></strong>
                <small>Points</small>
            </div>

        </div>

    </section>

    <section class="action-buttons">

        <a href="dashboard.php?course_id=<?php echo (int)$courseId; ?>" class="glass-button primary">
            <div>
                <strong>🏠 Course Dashboard</strong>
                <small>Return to this course control center.</small>
            </div>

            <div class="arrow">
                →
            </div>
        </a>

        <a href="submit-attendance.php?course_id=<?php echo (int)$courseId; ?>" class="glass-button">
            <div>
                <strong>📸 Submit Attendance</strong>
                <small>Submit today’s attendance code for this course.</small>
            </div>

            <div class="arrow">
                →
            </div>
        </a>

    </section>

    <section class="section-head">

        <div>
            <h2>Attendance Timeline</h2>
            <p>Your latest attendance records for this core course</p>
        </div>

    </section>

    <section class="timeline">

        <?php if($attendanceRecords): ?>

            <?php foreach($attendanceRecords as $record): ?>

                <?php
                    $status = strtolower((string)($record['status'] ?? 'present'));
                    $minutes = (int)(
                        $record['attendance_minutes']
                        ??
                        $record['minutes_spent']
                        ??
                        0
                    );

                    $points = (int)($record['points_awarded'] ?? 0);

                    $date = $record['session_date']
                        ??
                        $record['created_at']
                        ??
                        '';

                    $time = (string)($record['session_time'] ?? '');
                ?>

                <article class="session-card">

                    <div class="timeline-dot <?php echo e(attendanceStatusClass($status)); ?>">
                        <?php echo e(attendanceStatusIcon($status)); ?>
                    </div>

                    <div class="timeline-content">

                        <div class="session-title">
                            <?php echo e((string)($record['session_title'] ?? 'Attendance Record')); ?>
                        </div>

                        <div class="timeline-info">

                            <span class="info-chip <?php echo e(attendanceStatusClass($status)); ?>">
                                <?php echo e(attendanceStatusLabel($status)); ?>
                            </span>

                            <span class="info-chip">
                                📅 <?php echo e(formatCoreDate($date)); ?>
                            </span>

                            <?php if ($time !== ''): ?>
                                <span class="info-chip">
                                    🕒 <?php echo e($time); ?>
                                </span>
                            <?php endif; ?>

                            <span class="info-chip">
                                ⏱ <?php echo e((string)$minutes); ?> min
                            </span>

                        </div>

                    </div>

                    <div class="points-badge">
                        +<?php echo e((string)$points); ?> pts
                    </div>

                </article>

            <?php endforeach; ?>

        <?php else: ?>

            <div class="empty">
                No attendance records yet for this course.
                <br>
                Records will appear here after attendance is submitted or recorded by the teacher.
            </div>

        <?php endif; ?>

    </section>

</div>

<nav class="bottom-nav">

    <a href="dashboard.php">
        <span>🏠</span>
        Home
    </a>

    <a href="dashboard.php?course_id=<?php echo (int)$courseId; ?>">
        <span>📚</span>
        Course
    </a>

    <a href="attendance.php?course_id=<?php echo (int)$courseId; ?>" class="active">
        <span>✅</span>
        Attendance
    </a>

    <a href="submit-attendance.php?course_id=<?php echo (int)$courseId; ?>">
        <span>📸</span>
        Submit
    </a>

    <a href="profile.php">
        <span>👤</span>
        Profile
    </a>

</nav>

</body>
</html>