<?php
declare(strict_types=1);
session_start();
require_once '../config.php';
require_once __DIR__ . '/helpers.php';
if (!isset($_SESSION['parent_id'])) { header('Location: login.php'); exit; }
$conn = portalGetConnection();
if (!$conn instanceof mysqli) { http_response_code(500); exit('Database connection failed.'); }
$children = portalGetChildren($conn, (int) $_SESSION['parent_id']);
$childId = (int) ($_GET['child_id'] ?? ($children[0]['id'] ?? 0));
if ($childId > 0 && !portalParentOwnsStudent($conn, (int) $_SESSION['parent_id'], $childId)) {
    header('Location: dashboard.php?error=unauthorized');
    exit;
}
$student = $childId > 0 ? portalGetStudent($conn, $childId, (int) $_SESSION['parent_id']) : null;
$upcoming = [];
$past = [];
if ($student) {
    $className = (string) ($student['class'] ?? '');
    $stmt = $conn->prepare(
        "SELECT s.subject_name, ep.title, es.exam_date, es.start_time, es.venue, es.status
         FROM exam_schedules es
         INNER JOIN exam_papers ep ON ep.id = es.paper_id
         LEFT JOIN subjects s ON s.id = ep.subject_id
         WHERE es.class_name = ?
           AND es.status != 'cancelled'
           AND es.exam_date >= CURDATE()
         ORDER BY es.exam_date ASC, es.start_time ASC
         LIMIT 10"
    );
    $stmt->bind_param('s', $className);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) { $upcoming[] = $row; }
    $stmt->close();

    $pastStmt = $conn->prepare(
        "SELECT ep.title, ep.term, er.score, er.grade
         FROM exam_results er
         INNER JOIN exam_papers ep ON ep.id = er.paper_id
         WHERE er.student_id = ?
         ORDER BY er.submitted_at DESC"
    );
    $pastStmt->bind_param('i', $childId);
    $pastStmt->execute();
    $pastResult = $pastStmt->get_result();
    while ($row = $pastResult->fetch_assoc()) { $past[] = $row; }
    $pastStmt->close();
}
echo portalPageStart('Exams', 'reports', 'Exams');
?>
<?= portalChildSwitcher($children, $childId, 'exams.php') ?>
<div class="portal-card">
    <div class="portal-section-title">Upcoming Exam Schedule</div>
    <div class="portal-table-wrap">
        <table class="portal-table">
            <thead><tr><th>Subject</th><th>Paper Title</th><th>Date</th><th>Start</th><th>Venue</th><th>Status</th></tr></thead>
            <tbody>
            <?php foreach ($upcoming as $exam): ?>
                <tr>
                    <td><?= htmlspecialchars((string) ($exam['subject_name'] ?? '')) ?></td>
                    <td><?= htmlspecialchars((string) ($exam['title'] ?? '')) ?></td>
                    <td><?= htmlspecialchars((string) $exam['exam_date']) ?></td>
                    <td><?= htmlspecialchars(substr((string) $exam['start_time'], 0, 5)) ?></td>
                    <td><?= htmlspecialchars((string) ($exam['venue'] ?? '')) ?></td>
                    <td><?= htmlspecialchars((string) $exam['status']) ?></td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$upcoming): ?><tr><td colspan="6" class="portal-muted">No scheduled exams found.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<div class="portal-card">
    <div class="portal-section-title">Past Exam Results</div>
    <div class="portal-table-wrap">
        <table class="portal-table">
            <thead><tr><th>Paper Title</th><th>Score</th><th>Grade</th><th>Term</th></tr></thead>
            <tbody>
            <?php foreach ($past as $row): ?>
                <tr>
                    <td><?= htmlspecialchars((string) $row['title']) ?></td>
                    <td><?= htmlspecialchars((string) ($row['score'] ?? '')) ?></td>
                    <td><?= htmlspecialchars((string) ($row['grade'] ?? '')) ?></td>
                    <td><?= htmlspecialchars((string) ($row['term'] ?? '')) ?></td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$past): ?><tr><td colspan="4" class="portal-muted">No past results found.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<?= portalPageEnd('reports') ?>
