<?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.'); }

$conn->query("ALTER TABLE report_details ADD COLUMN IF NOT EXISTS is_published TINYINT(1) NOT NULL DEFAULT 0");

$conn->query("ALTER TABLE report_details ADD COLUMN IF NOT EXISTS published_at DATETIME NULL DEFAULT NULL");

$parentId = (int) $_SESSION['parent_id'];

$children = portalGetChildren($conn, $parentId);

$childId = (int) ($_GET['child_id'] ?? ($children[0]['id'] ?? 0));

if ($childId > 0 && !portalParentOwnsStudent($conn, $parentId, $childId)) {

    header('Location: dashboard.php?error=unauthorized');

    exit;

}

$student = $childId > 0 ? portalGetStudent($conn, $childId, $parentId) : null;

$term = trim((string) ($_GET['term'] ?? portalCurrentTerm($conn)));

$year = trim((string) ($_GET['academic_year'] ?? portalCurrentYear($conn)));

$scores = [];

$reportDetails = null;

$examResults = [];

$availableTerms = [];



if ($student) {

    $termStmt = $conn->prepare(

        "SELECT DISTINCT term, academic_year

         FROM report_details

         WHERE student_id = ? AND is_published = 1

         ORDER BY academic_year DESC, term ASC"

    );

    $termStmt->bind_param('i', $childId);

    $termStmt->execute();

    $termResult = $termStmt->get_result();

    while ($row = $termResult->fetch_assoc()) { $availableTerms[] = $row; }

    $termStmt->close();



    $scoreStmt = $conn->prepare(

        "SELECT sub.subject_name, sc.class_score, sc.exam_score, sc.total_score AS total, sc.grade, sc.remark

         FROM scores sc

         LEFT JOIN subjects sub ON sub.id = sc.subject_id

         WHERE sc.student_id = ? AND sc.term = ? AND sc.academic_year = ?

         ORDER BY sub.subject_name ASC"

    );

    $scoreStmt->bind_param('iss', $childId, $term, $year);

    $scoreStmt->execute();

    $scoreResult = $scoreStmt->get_result();

    while ($row = $scoreResult->fetch_assoc()) { $scores[] = $row; }

    $scoreStmt->close();



    $detailsStmt = $conn->prepare(

        "SELECT * FROM report_details WHERE student_id = ? AND term = ? AND academic_year = ? LIMIT 1"

    );

    $detailsStmt->bind_param('iss', $childId, $term, $year);

    $detailsStmt->execute();

    $reportDetails = $detailsStmt->get_result()->fetch_assoc();

    $detailsStmt->close();



    $examStmt = $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"

    );

    $examStmt->bind_param('i', $childId);

    $examStmt->execute();

    $examResult = $examStmt->get_result();

    while ($row = $examResult->fetch_assoc()) { $examResults[] = $row; }

    $examStmt->close();

}



echo portalPageStart('Reports', 'reports', 'Academic Reports');

?>

<?= portalChildSwitcher($children, $childId, 'reports.php') ?>

<div class="portal-card">

    <div class="portal-section-title">Term and Year</div>

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

        <input type="hidden" name="child_id" value="<?= $childId ?>">

        <select name="term" class="portal-select">

            <?php foreach ($availableTerms ?: [['term' => $term, 'academic_year' => $year]] as $item): ?>

                <option value="<?= htmlspecialchars((string) $item['term']) ?>" <?= ((string) $item['term'] === $term) ? 'selected' : '' ?>>

                    <?= htmlspecialchars((string) $item['term']) ?>

                </option>

            <?php endforeach; ?>

        </select>

        <select name="academic_year" class="portal-select">

            <?php foreach ($availableTerms ?: [['term' => $term, 'academic_year' => $year]] as $item): ?>

                <option value="<?= htmlspecialchars((string) $item['academic_year']) ?>" <?= ((string) $item['academic_year'] === $year) ? 'selected' : '' ?>>

                    <?= htmlspecialchars((string) $item['academic_year']) ?>

                </option>

            <?php endforeach; ?>

        </select>

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

    </form>

    <p class="portal-muted mt-3 mb-0">Scores below reflect your child's recorded results for the selected term.</p>

</div>



<div class="portal-card">

    <div class="portal-section-title">Report Card View</div>

    <div class="portal-table-wrap">

        <table class="portal-table">

            <thead><tr><th>Subject</th><th>Class Score</th><th>Exam Score</th><th>Total</th><th>Grade</th><th>Remark</th></tr></thead>

            <tbody>

            <?php foreach ($scores as $score): ?>

                <tr>

                    <td><?= htmlspecialchars((string) ($score['subject_name'] ?? '')) ?></td>

                    <td><?= htmlspecialchars((string) ($score['class_score'] ?? '')) ?></td>

                    <td><?= htmlspecialchars((string) ($score['exam_score'] ?? '')) ?></td>

                    <td><?= htmlspecialchars((string) ($score['total'] ?? '')) ?></td>

                    <td><?= htmlspecialchars((string) ($score['grade'] ?? '')) ?></td>

                    <td><?= htmlspecialchars((string) ($score['remark'] ?? '')) ?></td>

                </tr>

            <?php endforeach; ?>

            <?php if (!$scores): ?><tr><td colspan="6" class="portal-muted">No report scores found for this term.</td></tr><?php endif; ?>

            </tbody>

        </table>

    </div>



    <?php if ($reportDetails): ?>

        <div class="portal-kv mt-3">

            <div class="portal-kv-item"><div class="label">Attendance</div><div class="value"><?= htmlspecialchars((string) ($reportDetails['attendance'] ?? '')) ?></div></div>

            <div class="portal-kv-item"><div class="label">Conduct</div><div class="value"><?= htmlspecialchars((string) ($reportDetails['conduct'] ?? '')) ?></div></div>

            <div class="portal-kv-item"><div class="label">Interest</div><div class="value"><?= htmlspecialchars((string) ($reportDetails['interest'] ?? '')) ?></div></div>

            <div class="portal-kv-item"><div class="label">Teacher's Remark</div><div class="value"><?= htmlspecialchars((string) ($reportDetails['teacher_remark'] ?? $reportDetails['class_teacher_remark'] ?? '')) ?></div></div>

            <div class="portal-kv-item"><div class="label">Promoted To</div><div class="value"><?= htmlspecialchars((string) ($reportDetails['promoted_to'] ?? '')) ?></div></div>

            <div class="portal-kv-item"><div class="label">Closing / Reopening</div><div class="value"><?= htmlspecialchars((string) ($reportDetails['closing_date'] ?? '')) ?> / <?= htmlspecialchars((string) ($reportDetails['reopening_date'] ?? '')) ?></div></div>

        </div>

        <div class="mt-3">

            <strong>Signatures</strong>

            <div class="portal-muted small">Class Teacher | Headteacher | Director</div>

        </div>

    <?php endif; ?>



    <div class="mt-3">

        <?php

        $isPublished = !empty($reportDetails['is_published']);

        if ($isPublished): ?>

            <a class="portal-btn-primary d-inline-block"

               href="download_report.php?student_id=<?= $childId ?>&term=<?= urlencode($term) ?>&academic_year=<?= urlencode($year) ?>"

               target="_blank">

               &#x2913; Download Report Card PDF

            </a>

        <?php elseif ($scores || $reportDetails): ?>

            <div class="portal-muted small" style="padding:10px 14px;background:#fff8e1;border-radius:8px;border-left:4px solid #f59e0b;">

                &#x23F3; Report card not yet released &mdash; your school will notify you when it is available to download.

            </div>

        <?php else: ?>

            <div class="portal-muted small">No report card generated for this term yet.</div>

        <?php endif; ?>

    </div>

</div>



<div class="portal-card">

    <div class="portal-section-title">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 ($examResults as $result): ?>

                <tr>

                    <td><?= htmlspecialchars((string) $result['title']) ?></td>

                    <td><?= htmlspecialchars((string) ($result['score'] ?? '')) ?></td>

                    <td><?= htmlspecialchars((string) ($result['grade'] ?? '')) ?></td>

                    <td><?= htmlspecialchars((string) ($result['term'] ?? '')) ?></td>

                </tr>

            <?php endforeach; ?>

            <?php if (!$examResults): ?><tr><td colspan="4" class="portal-muted">No standalone exam results found.</td></tr><?php endif; ?>

            </tbody>

        </table>

    </div>

</div>

<?= portalPageEnd('reports') ?>

