<?php
declare(strict_types=1);

$PAGE_TITLE = 'Exam Marks';
$ACTIVE = 'exam_marks';

require_once __DIR__ . '/../includes/student_auth.php';
require_once __DIR__ . '/../includes/db.php';

$mysqli = $mysqli ?? ($conn ?? null);
if (!$mysqli instanceof mysqli) die('DB connection failed');
$mysqli->set_charset('utf8mb4');

function h($v): string {
    return htmlspecialchars((string)$v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

$studentId = (int)($_SESSION['student_id'] ?? 0);

$st = $mysqli->prepare("
    SELECT id, full_name, center_reg_no, reference_no, nic_passport
    FROM studentss
    WHERE id = ?
    LIMIT 1
");
$st->bind_param('i', $studentId);
$st->execute();
$student = $st->get_result()->fetch_assoc();
$st->close();

if (!$student) {
    header('Location: /elms/student/login.php');
    exit;
}

$centerReg = trim((string)($student['center_reg_no'] ?? ''));
$refNo     = trim((string)($student['reference_no'] ?? ''));

$marks = [];

$sql = "
    SELECT *
    FROM (
        SELECT
            r.id,
            r.score,
            r.total,
            r.grade,
            r.status,
            r.module_name,
            r.reference_no,
            r.date_taken,
            e.title AS exam_title,
            e.course_name,
            e.unit_exam,
            e.pass_mark,
            ROW_NUMBER() OVER (
                PARTITION BY e.unit_exam
                ORDER BY r.date_taken DESC, r.id DESC
            ) AS rn
        FROM results r
        LEFT JOIN exams e ON e.id = r.exam_id
        WHERE (r.reference_no = ? OR r.reference_no = ?)
          AND (
                LOWER(e.title) LIKE '%final%'
                OR LOWER(e.unit_exam) LIKE '%final%'
                OR LOWER(r.module_name) LIKE '%final%'
              )
    ) x
    WHERE x.rn = 1
    ORDER BY x.date_taken DESC, x.id DESC
";

$st = $mysqli->prepare($sql);
$st->bind_param('ss', $centerReg, $refNo);
$st->execute();
$marks = $st->get_result()->fetch_all(MYSQLI_ASSOC);
$st->close();

require_once __DIR__ . '/../includes/student_layout_top.php';
?>

<style>
.exam-marks-card{
    background:#fff;
    border:1px solid #e5e7eb;
    border-radius:18px;
    box-shadow:0 10px 28px rgba(15,23,42,.045);
    overflow:hidden;
}
.exam-marks-head{
    padding:18px 20px;
    border-bottom:1px solid #e5e7eb;
}
.exam-marks-title{
    margin:0;
    color:#12386f;
    font-weight:950;
}
.exam-marks-sub{
    color:#6b7280;
    font-size:.86rem;
    margin-top:4px;
}
.exam-table th{
    background:#f8fafc;
    color:#475569;
    font-size:12px;
    text-transform:uppercase;
    letter-spacing:.04em;
}
.exam-score{
    font-weight:950;
    color:#034ea2;
}
</style>

<div class="exam-marks-card">
    <div class="exam-marks-head">
        <h2 class="exam-marks-title">My Exam Marks</h2>
        <div class="exam-marks-sub">
            <?= h($student['full_name'] ?? '') ?> · <?= h($centerReg ?: $refNo) ?>
        </div>
    </div>

    <div class="p-3">
        <div class="table-responsive">
            <table class="table table-hover align-middle exam-table mb-0">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Course</th>
                        <th>Exam / Unit</th>
                        <th>Score</th>
                        <th>Grade</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!$marks): ?>
                    <tr>
                        <td colspan="6" class="text-center text-muted py-5">
                            No exam marks found.
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($marks as $m): ?>
                        <?php
                        $status = (string)($m['status'] ?? '');
                        $badge = strtolower($status) === 'fail' ? 'danger' : 'success';
                        ?>
                        <tr>
                            <td><?= h(!empty($m['date_taken']) ? date('d M Y', strtotime((string)$m['date_taken'])) : '—') ?></td>
                            <td><?= h($m['course_name'] ?: '—') ?></td>
                            <td>
                                <strong><?= h($m['exam_title'] ?: ($m['unit_exam'] ?: 'Exam')) ?></strong>
                                <?php if (!empty($m['module_name'])): ?>
                                    <div class="small text-muted"><?= h($m['module_name']) ?></div>
                                <?php endif; ?>
                            </td>
                            <td class="exam-score">
                                <?= h($m['score']) ?>/<?= h($m['total']) ?>
                            </td>
                            <td>
                                <span class="badge bg-primary rounded-pill"><?= h($m['grade'] ?: '—') ?></span>
                            </td>
                            <td>
                                <span class="badge bg-<?= h($badge) ?> rounded-pill"><?= h($status ?: '—') ?></span>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/student_layout_bottom.php'; ?>