<?php

declare(strict_types=1);

require_once __DIR__ . '/../library/auth.php';

require_once __DIR__ . '/helpers/result-helper.php';

allow_roles(['admin', 'teacher']);

requirePostRequest();

verifyCsrfToken();

$school_id = (int) $_SESSION['school_id'];

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

$page_title = 'Student Marksheet';

/*
|--------------------------------------------------------------------------
| VALIDATE RESULT ID
|--------------------------------------------------------------------------
*/

$result_id = validateId(
    $_POST['result_id'] ?? 0
);

if ($result_id <= 0) {

    header('Location: result-view.php');

    exit;
}

/*
|--------------------------------------------------------------------------
| FETCH RESULT
|--------------------------------------------------------------------------
*/

$resultStmt = $pdo->prepare("
    SELECT

        er.*,

        s.name,
        s.photo,
		s.admission_no,

        sp.father_name,

        c.class_name,

        et.exam_name,

        ss.roll_no

    FROM exam_results er

    INNER JOIN students s
        ON s.id = er.student_id
        AND s.school_id = er.school_id

    INNER JOIN student_sessions ss
        ON ss.student_id = er.student_id
        AND ss.school_id = er.school_id
        AND ss.session_id = er.session_id
        AND ss.class_id = er.class_id

    LEFT JOIN student_parents sp
        ON sp.student_id = s.id
        AND sp.school_id = s.school_id
        AND sp.session_id = er.session_id

    INNER JOIN classes c
        ON c.id = er.class_id
        AND c.school_id = er.school_id

    INNER JOIN exam_types et
        ON et.id = er.exam_type_id
        AND et.school_id = er.school_id

    WHERE er.school_id = ?
    AND er.session_id = ?
    AND er.id = ?

    LIMIT 1
");

$resultStmt->execute([

    $school_id,
    $session_id,
    $result_id

]);

$result = $resultStmt->fetch(PDO::FETCH_ASSOC);

if (!$result) {

    header('Location: result-view.php');

    exit;
}
/*
|--------------------------------------------------------------------------
| FETCH EXAM TYPES
|--------------------------------------------------------------------------
*/

$examStmt = $pdo->prepare("
    SELECT
        id,
        exam_name
    FROM exam_types
    WHERE school_id = ?
    AND status = 'Active'
    ORDER BY display_order ASC
");

$examStmt->execute([$school_id]);

$examTypes = $examStmt->fetchAll(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| FETCH REPORT CARD DATA
|--------------------------------------------------------------------------
*/

$marksStmt = $pdo->prepare("
    SELECT

        s.id AS subject_id,
        s.name AS subject_name,
        s.subject_code,

        et.id AS exam_type_id,
        et.exam_name,

        em.marks_obtained

    FROM subjects s

    CROSS JOIN exam_types et

    LEFT JOIN exam_marks em
        ON em.subject_id = s.id
        AND em.exam_type_id = et.id
        AND em.student_id = ?
        AND em.school_id = ?
        AND em.session_id = ?

    WHERE s.school_id = ?
    AND et.school_id = ?
    AND et.status = 'Active'

    ORDER BY
        s.name ASC,
        et.display_order ASC
");

$marksStmt->execute([
    $result['student_id'],
    $school_id,
    $session_id,
    $school_id,
    $school_id
]);

$rows = $marksStmt->fetchAll(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| BUILD REPORT CARD ARRAY
|--------------------------------------------------------------------------
*/

$reportCard = [];

foreach ($rows as $row) {

    $subjectId = (int)$row['subject_id'];

    if (!isset($reportCard[$subjectId])) {

        $reportCard[$subjectId] = [
            'subject_name' => $row['subject_name'],
            'subject_code' => $row['subject_code'],
            'marks' => []
        ];
    }

    $reportCard[$subjectId]['marks'][$row['exam_name']]
        = $row['marks_obtained'];
}
/*
|--------------------------------------------------------------------------
| SCHOOL SETTINGS
|--------------------------------------------------------------------------
*/

$schoolStmt = $pdo->prepare("
    SELECT

        school_name,
        school_logo,
        school_address,
        school_phone

    FROM school_settings

    WHERE school_id = ?

    LIMIT 1
");

$schoolStmt->execute([$school_id]);

$school = $schoolStmt->fetch(PDO::FETCH_ASSOC);

require_once __DIR__ . '/../include/header.php';
require_once __DIR__ . '/../include/sidebar.php';
?>

<div class="content-wrapper">

    <section class="content-header">

        <div class="container-fluid">

            <div class="row mb-2">

                <div class="col-sm-6">

                    <h1>

                        Student Marksheet

                    </h1>

                </div>

                <div class="col-sm-6 text-right">

                    <button
                        onclick="window.print()"
                        class="btn btn-primary"
                    >

                        <i class="fas fa-print mr-1"></i>

                        Print

                    </button>

                </div>

            </div>

        </div>

    </section>

    <section class="content">

        <div class="container-fluid">

            <div class="card card-outline card-primary">

                <div class="card-body">

                    <!-- SCHOOL HEADER -->

                    <!-- REPORT CARD HEADER -->

<div class="report-card-header mb-4">

    <table width="100%">

        <tr>

            <td width="15%" class="text-center">

                <?php

                $logo = !empty($school['school_logo'])
                    ? WEB_ROOT . 'uploads/school/' . $school['school_logo']
                    : 'https://placehold.co/100x100?text=Logo';

                ?>

                <img
                    src="<?= htmlspecialchars($logo); ?>"
                    width="90"
                    alt="School Logo"
                >

            </td>

            <td width="70%" class="text-center">

                <h2 class="mb-1">

                    <?= htmlspecialchars($school['school_name'] ?? 'School'); ?>

                </h2>

                <div>

                    <?= htmlspecialchars($school['school_address'] ?? ''); ?>

                </div>

                <div>

                    <?= htmlspecialchars($school['school_phone'] ?? ''); ?>

                </div>

                <h3 class="mt-3">

                    ACADEMIC REPORT CARD

                </h3>

                <strong>

                    Session :
                    <?= htmlspecialchars($_SESSION['session_name'] ?? ''); ?>

                </strong>

            </td>

            <td width="15%" class="text-center">

                <?php

                $photo = !empty($result['photo'])
                    ? WEB_ROOT . 'student/uploads/' . $result['photo']
                    : 'https://placehold.co/100x100?text=Photo';

                ?>

                <img
                    src="<?= htmlspecialchars($photo); ?>"
                    width="90"
                    class="img-thumbnail"
                    alt="Student Photo"
                >

            </td>

        </tr>

    </table>

</div>

<!-- STUDENT DETAILS -->

<div class="card mb-4">

    <div class="card-header">

        <strong>

            Student Information

        </strong>

    </div>

    <div class="card-body p-0">

        <table class="table table-bordered mb-0">

            <tr>

                <th width="20%">Student Name</th>

                <td width="30%">
                    <?= htmlspecialchars($result['name']); ?>
                </td>

                <th width="20%">Admission No</th>

                <td width="30%">
                    <?= htmlspecialchars($result['admission_no'] ?? '-'); ?>
                </td>

            </tr>

            <tr>

                <th>Father Name</th>

                <td>
                    <?= htmlspecialchars($result['father_name'] ?? '-'); ?>
                </td>

                <th>Roll No</th>

                <td>
                    <?= htmlspecialchars($result['roll_no'] ?? '-'); ?>
                </td>

            </tr>

            <tr>

                <th>Class</th>

                <td>
                    <?= htmlspecialchars($result['class_name']); ?>
                </td>

                <th>Exam</th>

                <td>
                    <?= htmlspecialchars($result['exam_name']); ?>
                </td>

            </tr>

            <tr>

                <th>Percentage</th>

                <td>
                    <?= htmlspecialchars($result['percentage']); ?>%
                </td>

                <th>Rank</th>

                <td>
                    
                </td>

            </tr>

        </table>

    </div>

</div>

                    <!-- STUDENT INFO -->

                    <div class="row mb-4">

                        <div class="col-md-6">

                            <table class="table table-bordered">

                                <tr>

                                    <th width="40%">

                                        Student Name

                                    </th>

                                    <td>

                                        <?= htmlspecialchars($result['name']); ?>

                                    </td>

                                </tr>

                                <tr>

                                    <th>

                                        Father Name

                                    </th>

                                    <td>

                                        <?= htmlspecialchars($result['father_name'] ?? '-'); ?>

                                    </td>

                                </tr>

                                <tr>

                                    <th>

                                        Roll No

                                    </th>

                                    <td>

                                        <?= htmlspecialchars($result['roll_no']); ?>

                                    </td>

                                </tr>

                            </table>

                        </div>

                        <div class="col-md-6">

                            <table class="table table-bordered">

                                <tr>

                                    <th width="40%">

                                        Class

                                    </th>

                                    <td>

                                        <?= htmlspecialchars($result['class_name']); ?>

                                    </td>

                                </tr>

                                <tr>

                                    <th>

                                        Percentage

                                    </th>

                                    <td>

                                        <?= htmlspecialchars($result['percentage']); ?>%

                                    </td>

                                </tr>

                                <tr>

                                    <th>

                                        Rank

                                    </th>

                                    <td>

                                       

                                    </td>

                                </tr>

                            </table>

                        </div>

                    </div>

                    <!-- SCHOLASTIC AREA -->

<div class="card">

    <div class="card-header">

        <strong>

            Scholastic Performance

        </strong>

    </div>

    <div class="card-body p-0">

        <div class="table-responsive">

            <table class="table table-bordered mb-0">

                <thead>

                    <tr>

                        <th width="25%">

                            Subject

                        </th>

                        <?php foreach ($examTypes as $exam): ?>

                            <th class="text-center">

                                <?= htmlspecialchars($exam['exam_name']); ?>

                            </th>

                        <?php endforeach; ?>

                    </tr>

                </thead>

                <tbody>

                    <?php foreach ($reportCard as $subject): ?>

                        <tr>

                            <td>

                                <strong>

                                    <?= htmlspecialchars($subject['subject_name']); ?>

                                </strong>

                                <br>

                                <small class="text-muted">

                                    <?= htmlspecialchars($subject['subject_code']); ?>

                                </small>

                            </td>

                            <?php foreach ($examTypes as $exam): ?>

                                <td class="text-center">

                                    <?php

                                    $marks =
                                        $subject['marks'][$exam['exam_name']]
                                        ?? null;

                                    echo ($marks !== null && $marks !== '')
                                        ? $marks
                                        : '-';

                                    ?>

                                </td>

                            <?php endforeach; ?>

                        </tr>

                    <?php endforeach; ?>

                </tbody>

            </table>

        </div>

    </div>

</div>
<!-- RESULT SUMMARY -->

<div class="card mt-4">

    <div class="card-header">

        <strong>

            Result Summary

        </strong>

    </div>

    <div class="card-body">

        <div class="row">

            <div class="col-md-6">

                <table class="table table-bordered">

                    <tr>

                        <th width="50%">

                            Total Marks

                        </th>

                        <td>

                            <?= htmlspecialchars($result['total_marks']); ?>

                        </td>

                    </tr>

                    <tr>

                        <th>

                            Obtained Marks

                        </th>

                        <td>

                            <?= htmlspecialchars($result['obtained_marks']); ?>

                        </td>

                    </tr>

                    <tr>

                        <th>

                            Percentage

                        </th>

                        <td>

                            <?= htmlspecialchars($result['percentage']); ?>%

                        </td>

                    </tr>

                </table>

            </div>

            <div class="col-md-6">

                <table class="table table-bordered">

                    <tr>

                        <th width="50%">

                            Overall Grade

                        </th>

                        <td>

                            <?= htmlspecialchars($result['overall_grade']); ?>

                        </td>

                    </tr>

                    <tr>

                        <th>

                            Rank

                        </th>

                        <td>

                            <?= (int) $result['rank_position']; ?>

                        </td>

                    </tr>

                    <tr>

                        <th>

                            Result Status

                        </th>

                        <td>

                            <?php if ($result['result_status'] === 'Pass'): ?>

                                <span class="badge badge-success">

                                    PASS

                                </span>

                            <?php else: ?>

                                <span class="badge badge-danger">

                                    FAIL

                                </span>

                            <?php endif; ?>

                        </td>

                    </tr>

                </table>

            </div>

        </div>

    </div>

</div>

<!-- TEACHER REMARKS -->

<div class="card mt-4">

    <div class="card-header">

        <strong>

            Teacher Remarks

        </strong>

    </div>

    <div class="card-body">

        <?php if ($result['result_status'] === 'Pass'): ?>

            Promoted to next class.

        <?php else: ?>

            Needs improvement in weak subjects.

        <?php endif; ?>

    </div>

</div>
<!-- CERTIFICATION -->

<div class="card mt-4">

    <div class="card-header">

        <strong>

            Certification

        </strong>

    </div>

    <div class="card-body">

        <p class="mb-5">

            This is to certify that the above result has been prepared
            from the official records maintained by the school.

        </p>

        <div class="row text-center mt-5">

            <div class="col-4">

                <div style="padding-top:50px;border-top:1px solid #000;">

                    Class Teacher

                </div>

            </div>

            <div class="col-4">

                <div style="padding-top:50px;border-top:1px solid #000;">

                    Principal

                </div>

            </div>

            <div class="col-4">

                <div style="padding-top:50px;border-top:1px solid #000;">

                    Parent / Guardian

                </div>

            </div>

        </div>

    </div>

</div>

                </div>

            </div>

        </div>

    </section>

</div>

<link
    rel="stylesheet"
    href="assets/css/marksheet.css"
>

<?php require_once __DIR__ . '/../include/footer.php'; ?>