<?php
// students.php - Student Portal with full filtering
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'includes/conn.php';
require_once 'includes/functions.php';

requireRole('student');

enforceAccessControl($pdo);

$student_id = (int)($_SESSION['user_id'] ?? 0);
if (!$student_id) { header('Location: index.php'); exit; }

// ---------- Student Info ----------
$student_info_stmt = $pdo->prepare("SELECT first_name, last_name, photo, email, current_class, date_of_birth FROM users WHERE id = ?");
$student_info_stmt->execute([$student_id]);
$student_info = $student_info_stmt->fetch(PDO::FETCH_ASSOC) ?: ['first_name'=>'', 'last_name'=>'', 'photo'=>null, 'email'=>'', 'current_class'=>'', 'date_of_birth'=>''];

$student_name = trim(($student_info['first_name'] ?? '') . ' ' . ($student_info['last_name'] ?? ''));
$student_email = $student_info['email'] ?? '';
$student_class = $student_info['current_class'] ?? '';
$student_dob = $student_info['date_of_birth'] ?? '';

// Build photo src (detect mime if BLOB present)
$photo_src = 'user.png';
if (!empty($student_info['photo'])) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_buffer($finfo, $student_info['photo']);
    finfo_close($finfo);
    $mime = $mime ?: 'image/jpeg';
    $photo_src = 'data:' . $mime . ';base64,' . base64_encode($student_info['photo']);
}

// ---------- Active Session & Term ----------
$active_session = $pdo->query("SELECT * FROM sessions WHERE is_active = 1 LIMIT 1")->fetch(PDO::FETCH_ASSOC) ?: null;
$active_term = $pdo->query("SELECT * FROM terms WHERE is_active = 1 LIMIT 1")->fetch(PDO::FETCH_ASSOC) ?: null;

// GET parameters for filtering
$session_id = isset($_GET['session_id']) ? (int)$_GET['session_id'] : ($active_session['id'] ?? null);
$term_id = isset($_GET['term_id']) ? (int)$_GET['term_id'] : ($active_term['id'] ?? null);
$class_id = isset($_GET['class_id']) ? (int)$_GET['class_id'] : null;

// ---------- Subjects Assigned ----------
$subject_stmt = $pdo->prepare("
    SELECT s.id, s.name
    FROM subjects s
    INNER JOIN student_subjects ss ON s.id = ss.subject_id
    WHERE ss.student_id = ?
    ORDER BY s.name ASC
");
$subject_stmt->execute([$student_id]);
$student_subjects = $subject_stmt->fetchAll(PDO::FETCH_ASSOC);
$subject_ids = !empty($student_subjects) ? array_column($student_subjects, 'id') : [];

// ---------- Terminal Grades ----------
$term_grades = [];
$no_subjects_message = null;

if (empty($student_subjects)) {
    $no_subjects_message = "⚠️ You have not been assigned any subjects yet. Please contact your teacher or administrator.";
} elseif ($session_id && $term_id) {
    // prepare placeholders only for subject_ids
    if (!empty($subject_ids)) {
        $placeholders = implode(',', array_fill(0, count($subject_ids), '?'));
        $sql = "
            SELECT g.*, s.name AS subject_name, c.name AS classroom_name,
                   u.first_name AS teacher_first, u.last_name AS teacher_last
            FROM grades g
            LEFT JOIN subjects s ON g.subject_id = s.id
            LEFT JOIN classrooms c ON g.classroom_id = c.id
            LEFT JOIN users u ON g.teacher_id = u.id
            WHERE g.student_id = ?
              AND g.session_id = ?
              AND g.term_id = ?
              AND g.subject_id IN ($placeholders)
        ";

        $bind = array_merge([$student_id, $session_id, $term_id], $subject_ids);

        if ($class_id) {
            $sql .= " AND g.classroom_id = ?";
            $bind[] = $class_id;
        }

        $sql .= " ORDER BY s.name";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($bind);
        $term_grades = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $term_grades = [];
    }
}

// ---------- Terminal Statistics ----------
$total_marks = $sum_scores = 0;
$nonzero_count = 0;
$grade_distribution = ['A1'=>0,'A2'=>0,'B1'=>0,'B2'=>0,'UC'=>0,'LC'=>0,'P'=>0,'F'=>0];

foreach ($term_grades as $g) {
    $t = isset($g['total']) ? (float)$g['total'] : 0;
    if ($t > 0) { $total_marks += $t; $sum_scores += $t; $nonzero_count++; }
    $letter = $g['grade'] ?? ($t>0 ? calculateGradePoint($t) : null);
    if ($letter && isset($grade_distribution[$letter])) $grade_distribution[$letter]++;
}
$average_grade = $nonzero_count ? ($sum_scores / $nonzero_count) : 0;
$total_grades = $nonzero_count;

// ---------- Final Session Results (per student) ----------
$final_subject_data = [];
if ($session_id && $subject_ids) {
    $placeholders = implode(',', array_fill(0, count($subject_ids), '?'));
    // Note: include student_id conditions in SUM cases so we aggregate only this student's grades
    $sql = "
        SELECT s.id AS subject_id, s.name AS subject_name,
            SUM(CASE WHEN g.term_id=1 AND g.session_id=? AND g.student_id=? THEN g.total ELSE 0 END) AS first_term,
            SUM(CASE WHEN g.term_id=2 AND g.session_id=? AND g.student_id=? THEN g.total ELSE 0 END) AS second_term,
            SUM(CASE WHEN g.term_id=3 AND g.session_id=? AND g.student_id=? THEN g.total ELSE 0 END) AS third_term,
            ROUND(AVG(CASE WHEN g.term_id IN (1,2,3) AND g.session_id=? AND g.student_id=? THEN g.total ELSE NULL END),2) AS average_score
        FROM subjects s
        LEFT JOIN grades g ON g.subject_id=s.id
        WHERE s.id IN ($placeholders)
        GROUP BY s.id
        ORDER BY s.name
    ";
    // Bind: for each SUM/AVG we need session_id & student_id (repeated)
    $bind = [];
    // first_term (session, student)
    $bind[] = $session_id; $bind[] = $student_id;
    // second_term
    $bind[] = $session_id; $bind[] = $student_id;
    // third_term
    $bind[] = $session_id; $bind[] = $student_id;
    // avg
    $bind[] = $session_id; $bind[] = $student_id;
    // finally subject ids
    $bind = array_merge($bind, $subject_ids);

    $stmt = $pdo->prepare($sql);
    $stmt->execute($bind);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($rows as $r) {
        $final_subject_data[] = $r;
    }
}

// ---------- Fetch Sessions, Terms, Classes for Filters ----------
$sessions = $pdo->query("SELECT * FROM sessions ORDER BY name DESC")->fetchAll(PDO::FETCH_ASSOC);
$terms = $pdo->query("SELECT * FROM terms ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
$classes = $pdo->query("SELECT * FROM classrooms ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);

// For the performance chart (reuse $term_grades labels and totals)
$chart_labels = array_values(array_map(fn($g) => $g['subject_name'] ?? '—', $term_grades));
$chart_data = array_values(array_map(fn($g) => floatval($g['total'] ?? 0), $term_grades));
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/png" sizes="32x32" href="BCA-Logo.png">
<link rel="icon" type="image/png" sizes="16x16" href="BCA-Logo.png">
<title>Student Portal - Bethany Christian Academy</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
<link href="major.css" rel="stylesheet">
<style>
.sidebar { background: linear-gradient(135deg,#007bff 0%,#0056b3 100%); color:white; min-height:100vh; padding:0; }
.sidebar .nav-link { color:white; padding:1rem 1.5rem; border-left:4px solid transparent; }
.sidebar .nav-link:hover, .sidebar .nav-link.active { background: rgba(255,255,255,0.1); border-left-color:white; }
.grade-progress { height:10px; }
.stat-card { transition: transform .2s; } .stat-card:hover{ transform: translateY(-2px); }
@media print {
    @page { size: A4 portrait; margin: 20mm; }
    nav, .btn, .footer, .tab-content > .tab-pane:not(.active), .nav-tabs, .navbar, .tab-buttons { display: none !important; }
    body { background: #fff;
         -webkit-print-color-adjust: exact !important; 
         print-color-adjust: exact !important; }
    .print-header { display: block !important; }
    .card, .card-body { border: none !important; 
        box-shadow: none !important; }
}
</style>
<link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
</head>
<body>
<div class="container-fluid">
<div class="row">
    <!-- Sidebar -->
    <div class="col-md-3 col-lg-2 sidebar">
        <div class="d-flex flex-column p-3">
            <div class="text-center mb-4">
                <a href="../"><img src="BCA-Logo.png" alt="BCA LOGO" height="100px" width="100px"></a>
                <h5>Bethany Christian Academy</h5>
                <h5>Student Portal</h5>
            </div>
            <ul class="nav nav-pills flex-column">
                <li class="nav-item"><a class="nav-link active" href="#dashboard" data-bs-toggle="tab"><i class="fas fa-tachometer-alt me-2"></i>Dashboard</a></li>
                <li class="nav-item"><a class="nav-link" href="mail/dashboard.php"><i class="fas fa-envelope me-2"></i>Mail</a></li>
                <li class="nav-item"><a class="nav-link" href="#users" data-bs-toggle="tab"><i class="fas fa-users me-2"></i>Users</a></li>
                <li class="nav-item"><a class="nav-link" href="#grades" data-bs-toggle="tab"><i class="fas fa-chart-bar me-2"></i>Grades</a></li>
                <li class="nav-item"><a class="nav-link" href="#final" data-bs-toggle="tab"><i class="fas fa-chart-line me-2"></i>Final Result</a></li>
                <li class="nav-item"><a class="nav-link" href="#performance" data-bs-toggle="tab"><i class="fas fa-trophy me-2"></i>Performance</a></li>
                <li class="nav-item"><a class="nav-link" href="#idcard" data-bs-toggle="tab"><i class="fas fa-id-card me-2"></i>Id card</a></li>
                <li class="nav-item"><a class="nav-link" href="/BCA/student-grades-management-system/CBT-EXAM/student/available_exams.php"><i class="fas fa-desktop me-2"></i>CBT Exams</a></li>
                <li class="nav-item"><a class="nav-link" href="logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
            </ul>
            <button id="themeToggle" class="toggle-btn"><i class="fas fa-moon"></i> Dark Mode</button>
            <script src="dark.js"></script>
        </div>
    </div>

    <!-- Main Content -->
    <div class="col-md-9 col-lg-10 ms-sm-auto px-4 py-4">
        <div class="tab-content">

        <!-- Dashboard Tab -->
        <div class="tab-pane fade show active" id="dashboard">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2>Student Dashboard</h2>
                <div class="d-flex align-items-center mb-4 p-3 bg-white rounded shadow-sm border">
                    <div class="me-3">
                        <img src="<?= htmlspecialchars($photo_src) ?>" alt="Student Photo" class="rounded-circle border" style="width:90px;height:90px;object-fit:cover;">
                    </div>
                    <div>
                        <h5 class="mb-1 fw-bold text-primary"><?= htmlspecialchars($student_name) ?></h5>
                        <p class="mb-0 text-muted small">Student ID: <?= htmlspecialchars($student_id) ?></p>
                    </div>
                </div>
            </div>

            <!-- Statistics Cards -->
            <div class="row mb-4">
                <div class="col-md-3">
                    <div class="card stat-card bg-primary text-white">
                        <div class="card-body d-flex justify-content-between align-items-center">
                            <div><h4><?= $total_grades ?></h4><p>Total Grades</p></div>
                            <i class="fas fa-list-alt fa-2x"></i>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card stat-card bg-success text-white">
                        <div class="card-body d-flex justify-content-between align-items-center">
                            <div><h4><?= number_format($average_grade, 2) ?></h4><p>Average Grade</p></div>
                            <i class="fas fa-calculator fa-2x"></i>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card stat-card bg-warning text-dark">
                        <div class="card-body d-flex justify-content-between align-items-center">
                            <div><h4><?= htmlspecialchars(calculateGradePoint($average_grade)) ?></h4><p>Overall Grade</p></div>
                            <i class="fas fa-award fa-2x"></i>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card stat-card bg-success text-light">
                        <div class="card-body d-flex justify-content-between align-items-center">
                            <div><h4><?= count($student_subjects) ?></h4><p>Subjects Offered</p></div>
                            <i class="fas fa-book fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header"><h5>Grade Distribution</h5></div>
                        <div class="card-body">
                            <?php foreach($grade_distribution as $letter => $count):
                                $percentage = $total_grades > 0 ? ($count / $total_grades) * 100 : 0;
                                $color_class = match($letter) {
                                    'A1' => 'bg-success',
                                    'A2' => 'bg-info',
                                    'B1' => 'bg-primary',
                                    'B2' => 'bg-warning',
                                    'UC' => 'bg-secondary',
                                    'LC' => 'bg-warning',
                                    'P'  => 'bg-danger',
                                    'F'  => 'bg-dark',
                                    default => 'bg-secondary'
                                };
                            ?>
                            <div class="mb-3">
                                <div class="d-flex justify-content-between mb-1">
                                    <span>Grade <?= htmlspecialchars($letter) ?></span>
                                    <span><?= (int)$count ?> (<?= number_format($percentage,1) ?>%)</span>
                                </div>
                                <div class="progress grade-progress">
                                    <div class="progress-bar <?= $color_class ?>" style="width: <?= $percentage ?>%"></div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header"><h5>Recent Grades</h5></div>
                        <div class="card-body">
                            <?php foreach(array_slice($term_grades, 0, 5) as $grade):
                                $letter = $grade['grade'] ?? calculateGradePoint($grade['total'] ?? 0);
                                $color = getGradeColor($letter);
                            ?>
                            <div class="d-flex justify-content-between align-items-center mb-3 p-2 border rounded">
                                <div>
                                    <h6 class="mb-0"><?= htmlspecialchars($grade['subject_name'] ?? '—') ?></h6>
                                    <small class="text-muted"><?= htmlspecialchars($grade['classroom_name'] ?? '—') ?></small>
                                </div>
                                <div class="text-end">
                                    <span class="badge bg-<?= $color ?>"><?= htmlspecialchars($letter) ?></span>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- VIEW USERS (unchanged) -->
        <div class="tab-pane fade" id="users">
            <h2 class="mb-4">View Users</h2>
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5>All Users</h5>
                    <input type="text" id="userSearch" class="form-control form-control-sm w-50" placeholder="Search users...">
                </div>
                <div class="card-body">
                    <div class="table-responsive" id="userTableContainer"></div>
                </div>
            </div>
        </div>

        <!-- Grades Tab -->
        <div class="tab-pane fade" id="grades">
            <h2 class="mb-4">My Terminal Result</h2>

            <!-- Filter Form -->
            <form method="GET" class="d-flex mb-3 gap-2">
                <select name="session_id" class="form-select w-auto">
                    <?php foreach($sessions as $s): 
                        $selected = ($session_id == $s['id']) ? 'selected' : ''; ?>
                        <option value="<?= $s['id'] ?>" <?= $selected ?>><?= htmlspecialchars($s['name']) ?></option>
                    <?php endforeach; ?>
                </select>

                <select name="term_id" class="form-select w-auto">
                    <?php foreach($terms as $t):
                        $selected = ($term_id == $t['id']) ? 'selected' : ''; ?>
                        <option value="<?= $t['id'] ?>" <?= $selected ?>><?= htmlspecialchars($t['name']) ?></option>
                    <?php endforeach; ?>
                </select>

                <select name="class_id" class="form-select w-auto" disabled>
                    <option value="">All Classes</option>
                    <?php foreach($classes as $c):
                        $selected = ($class_id == $c['id']) ? 'selected' : ''; ?>
                        <option value="<?= $c['id'] ?>" <?= $selected ?>><?= htmlspecialchars($c['name']) ?></option>
                    <?php endforeach; ?>
                </select>

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

            <div class="card">
                <div class="card-body table-responsive" id="print-area">
                    <!-- Print Header (moved outside table for valid HTML) -->
                    <div class="print-header text-center mb-4" style="display:none;">
                        <img src="BCA-Logo.png" alt="School Logo" style="height:90px; margin-bottom:10px;">
                        <h2 class="fw-bold mb-0">Bethany Christian Academy</h2>
                        <p class="mb-0 small">Barkin Ladi, Plateau State, Nigeria</p>
                        <p class="mb-1 small">Phone: +234 812 177 1300 | Email: info.bcagcmnigeria@gmail.com</p>
                        <h4 class="fw-bold">STUDENT TERMINAL RESULT</h4>
                    </div>

                    <?php if ($no_subjects_message): ?>
                        <div class="alert alert-warning"><?= htmlspecialchars($no_subjects_message) ?></div>
                    <?php elseif (empty($term_grades)): ?>
                        <div class="alert alert-info">No recorded grades for the selected filters.</div>
                    <?php else: ?>
                        <div class="d-flex justify-content-end mb-2">
                            <button class="btn btn-outline-primary btn-sm" onclick="printResult()">🖨️ Print Result</button>
                        </div>

                        <!-- Student info card -->
                        <div class="card mb-3 p-3">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <p class="mb-1"><strong>Student Name:</strong> <?= htmlspecialchars($student_name) ?></p>
                                    <p class="mb-1"><strong>Date Of Birth:</strong> <?= $student_info['date_of_birth'] ?></p>
                                    <p class="mb-1"><strong>Class:</strong> <?= htmlspecialchars($student_class ?? '—') ?></p>
                                    <p class="mb-1"><strong>Session:</strong> <?= htmlspecialchars($active_session['name'] ?? '—') ?></p>
                                    <p class="mb-0"><strong>Term:</strong> <?= htmlspecialchars($active_term['name'] ?? '—') ?></p>
                                </div>
                                <div>
                                    <img src="<?= $photo_src ?>"
                                        alt="Student Photo"
                                        class="img-thumbnail rounded"
                                        style="width:150px; height:150px; object-fit:cover;">
                                </div>
                            </div>
                        </div>

                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>Subject</th><th>Class</th><th>Note1</th><th>Ass1</th><th>Test1</th>
                                    <th>Note2</th><th>Ass2</th><th>Test2</th><th>Exam</th><th>Total</th><th>Grade</th><th>Teacher</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($term_grades as $grade):
                                    $letter = $grade['grade'] ?? calculateGradePoint($grade['total'] ?? 0);
                                    $color = getGradeColor($letter);
                                ?>
                                <tr>
                                    <td><?= htmlspecialchars($grade['subject_name'] ?? '—') ?></td>
                                    <td><?= htmlspecialchars($grade['classroom_name'] ?? '—') ?></td>
                                    <td><?= htmlspecialchars($grade['first_note'] ?? '—') ?></td>
                                    <td><?= htmlspecialchars($grade['first_ass'] ?? '—') ?></td>
                                    <td><?= htmlspecialchars($grade['first_test'] ?? '—') ?></td>
                                    <td><?= htmlspecialchars($grade['second_note'] ?? '—') ?></td>
                                    <td><?= htmlspecialchars($grade['second_ass'] ?? '—') ?></td>
                                    <td><?= htmlspecialchars($grade['second_test'] ?? '—') ?></td>
                                    <td><?= htmlspecialchars($grade['exam'] ?? '—') ?></td>
                                    <td><?= htmlspecialchars($grade['total'] ?? '—') ?></td>
                                    <td><span class="badge bg-<?= $color ?>"><?= htmlspecialchars($letter) ?></span></td>
                                    <td><?= htmlspecialchars(trim(($grade['teacher_first'] ?? '').' '.($grade['teacher_last'] ?? ''))) ?></td>
                                </tr>
                                <?php endforeach; ?>

                                <?php
                                // Calculate overall average for this term
                                $total_score_sum = 0;
                                $subject_count = 0;
                                foreach ($term_grades as $g) {
                                    if (isset($g['total'])) {
                                        $total_score_sum += $g['total'];
                                        $subject_count++;
                                    }
                                }
                                $overall_average = ($subject_count > 0) ? number_format($total_score_sum / $subject_count, 2) : '—';
                                ?>
                                <tr class="fw-bold bg-light">
                                    <td colspan="9" class="text-end">Overall Average:</td>
                                    <td><?= $overall_average ?></td>
                                    <td colspan="2"></td>
                                </tr>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Final Results Tab -->
        <div class="tab-pane fade" id="final">
            <h2 class="mb-4">End of Session Result (<?= htmlspecialchars($active_session['name'] ?? '') ?>)</h2>
            <div class="card table-responsive" id="print-area-final">
                <div class="d-flex justify-content-end mb-2">
                    <button class="btn btn-outline-primary btn-sm" onclick="printResultFinal()">🖨️ Print Result</button>
                </div>

                <!-- Print Header (moved) -->
                <div class="print-header text-center mb-4" style="display:none;">
                    <img src="BCA-Logo.png" alt="School Logo" style="height:90px; margin-bottom:10px;">
                    <h2 class="fw-bold mb-0">Bethany Christian Academy</h2>
                    <p class="mb-0 small">Barkin Ladi, Plateau State, Nigeria</p>
                    <p class="mb-1 small">Phone: +234 812 177 1300 | Email: info.bcagcmnigeria@gmail.com</p>
                    <h4 class="fw-bold">STUDENT FINAL RESULT</h4>
                </div>

                <div class="card mb-3 p-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="mb-1"><strong>Student Name:</strong> <?= htmlspecialchars($student_name) ?></p>
                            <p class="mb-1"><strong>Date Of Birth:</strong> <?= $student_info['date_of_birth'] ?></p>
                            <p class="mb-1"><strong>Class:</strong> <?= htmlspecialchars($student_class ?? '—') ?></p>
                            <p class="mb-1"><strong>Session:</strong> <?= htmlspecialchars($active_session['name'] ?? '—') ?></p>
                        </div>
                        <div>
                            <img src="<?= $photo_src ?>"
                                alt="Student Photo"
                                class="img-thumbnail rounded"
                                style="width:150px; height:150px; object-fit:cover;">
                        </div>
                    </div>
                </div>

                <table class="table table-striped">
                    <thead class="table-dark">
                        <tr>
                            <th>Subject</th><th>1st Term</th><th>2nd Term</th><th>3rd Term</th><th>Average Total</th><th>Grade</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $grand_total = 0; $subject_count = 0;
                        foreach($final_subject_data as $r):
                            $avg = (float)($r['average_score'] ?? 0);
                            $letter_grade = calculateGradePoint($avg);
                            $color = getGradeColor($letter_grade);
                            $grand_total += $avg; $subject_count++;
                        ?>
                        <tr>
                            <td><?= htmlspecialchars($r['subject_name']) ?></td>
                            <td><?= htmlspecialchars($r['first_term'] ?? 0) ?></td>
                            <td><?= htmlspecialchars($r['second_term'] ?? 0) ?></td>
                            <td><?= htmlspecialchars($r['third_term'] ?? 0) ?></td>
                            <td><?= htmlspecialchars($r['average_score'] ?? 0) ?></td>
                            <td><span class="badge bg-<?= $color ?>"><?= htmlspecialchars($letter_grade) ?></span></td>
                        </tr>
                        <?php endforeach; ?>

                        <?php if ($subject_count > 0): ?>
                        <tr class="fw-bold bg-light">
                            <td class="text-end" colspan="4">Overall Average:</td>
                            <td><?= number_format($grand_total / $subject_count,2) ?></td>
                            <td><?= htmlspecialchars(calculateGradePoint($grand_total / $subject_count)) ?></td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Performance Chart Tab -->
        <div class="tab-pane fade" id="performance">
            <h2 class="mb-4">Performance Overview</h2>
            <!-- Chart Filter -->
            <form method="GET" class="d-flex mb-3 gap-2">
                <input type="hidden" name="class_id" value="<?= htmlspecialchars($class_id) ?>">
                <select name="session_id" class="form-select w-auto">
                    <?php foreach($sessions as $s): 
                        $selected = ($session_id == $s['id']) ? 'selected' : ''; ?>
                        <option value="<?= $s['id'] ?>" <?= $selected ?>><?= htmlspecialchars($s['name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="term_id" class="form-select w-auto">
                    <?php foreach($terms as $t):
                        $selected = ($term_id == $t['id']) ? 'selected' : ''; ?>
                        <option value="<?= $t['id'] ?>" <?= $selected ?>><?= htmlspecialchars($t['name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <button class="btn btn-primary" type="submit">Filter Chart</button>
            </form>

            <canvas id="performanceChart" height="120"></canvas>
            <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
            <script>
                const ctx = document.getElementById('performanceChart').getContext('2d');
                const chartData = {
                    labels: <?= json_encode($chart_labels) ?>,
                    datasets: [{
                        label: 'Total Score',
                        data: <?= json_encode($chart_data) ?>,
                        /* Do not hardcode colors if you plan to theme later */
                        backgroundColor: 'rgba(0,123,255,0.5)',
                        borderColor: 'rgba(0,123,255,1)',
                        borderWidth: 1
                    }]
                };
                new Chart(ctx, { type:'bar', data:chartData, options:{ responsive:true, plugins:{legend:{display:false}}, scales:{y:{beginAtZero:true}} } });
            </script>
        </div>

        <div class="tab-pane fade" id="idcard">
                <div class="idcard row mb-4 w-100">
                    <h1>Student ID card</h1>
                    <?php if ($student_id): ?>
                        <style>
                        /* Much Larger PVC ID Card */
                        .idcard-large {
                            width: 640px; 
                            height: 400px;
                            border-radius: 18px;
                            overflow: hidden;
                            position: relative;
                            background: #ffffff;
                            border: 2px solid #0a3d62;
                        }
                        /* Security watermark */
                        .idcard-watermark {
                            position: absolute;
                            inset: 0;
                            opacity: 0.06;
                            display: flex;
                            justify-content: center;
                            align-items: center;
                            font-size: 110px;
                            font-weight: 900;
                            pointer-events: none;
                            transform: rotate(-25deg);
                            color: #000;
                        }
                        .topper{
                            padding: 20px;
                        }
                        /* Print only card */
                        @media print {
                            body * {
                                visibility: hidden;
                            }
                            .print-area, .print-area * {
                                visibility: visible;
                            }
                            /* Keep both cards on the same printed page */
                            .print-area {
                                position: absolute;
                                left: 0;
                                top: 0;
                                width: 100%;
                                display: flex;
                                justify-content: center; /* center on page */
                                gap: 40px; /* spacing between front/back cards */
                                flex-wrap: nowrap; /* prevent wrapping to next line */
                            }
                            .idcard-large {
                                page-break-inside: avoid; /* prevent splitting card across pages */
                            }
                        }
                        </style>
                        <div class="print-area d-flex justify-content-between align-items-center mb-2">
                        <!-- FRONT SIDE (ENLARGED) -->
                        <div class="idcard-large col-auto">
                            <div class="topper d-flex bg-secondary justify-content-center align-items-center">
                                <div class="school-logo">
                                    <img src="BCA-Logo.png" width="50px" height="50px">
                                </div>
                                <h2>BETHANY CHRISTIAN ACADEMY</h2>
                            </div>
                            <div class="idcard-watermark">BETHANY CHRISTIAN ACADEMY</div>
                            <div class="d-flex h-70 p-4">
                                <!-- Photo -->
                                <div class="d-flex flex-column justify-content-center align-items-center" style="width: 40%;">
                                        <?php if (!empty($student_info['photo'])): ?>
                                            <img src="data:image/jpeg;base64,<?php echo base64_encode($student_info['photo']); ?>" 
                                                alt="User Photo"
                                                style="width:180px; height:180px; border-radius: 5px; object-fit:cover;">
                                        <?php else: ?>
                                            <img src="user.png"
                                                alt="Default Photo"
                                                style="width:180px; height:180px; border-radius: 5px; object-fit:cover;">
                                        <?php endif; ?>
                                </div>
                                <!-- Details -->
                                <div class="ps-4 d-flex flex-column justify-content-center " style="width: 60%;">
                                    <h2 class="fs-5 mb-2">
                                       <strong>Name:</strong> <?= $student_info['first_name'] . ' ' . $student_info['last_name'] ?>
                                    </h2>
                                    <p class="fs-5 mb-2">
                                        <strong>DUID:</strong> <?= htmlspecialchars($student_id) ?>
                                    </p> 
                                    <p class="fs-5 mb-2">
                                        <strong>Class:</strong> <?= $student_info['current_class'] ?>
                                    </p>
                                    <p class="fs-5 mb-2">
                                        <strong>Date Of birth:</strong> <?= $student_info['date_of_birth'] ?>
                                    </p>
                                    <p class="fs-5 mb-2">
                                        <strong>Current Year:</strong> <?= htmlspecialchars($active_session['name'] ?? '—') ?>
                                    </p>
                                    <p class="fw-bold text-primary">
                                        STUDENT IDENTITY CARD
                                    </p>
                                </div>
                            </div>
                        </div>
                        <!-- BACK SIDE (ENLARGED) -->
                        <div class="idcard-large shadow-lg">
                            <div class="idcard-watermark">BETHANY CHRISTIAN ACADEMY</div>
                            <div class="p-4">
                                <h3 class="fw-bold text-primary mb-3">School Information</h3>
                                <p class="fs-5 mb-2"><strong>School:</strong> Bethany Christian Academy</p>
                                <p class="fs-5 mb-2"><strong>Address:</strong> KM2 Bokkos Road Barkin Ladi, Plateau State.</p>
                                <p class="fs-5 mb-2"><strong>Phone:</strong> +234 123 456 1234</p>
                                <p class="fs-5 mb-2"><strong>Email:</strong> contact@bca.edu.ng</p>
                                <hr>
                                <p class="fs-6 text-muted mt-3">
                                    This card is the property of the Bethany Christian Academy.  
                                    If found, please return to the school administration office.
                                </p>
                            </div>
                        </div>
                        </div>
                        <!-- Print Button -->
                        <div class="mt-4">
                            <button class="btn btn-primary btn-lg" onclick="window.print()">Print ID Card</button>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
                                <!-- Footer -->
                    <footer class="mt-5">
                        <div class="container py-3 d-flex flex-column flex-md-row justify-content-between align-items-center">
                            <div>
                                &copy; <?= date('Y') ?> Bethany Christian Academy *Designed by Peter Danye. All rights reserved.
                            </div>
                            <div>
                                <a href="#" class="text-decoration-none me-3">Privacy Policy</a>
                                <a href="#" class="text-decoration-none">Terms of Service</a>
                            </div>
                        </div>
                    </footer>
        </div>
        
        <!-- tab-content -->
    </div> <!-- main content -->
</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// simple user search loader
function loadUsers(query = '') {
    fetch('search_users.php?q=' + encodeURIComponent(query))
        .then(r => r.text())
        .then(html => document.getElementById('userTableContainer').innerHTML = html);
}
document.getElementById('userSearch')?.addEventListener('keyup', e => loadUsers(e.target.value));
loadUsers();

function printResult() {
    const printContents = document.getElementById("print-area").innerHTML;
    const originalContents = document.body.innerHTML;
    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;
}

function printResultFinal() {
    const printContents = document.getElementById("print-area-final").innerHTML;
    const originalContents = document.body.innerHTML;
    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;
}
</script>
</body>
</html>
