<?php
date_default_timezone_set('Africa/Lagos'); // Replace with your desired time zone
include('includes/session.php');
error_reporting(0);
include('includes/dbconnection.php');
require_once __DIR__ . '/includes/session_term_helper.php';
// Fetch current session and term (with gap/fallback support)
$stResult = resolveCurrentSessionTerm($con);
$currentSessionId   = $stResult['session_id'];
$currentSessionName = $stResult['session_name'];
$currentTermId      = $stResult['term_id'];
$currentTermName    = $stResult['term_name'];
// OTP verification removed - access is controlled by payment check in verify_email_otp.php

$student_id = $_SESSION['student_id'];

// $session_id = $_POST['session_id'];
// $term_id = $_POST['term_id'];
// $class = $_POST['class'];

$session_id = $_GET['session_id'];
$term_id = $_GET['term_id'];
$tabSessionID = $_GET['tab_id'];
$class = $_GET['class'];

$currentSessionId = $session_id;
$currentTermId = $term_id;

// Get selected names
$selected_session = mysqli_fetch_assoc(mysqli_query($con, "SELECT session_name FROM school_sessions WHERE id = '$session_id'"))['session_name'] ?? '';
$selected_term = mysqli_fetch_assoc(mysqli_query($con, "SELECT term_name FROM school_terms WHERE id = '$term_id'"))['term_name'] ?? '';

$currentSessionName = $selected_session;
$currentTermName = $selected_term;

// Fetch all sessions, terms, and student's result classes
$sessions = mysqli_query($con, "SELECT * FROM school_sessions ORDER BY id DESC");
$terms = mysqli_query($con, "SELECT * FROM school_terms");
$classes = mysqli_query($con, "SELECT DISTINCT class FROM results WHERE student_id = '$student_id'");


// Fetch student info
$student_sql = "SELECT * FROM students WHERE id = $student_id";
$student_result = $con->query($student_sql);
$student = $student_result->fetch_assoc();
$default_class = $student['class'];
$section = $student['section'];
$studentImage = "studentimages/" . htmlspecialchars($student['studentImage']);

// Fetch Psychomotor
$psychomotor_sql = "SELECT * FROM psychomotor WHERE student_id = $student_id AND term = '$selected_term' AND session ='$selected_session'";
$psychomotor_result = $con->query($psychomotor_sql);
$psychomotor = ($psychomotor_result && $psychomotor_result->num_rows > 0) ? $psychomotor_result->fetch_assoc() : [];

// Fetch Affective
$affective_sql = "SELECT * FROM affective WHERE student_id = $student_id AND term = '$selected_term' AND session ='$selected_session'";
$affective_result = $con->query($affective_sql);
$affective = ($affective_result && $affective_result->num_rows > 0) ? $affective_result->fetch_assoc() : [];

// 1. Get School Calendar for the term + session
$sqlCalendar = "
    SELECT c.resumption_date, c.closing_date
    FROM school_calendar c
    WHERE c.term_id = ? AND c.session_id = ?
    LIMIT 1
";
$stmtCalendar = $con->prepare($sqlCalendar);
$stmtCalendar->bind_param("ii", $currentTermId, $currentSessionId);
$stmtCalendar->execute();
$resCalendar = $stmtCalendar->get_result();
$calendar = $resCalendar->fetch_assoc();

// 2. Get all public holidays for this term + session
$holidayDates = [];
$sqlHolidays = "
    SELECT holiday_date 
    FROM public_holidays 
    WHERE term_id = ? AND session_id = ?
";
$stmtHoliday = $con->prepare($sqlHolidays);
$stmtHoliday->bind_param("ii", $currentTermId, $currentSessionId);
$stmtHoliday->execute();
$resHoliday = $stmtHoliday->get_result();
while ($row = $resHoliday->fetch_assoc()) {
    $holidayDates[] = $row['holiday_date'];
}

// 3. Calculate Total Open Days (weekdays excluding holidays)
$totalDays = 0;
if ($calendar) {
    $startDate = new DateTime($calendar['resumption_date']);
    $endDate = new DateTime($calendar['closing_date']);

    while ($startDate <= $endDate) {
        $dayOfWeek = $startDate->format("N"); // 1=Mon, 7=Sun
        $dateStr = $startDate->format("Y-m-d");

        if ($dayOfWeek < 6 && !in_array($dateStr, $holidayDates)) {
            $totalDays++;
        }
        $startDate->modify("+1 day");
    }
}

// 4. Count student's days present
$sql1 = "SELECT COUNT(*) AS total_attendance 
         FROM attendance 
         WHERE student_id = ? 
           AND term_id = ? 
           AND session_id = ? 
           AND status = 'Present'";
$stmt1 = $con->prepare($sql1);
$stmt1->bind_param("iii", $student_id, $currentTermId, $currentSessionId);
$stmt1->execute();
$res1 = $stmt1->get_result();
$totalAttendance = $res1->fetch_assoc()['total_attendance'] ?? 0;


// Get selected session and term
$selected_session_id = $_GET['session_id'];
$selected_term_id = $_GET['term_id'];



// Fetch all terms for the session, ordered correctly
$terms_sql = "SELECT id AS term_id, term_name FROM school_terms WHERE session_id = '$selected_session_id' ORDER BY id ASC";
$terms_result = $con->query($terms_sql);

$terms = [];
$term_order = [];
$term_names = [];


if ($terms_result && $terms_result->num_rows > 0) {
    while ($row = $terms_result->fetch_assoc()) {
        $terms[] = $row;
        $term_order[] = $row['term_id'];
        $term_names[$row['term_id']] = $row['term_name'];
    }
}

$current_term_index = array_search($selected_term_id, $term_order);

$previous_term_ids = [];

if ($current_term_index !== false) {
    for ($i = 0; $i < $current_term_index; $i++) {
        $previous_term_ids[] = $term_order[$i];
    }
}

$all_terms_to_fetch = array_merge($previous_term_ids, [$selected_term_id]);
$term_ids_in = implode(",", $all_terms_to_fetch);

$sql = "SELECT DATE(publish_datetime) AS publish_date 
FROM result_publish_schedule 
WHERE session_id = ? AND term_id = ? AND result_type = 'Endterm'";

$stmt = $con->prepare($sql);
$stmt->bind_param("ii", $session_id, $term_id);
$stmt->execute();
$result = $stmt->get_result();
$publish_date = 'N/A'; // Default value if no publish date is found
if ($row = $result->fetch_assoc()) {
    $publish_date = $row['publish_date'];
}


$results = [];  // Initialize it as an empty array to avoid "undefined" error
$total_score = 0;
$total_subjects = 0;
$mark_obtainable = 0;
$percentage = 0;
$average_score = 0;
$error_message = '';
if (isset($_GET['session_id'], $_GET['term_id'], $_GET['class'])) {
    // Initialize result variables
    // Check publish date first
// --- Integration of Publication Schedule Check ---

    if ($publish_date === 'N/A') {
        // 1. Publication Date Not Found
        $error_message = "Kindly note that the official date for the release of results has not been announced by the school.<br> You are advised to check back at a later time or contact the school administration for further clarification.";

    } elseif (strtotime(date('Y-m-d')) < strtotime($publish_date)) {
        // 2. Publication Date is in the Future

        // Note: Removed "Mid Term" based on previous discussion, keeping it generic ("Results")
        $error_message = "Results for " . $selected_term . " " . $selected_session . " session has not been published yet. Wait till " . date("l, jS F Y g:i A", strtotime($publish_date)) . ".";

    } else {

        // Fetch academic results

        $results_sql = "SELECT term_id, subject, test_score, test_score2, class_performance, weekly_assessment, exam_score, total_score,remarks,
     test_absent,test2_absent,class_performance_absent,weekly_assessment_absent,exam_absent
                FROM results 
                WHERE student_id = '$student_id' 
                AND session_id = '$selected_session_id' 
                AND term_id IN ($term_ids_in)
                AND class = '$class'
                AND status = 'Approved'";

        $results_result = $con->query($results_sql);

        $current_term_id = $term_id;

        $subjects_results = [];

        if ($results_result && $results_result->num_rows > 0) {
            while ($row = $results_result->fetch_assoc()) {
                $result_term_id = $row['term_id']; // actual row term
                $subject = $row['subject'];

                if (!isset($subjects_results[$subject])) {
                    $subjects_results[$subject] = [
                        'terms' => [] // store each term's scores here
                    ];
                }

                $subjects_results[$subject]['terms'][$result_term_id] = $row; // assign by term ID
            }

            // ✅ Calculate Total and Averages
            $total_subjects = count($subjects_results);
            $mark_obtainable = $total_subjects * 100;

            $current_term_id = $selected_term_id; // the term you want total for

            foreach ($subjects_results as $subject_data) {
                if (isset($subject_data['terms'][$current_term_id])) {
                    $score = $subject_data['terms'][$current_term_id]['total_score'];

                    // Treat absent or invalid as 0
                    if ($score === null || $score === '' || strtoupper($score) === 'AB') {
                        $score = 0;
                    }

                    $total_score += (int) $score;
                }
            }

            $percentage = $total_subjects ? round(($total_score / $mark_obtainable) * 100, 2) : 0;
            $average_score = $total_subjects ? round($total_score / $total_subjects, 2) : 0;
            $average_score = $total_subjects ? round($total_score / $total_subjects, 2) : 0;

        }
    }
    // Remark generator
    function generateRemark($percentage)
    {
        if ($percentage >= 75) {
            return 'Outstanding Performance!';
        } elseif ($percentage >= 60) {
            return 'Commendable performance!';
        } elseif ($percentage >= 50) {
            return 'Satisfactory Performance!';
        } elseif ($percentage >= 40) {
            return 'Marginal Performance!';
        } else {
            return 'Unsatisfactory Performance!';
        }
    }
    $principal_remarks = generateRemark($percentage);

    // Number of Students
    $sql2 = "SELECT COUNT(*) AS num_students FROM students WHERE class = ? AND section = ?";
    $stmt2 = $con->prepare($sql2);
    $stmt2->bind_param("ss", $class, $section);
    $stmt2->execute();
    $res2 = $stmt2->get_result();
    $numStudents = $res2->fetch_assoc()['num_students'] ?? 0;

    $sql_avg_age = "SELECT AVG(TIMESTAMPDIFF(YEAR, age, CURDATE())) AS average_age FROM students WHERE class = '$class' AND section = '$section'";
    $result_avg_age = $con->query($sql_avg_age);
    $row_avg_age = $result_avg_age->fetch_assoc();
    $average_age = $row_avg_age['average_age'] ?? 0;

    // Fetch the next resumption date (next term's start and end dates after today)
    $currentSessionId = $currentSessionId ?? null;
    $currentTermId = $currentTermId ?? null;

    $nextQuery = "
    SELECT session_id, term_id, resumption_date, vacating_date, result_type
    FROM result_publish_schedule
    WHERE result_type = 'Endterm'
      AND session_id = '$currentSessionId'
      AND term_id = '$currentTermId'
    ORDER BY resumption_date ASC
    LIMIT 1
";

    $nextResult = mysqli_query($con, $nextQuery);

    if ($nextResult && mysqli_num_rows($nextResult) > 0) {
        $nextRow = mysqli_fetch_assoc($nextResult);

        $nextSessionId = $nextRow['session_id'];
        $nextTermId = $nextRow['term_id'];
        $nextTermName = "Term ID: " . $nextTermId; // raw ID, since no join
        $nextStartDate = $nextRow['resumption_date'] ?? 'N/A';
        $nextEndDate = $nextRow['vacating_date'] ?? 'N/A';
        $nextResultType = $nextRow['result_type'];
    } else {
        $nextTermName = 'N/A';
        $nextStartDate = 'N/A';
        $nextEndDate = 'N/A';
    }




    // Optional: Round age to 2 decimal places
    $average_age = ceil($average_age);

    // Function to get the appropriate suffix for the position
    function getPositionSuffix($position)
    {
        // Handle the special case for 11th, 12th, and 13th
        if ($position % 10 == 1 && $position != 11) {
            return $position . 'st';
        } elseif ($position % 10 == 2 && $position != 12) {
            return $position . 'nd';
        } elseif ($position % 10 == 3 && $position != 13) {
            return $position . 'rd';
        } else {
            return $position . 'th';
        }
    }


    // Get the position in the class (already done in your code)
    $positionQuery = "
  SELECT student_id, SUM(total_score) AS total
  FROM results 
  WHERE session_id = '$session_id' AND term_id = '$term_id' AND class = '$class' AND status = 'Approved'
  GROUP BY student_id
  ORDER BY total DESC
";
    $positionResult = mysqli_query($con, $positionQuery);
    $position = 1;
    $previous_score = null;

    while ($row = mysqli_fetch_assoc($positionResult)) {
        if ($row['student_id'] == $student_id) {
            break;
        }

        if ($row['total'] != $previous_score) {
            $position++;
        }

        $previous_score = $row['total'];
    }

    // Get the position with the suffix
    $position_with_suffix = getPositionSuffix($position);

    // SECTION POSITION
    $sectionQuery = $con->prepare("
    SELECT student_id, SUM(total_score) AS total
    FROM results 
    WHERE session_id = ? 
      AND term_id = ? 
      AND class = ?
      AND section = ?
      AND status = 'Approved'
    GROUP BY student_id
    ORDER BY total DESC
");

    $sectionQuery->bind_param("iiss", $session_id, $term_id, $class, $section);
    $sectionQuery->execute();
    $sectionResult = $sectionQuery->get_result();

    $section_position = 1;
    $section_previous_score = null;

    while ($row = $sectionResult->fetch_assoc()) {

        if ($row['student_id'] == $student_id) {
            break;
        }

        if ($row['total'] != $section_previous_score) {
            $section_position++;
        }

        $section_previous_score = $row['total'];
    }

    $section_pos_with_suffix = getPositionSuffix($section_position);


    // Grading Logic
    function getGrade($score)
    {
        $class = $_GET['class'];
        if ($class === 'JSS 1' || $class === 'JSS 2' || $class === 'JSS 3') {
            if ($score >= 70)
                return 'A';
            if ($score >= 50)
                return 'C';
            if ($score >= 40)
                return 'P';
            if ($score < 40)
                return 'F';
        } elseif ($class === 'SS 1' || $class === 'SS 2' || $class === 'SS 3') {
            if ($score >= 75)
                return 'A1';
            if ($score >= 70)
                return 'B2';
            if ($score >= 65)
                return 'B3';
            if ($score >= 60)
                return 'C4';
            if ($score >= 55)
                return 'C5';
            if ($score >= 50)
                return 'C6';
            if ($score >= 45)
                return 'D7';
            if ($score >= 40)
                return 'E8';
            if ($score < 40)
                return 'F9';
        } else {
            if ($score >= 70)
                return 'A';
            if ($score >= 50)
                return 'C';
            if ($score >= 40)
                return 'P';
            if ($score < 40)
                return 'F';
        }
    }
}
use Dotenv\Dotenv;

// Load Composer dependencies
require_once 'vendor/autoload.php';
// Load environment variables

$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

$school_name = $_ENV['SCHOOL_NAME_1'];
$logo = $_ENV['WEBSITE_LOGO'];
$address = $_ENV['id_address'];
$school_email = $_ENV['SCHOOL_EMAIL'];
$signature = $_ENV['PRINCIPAL_SIGNATURE'];
$website = $_ENV['SCHOOL_WEBSITE'];



?>
<!DOCTYPE html>
<html lang="en">
<?php include('includes/head.php'); ?>
<style>
    table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 10px;
    }

    th,
    td {
        border: 1px solid #000;
        padding: 8px;
        text-align: left;
    }

    th {
        background-color: #f2f2f2;
    }





    .academic-table {
        margin-top: 20px;
    }

    .academic-table thead th {
        background-color: #e6e6e6;
    }

    .psychomotor-table,
    .affective-table {
        margin-top: 20px;
    }

    .grades-table {
        margin-top: 20px;
    }

    .grades-table th {
        background-color: #e6e6e6;
    }

    .grades-table td {
        padding: 5px;
    }

    .slant-header {
        transform: rotate(180deg);
        /* or adjust to your desired angle */
        writing-mode: vertical-rl;
        /* optional: can stack text vertically if needed */
        white-space: nowrap;
        /* prevent wrapping */
        text-align: left;
        /* align slanted text nicely */
        padding: 10px;
        /* optional: add spacing */
        font-size: 14px;
        /* adjust size if needed */
        font-style: italic;
        font-weight: bold;
    }
</style>

<body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <?php include('includes/headerstd.php'); ?>
        <?php include('includes/sidebaroldstd.php'); ?>

        <div class="content-wrapper">
            <section class="content-header premium-header">
                <div class="container-fluid">
                    <div class="header-glass-card">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <div class="title-section">
                                    <div class="icon-box bg-primary-gradient shadow-sm">
                                        <i class="fas fa-clipboard-list"></i>
                                    </div>
                                    <div>
                                        <h1 class="premium-title text-primary">
                                            Result Management
                                            <span class="premium-subtitle text-secondary">View Result </span>
                                        </h1>
                            <div class="mt-1">
                              <?php if ($currentSessionName): ?>
                                <span class="badge badge-primary mr-1">
                                  <i class="fas fa-calendar-alt"></i>
                                  <?= htmlspecialchars($currentSessionName) ?>
                                </span>
                              <?php endif; ?>
                              <?php if ($currentTermName): ?>
                                <span class="badge badge-success">
                                  <i class="fas fa-bookmark"></i>
                                  <?= htmlspecialchars($currentTermName) ?>
                                </span>
                              <?php else: ?>
                                <span class="badge badge-warning">
                                  <i class="fas fa-exclamation-triangle"></i> No active term
                                </span>
                              <?php endif; ?>
                            </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <nav aria-label="breadcrumb">
                                    <ol class="breadcrumb premium-breadcrumb">
                                        <li class="breadcrumb-item"><a href="oldstdday.php"
                                                class="text-primary">Home</a></li>
                                        <li class="breadcrumb-item active" aria-current="page">View Result</li>
                                    </ol>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            <section class="content">
                <div class="container-fluid">
                    <div class="card shadow-sm">
                        <div class="card-header bg-primary text-white">
                            <h5 class="card-title font-weight-bold">
                                <i class="fas fa-file-alt"></i> Check Result
                            </h5>

                        </div>
                        <!-- <div class="card-body"> -->

                        <!-- Result Filter Form -->
                        <!-- <form method="POST" class="mb-4">
                                <div class="row">
                                    <div class="form-group col-md-4">
                                        <label for="session_id">Academic Session</label>
                                        <select name="session_id" id="session_id" class="form-control select2" required>
                                            <option value="">-- Select Session --</option>
                                            <?php
                                            $sessionResult = $con->query("SELECT DISTINCT id, session_name FROM school_sessions ORDER BY session_name DESC");
                                            while ($row = $sessionResult->fetch_assoc()) {
                                                echo "<option value='{$row['id']}'>{$row['session_name']}</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>

                                    <div class="form-group col-md-4">
                                        <label for="term_id">Term</label>
                                        <select name="term_id" id="term_id" class="form-control select2" required>
                                            <option value="">-- Select Term --</option>
                                        </select>
                                    </div>

                                    <div class="form-group col-md-4">
                                        <label for="class">Class</label>
                                        <select name="class" id="class" class="form-control select2" required>
                                            <option value="">-- Select Class --</option>
                                            <?php
                                            $classResult = $con->query("SELECT DISTINCT class FROM class_section ORDER BY class");
                                            while ($row = $classResult->fetch_assoc()) {
                                                echo "<option value='{$row['class']}'>{$row['class']}</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-group col-md-12  text-center">
                                    <button type="submit" name="view_result" class="btn btn-primary mt-3"><i class="fas fa-check-circle"></i> View Result</button>
                                </div>
                            </form> -->
                        <!-- End of Result Filter Form -->
                        <!-- </div> -->

                        <!-- // Check if the student has paid the full amount -->
                        <?php if (!empty($error_message)): ?>
                            <section class="content">
                                <div class="container-fluid">
                                    <div class="alert alert-danger text-center mt-4">
                                        <p><?php echo $error_message; ?></p>
                                    </div>
                                </div>
                            </section>

                        <?php elseif (empty($selected_term) || empty($selected_session)): ?>
                            <section class="content">
                                <div class="container-fluid">
                                    <div class="alert alert-info mt-5">
                                        <p class="mb-0">Please select a <strong>Term</strong> and <strong>Session</strong>
                                            to view the result.</p>
                                    </div>
                                </div>
                            </section>
                        <?php elseif ($total_subjects > 0): ?>
                            <!-- JSS 1 REPORT CARD -->
                            <section class="content">
                                <div class="container-fluid">
                                    <div class="card border-5" style="position: relative;">
                                        <!-- Watermark image -->
                                        <style>
                                            .watermark-text {
                                                /* Positioning */
                                                position: absolute;
                                                top: 50%;
                                                left: 50%;

                                                /* Centering and Rotation */
                                                transform: translate(-50%, -50%) rotate(-45deg);
                                                /* Added rotation */

                                                /* Styling */
                                                color: #000;
                                                /* Dark color for better contrast when transparent */
                                                opacity: 0.10;
                                                font-size: 4rem;
                                                /* Adjust this size as needed */
                                                font-weight: bold;
                                                text-transform: uppercase;
                                                white-space: nowrap;
                                                /* Ensures text stays on one line */

                                                /* Security/Performance */
                                                pointer-events: none;
                                                /* Allows clicks on content above it */
                                                z-index: 0;
                                            }
                                        </style>
                                        <div class="watermark-text">
                                            NOT FOR OFFICIAL USE
                                        </div>
                                        <!-- Main content goes here -->
                                        <div style="position: relative; z-index: 1;">
                                            <!-- Your result content here -->
                                            <div class="container mt-4">
                                                <div
                                                    class="d-flex justify-content-between align-items-center border-bottom pb-2">
                                                    <!-- Logo on the left -->
                                                    <div class="logo">
                                                        <img src="<?php echo $logo; ?>" width="100" alt="School Logo">
                                                    </div>

                                                    <!-- School name and details centered -->
                                                    <div class="text-center flex-grow-1">
                                                        <h1 class="mb-0 fw-bold" style="font-weight:bold; font-size: 65px;">
                                                            <?php echo strtoupper($school_name) ?>
                                                        </h1>
                                                        <p class="mb-0" style="font-size: 0.9rem;font-weight:bold;">
                                                            <?php echo $address; ?>
                                                        </p>
                                                        <p class="mb-0" style="font-size: 0.9rem;font-weight:bold;">
                                                            Website: <span
                                                                class="text-decoration-underline"><?php echo $website; ?></span>
                                                            | E-mail: <span
                                                                class="text-decoration-underline"><?php echo $school_email; ?></span>
                                                        </p>
                                                    </div>

                                                    <!-- Placeholder for spacing on the right (can be used if needed) -->
                                                    <div class="logo" style="width: 100px;"></div>
                                                </div>

                                                <!-- 2nd Term Report Title -->
                                                <div class="text-center mt-2">
                                                    <strong class="fw-bold border border-dark d-inline-block px-3 py-1"
                                                        style="font-size: 26px;"><?php echo strtoupper($selected_term); ?>
                                                        REPORT</strong>
                                                </div>
                                            </div>



                                            <div class="card-body">
                                                <div class="col-md-12 mb-3">
                                                    <div class="row">
                                                        <div class="col-md-4 mb-3">
                                                            <strong> Name:</strong>
                                                            <?= (htmlentities($student->studentName)) ?>
                                                        </div>
                                                        <div class="col-md-4 mb-3">
                                                            <strong>Term:</strong> <?= ($selected_term) ?>
                                                        </div>
                                                        <div class="col-md-4 mb-3">
                                                            <strong>Individual Attendance:</strong>
                                                            <?= ($totalAttendance) ?>
                                                        </div>
                                                        <div class="col-md-4 mb-3">
                                                            <strong> Class:</strong> <?= ($class) . ' - ' . ($section); ?>
                                                        </div>
                                                        <div class="col-md-4 mb-3">
                                                            <strong>Session:</strong> <?= ($selected_session) ?>
                                                        </div>
                                                        <div class="col-md-4 mb-3">
                                                            <strong>Total Attendance This Term:</strong> <?= ($totalDays) ?>
                                                        </div>
                                                        <div class="col-md-4 mb-3">
                                                            <strong>Gender:</strong> <?= ($student->gender ?? 'N/A') ?>
                                                        </div>

                                                        <div class="col-md-4 mb-3">
                                                            <strong>No. in Class:</strong> <?= ($numStudents) ?>
                                                        </div>

                                                        <div class="col-md-4 mb-3">
                                                            <strong>Next Resupmtion Date:</strong>
                                                            <?= date("F j, Y", strtotime($nextStartDate)) ?>
                                                        </div>
                                                        <div class="col-md-4 mb-3">
                                                            <strong>Student's Age:</strong>
                                                            <?= (!empty($student->age) && date_diff(date_create($student->age), date_create('today'))->y > 0)
                                                                ? date_diff(date_create($student->age), date_create('today'))->y
                                                                : "N/A"; ?>
                                                        </div>
                                                        <div class="col-md-4 mb-3">
                                                            <strong>Average Age:</strong> N/A
                                                        </div>
                                                        <div class="col-md-4 mb-3">
                                                            <strong>Next Vacation Date:</strong>
                                                            <?= date("F j, Y", strtotime($nextEndDate)) ?>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div style="display: flex; gap: 20px; align-items: flex-start;">

                                                    <!-- ACADEMICS TABLE -->
                                                    <table class="academic-table"
                                                        style="border-collapse: collapse; width: 60%;">
                                                        <?php
                                                        // Calculate colspan dynamically
                                                        $base_columns = 7;
                                                        $previous_term_count = count($previous_term_ids);

                                                        $total_colspan = ($previous_term_count < 1)
                                                            ? $base_columns
                                                            : $base_columns + (($previous_term_count >= 2) ? ($previous_term_count + 2) : 1);
                                                        ?>

                                                        <thead>
                                                            <tr>
                                                                <th colspan="<?= $total_colspan ?>">COGNITIVE DOMAIN
                                                                    (ACADEMICS)</th>
                                                            </tr>
                                                            <tr>
                                                                <th style="font-weight: bold; font-style: italic;">Subjects
                                                                </th>
                                                                <th class="slant-header">C.A. Test</th>
                                                                <th class="slant-header">Ex. & Projects</th>
                                                                <th class="slant-header">Assignment</th>
                                                                <th class="slant-header">Exam</th>
                                                                <th class="slant-header">Total</th>
                                                                <th class="slant-header">Grade</th>

                                                                <?php foreach ($previous_term_ids as $prev_id): ?>
                                                                    <th class="slant-header">
                                                                        <?= htmlspecialchars($term_names[$prev_id]) ?> Score
                                                                    </th>
                                                                <?php endforeach; ?>

                                                                <?php if ($previous_term_count >= 2): ?>
                                                                    <th class="slant-header">Cumm. Total</th>
                                                                    <th class="slant-header">Cumm. Average</th>
                                                                <?php endif; ?>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <tr>
                                                                <td>Marks Obtainable</td>
                                                                <td>10</td>
                                                                <td>15</td>
                                                                <td>5</td>
                                                                <td>70</td>
                                                                <td>100</td>
                                                                <td></td>
                                                                <?php foreach ($previous_term_ids as $prev_id): ?>
                                                                    <td>100</td>
                                                                <?php endforeach; ?>
                                                                <?php if (count($previous_term_ids) >= 2): ?>
                                                                    <td>300</td>
                                                                    <td>100</td>
                                                                <?php endif; ?>
                                                            </tr>

                                                            <?php foreach ($subjects_results as $subject => $data):
                                                                $current = $data['terms'][$current_term_id] ?? [];

                                                                // Display values (show 'AB' if absent)
                                                                $display_test_score1 = ($current['test_absent'] ?? 0) ? 'AB' : ($current['test_score'] ?? 0);
                                                                $display_class_performance = ($current['class_performance_absent'] ?? 0) ? 'AB' : ($current['class_performance'] ?? 0);
                                                                $display_weekly_assessment = ($current['weekly_assessment_absent'] ?? 0) ? 'AB' : ($current['weekly_assessment'] ?? 0);
                                                                $display_exam_score = ($current['exam_absent'] ?? 0) ? 'AB' : ($current['exam_score'] ?? 0);

                                                                // Numeric values for calculations
                                                                $calc_test_score1 = ($current['test_absent'] ?? 0) ? 0 : ($current['test_score'] ?? 0);
                                                                $calc_class_performance = ($current['class_performance_absent'] ?? 0) ? 0 : ($current['class_performance'] ?? 0);
                                                                $calc_weekly_assessment = ($current['weekly_assessment_absent'] ?? 0) ? 0 : ($current['weekly_assessment'] ?? 0);
                                                                $calc_exam_score = ($current['exam_absent'] ?? 0) ? 0 : ($current['exam_score'] ?? 0);

                                                                // Total score1
                                                                $total_score1 = $calc_test_score1 + $calc_class_performance + $calc_weekly_assessment + $calc_exam_score;

                                                                $remarks = $current['remarks'] ?? 'N/A';

                                                                // Prepare previous scores
                                                                $previous_scores = [];
                                                                foreach ($previous_term_ids as $prev_id) {
                                                                    $prev = $data['terms'][$prev_id] ?? [];
                                                                    $prev_total = 0;
                                                                    $prev_total += ($prev['test_score'] ?? 0);
                                                                    $prev_total += ($prev['class_performance'] ?? 0);
                                                                    $prev_total += ($prev['weekly_assessment'] ?? 0);
                                                                    $prev_total += ($prev['exam_score'] ?? 0);
                                                                    $previous_scores[] = $prev_total;
                                                                }

                                                                // Cumulative total and average
                                                                $all_scores = array_merge($previous_scores, [$total_score1]);
                                                                $terms_count = count(array_filter($all_scores, fn($score) => $score > 0));
                                                                $cumm_total = array_sum($all_scores);
                                                                $cumm_average = $terms_count > 0 ? round($cumm_total / $terms_count, 2) : 0;
                                                                ?>
                                                                <tr>
                                                                    <td><?= htmlspecialchars($subject) ?></td>
                                                                    <td
                                                                        style="<?= $display_test_score1 === 'AB' ? 'color:red;font-weight:bold;' : '' ?>">
                                                                        <?= htmlspecialchars($display_test_score1) ?>
                                                                    </td>
                                                                    <td
                                                                        style="<?= $display_class_performance === 'AB' ? 'color:red;font-weight:bold;' : '' ?>">
                                                                        <?= htmlspecialchars($display_class_performance) ?>
                                                                    </td>
                                                                    <td
                                                                        style="<?= $display_weekly_assessment === 'AB' ? 'color:red;font-weight:bold;' : '' ?>">
                                                                        <?= htmlspecialchars($display_weekly_assessment) ?>
                                                                    </td>
                                                                    <td
                                                                        style="<?= $display_exam_score === 'AB' ? 'color:red;font-weight:bold;' : '' ?>">
                                                                        <?= htmlspecialchars($display_exam_score) ?>
                                                                    </td>
                                                                    <td><?= htmlspecialchars($total_score1) ?></td>
                                                                    <td><?= getGrade($total_score1) ?></td>

                                                                    <?php foreach ($previous_scores as $prev_score): ?>
                                                                        <td><?= htmlspecialchars($prev_score) ?></td>
                                                                    <?php endforeach; ?>

                                                                    <?php if (count($previous_scores) >= 2): ?>
                                                                        <td><?= htmlspecialchars($cumm_total) ?></td>
                                                                        <td><?= htmlspecialchars($cumm_average) ?></td>
                                                                    <?php endif; ?>
                                                                </tr>
                                                            <?php endforeach; ?>
                                                        </tbody>


                                                    </table>

                                                    <!-- PSYCHOMOTOR & AFFECTIVE TABLE -->
                                                    <table class="behavior-table"
                                                        style="border-collapse: collapse; width: 35%;">
                                                        <thead>

                                                            <tr>
                                                                <th>PSYCHOMOTOR DOMAIN (SKILLS)</th>
                                                                <th>5</th>
                                                                <th>4</th>
                                                                <th>3</th>
                                                                <th>2</th>
                                                                <th>1</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <!-- Psychomotor subheading -->

                                                            <?php
                                                            $psychomotor_traits = [
                                                                "Fluency" => $psychomotor['fluency'] ?? '',
                                                                "Handwriting" => $psychomotor['handwriting'] ?? '',
                                                                "Lab Workshops" => $psychomotor['lab_workshops'] ?? '',
                                                                "Musical Skills" => $psychomotor['musical_skills'] ?? '',
                                                                "Sports" => $psychomotor['sports'] ?? ''
                                                            ];
                                                            foreach ($psychomotor_traits as $trait_name => $trait_value) {
                                                                ?>
                                                                <tr>
                                                                    <td><?= htmlspecialchars($trait_name) ?></td>
                                                                    <?php for ($i = 5; $i >= 1; $i--): ?>
                                                                        <td><?= $trait_value == $i ? "&#10004;" : "" ?></td>
                                                                    <?php endfor; ?>
                                                                </tr>
                                                            <?php } ?>

                                                            <!-- Affective subheading -->
                                                            <tr>
                                                                <th>AFFECTIVE DOMAIN (BEHAVIOUR)</th>
                                                                <th>5</th>
                                                                <th>4</th>
                                                                <th>3</th>
                                                                <th>2</th>
                                                                <th>1</th>
                                                            </tr>
                                                            <?php
                                                            $affective_traits = [
                                                                "Punctuality" => $affective['punctuality'] ?? '',
                                                                "Reliability" => $affective['reliability'] ?? '',
                                                                "Politeness/Honesty" => $affective['politeness_honesty'] ?? '',
                                                                "Charisma" => $affective['charisma'] ?? '',
                                                                "Organizational Ability" => $affective['organizational_ability'] ?? '',
                                                                "Self-Control" => $affective['self_control'] ?? ''
                                                            ];
                                                            foreach ($affective_traits as $trait_name => $trait_value) {
                                                                ?>
                                                                <tr>
                                                                    <td><?= htmlspecialchars($trait_name) ?></td>
                                                                    <?php for ($i = 5; $i >= 1; $i--): ?>
                                                                        <td><?= $trait_value == $i ? "&#10004;" : "" ?></td>
                                                                    <?php endfor; ?>
                                                                </tr>
                                                            <?php } ?>
                                                        </tbody>
                                                    </table>

                                                </div>

                                                <div style="display: flex; gap: 20px; align-items: flex-start;">
                                                    <!-- First Column: Table + Row -->
                                                    <div style="display: flex; flex-direction: column; width: 150%;">
                                                        <table style="width: 100%;">
                                                            <thead style="font-style:italic;">
                                                                <tr>
                                                                    <th><?php echo (count($previous_term_ids) >= 2) ? 'Total Marks Obtainable' : 'Total Marks Obtainable'; ?>
                                                                    </th>
                                                                    <th><?php echo (count($previous_term_ids) >= 2) ? 'Marks Obtained' : 'Marks Obtained'; ?>
                                                                    </th>
                                                                    <th><?php echo (count($previous_term_ids) >= 2) ? '% Obtained' : '% Obtained'; ?>
                                                                    </th>
                                                                    <th> Position in Class</th>
                                                                    <th>Overall Position</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody>
                                                                <tr>
                                                                    <?php
                                                                    // Calculate cumulative data if we're in the third term (or more than one term exists)
                                                                    if (count($previous_term_ids) >= 2) {

                                                                        // Map admission term from text to number
                                                                        $admission_term_text = $student['admission_term'] ?? 'First Term';
                                                                        $term_mapping = [
                                                                            'First Term' => 1,
                                                                            'Second Term' => 2,
                                                                            'Third Term' => 3
                                                                        ];
                                                                        $admission_term_id = $term_mapping[$admission_term_text] ?? 1;

                                                                        // Filter only the terms the student actually attended
                                                                        $attended_terms = array_filter($all_terms_to_fetch, function ($t) use ($admission_term_id) {
                                                                            return $t >= $admission_term_id;
                                                                        });
                                                                        $terms_attended_count = count($attended_terms);

                                                                        // Calculate cumulative marks obtainable (subjects * 100 * terms attended)
                                                                        $cumulative_mark_obtainable = $total_subjects * 100 * $terms_attended_count;

                                                                        // Calculate cumulative marks obtained across attended terms
                                                                        $cumulative_total_score = 0;
                                                                        foreach ($subjects_results as $subject_data) {
                                                                            foreach ($attended_terms as $term_id) {
                                                                                if (isset($subject_data['terms'][$term_id])) {
                                                                                    $score = $subject_data['terms'][$term_id]['total_score'];
                                                                                    if ($score === null || $score === '' || strtoupper($score) === 'AB') {
                                                                                        $score = 0;
                                                                                    }
                                                                                    $cumulative_total_score += (int) $score;
                                                                                }
                                                                            }
                                                                        }

                                                                        // Calculate cumulative percentage
                                                                        $cumulative_percentage = $cumulative_mark_obtainable ?
                                                                            round(($cumulative_total_score / $cumulative_mark_obtainable) * 100, 2) : 0;

                                                                        // Get position based on average per attended term
                                                                        $cumulativePositionQuery = "
                                                    SELECT student_id, 
                                                        SUM(total_score) AS total,
                                                        COUNT(DISTINCT term_id) AS terms_attended
                                                    FROM results 
                                                    WHERE session_id = '$session_id' 
                                                    AND term_id IN ($term_ids_in) 
                                                    AND class = '$class' 
                                                    AND status = 'Approved'
                                                    GROUP BY student_id
                                                    ORDER BY (SUM(total_score) / COUNT(DISTINCT term_id)) DESC
                                                ";
                                                                        $cumulativePositionResult = mysqli_query($con, $cumulativePositionQuery);
                                                                        $cumulative_position = 1;
                                                                        $previous_cumulative_avg = null;

                                                                        while ($row = mysqli_fetch_assoc($cumulativePositionResult)) {
                                                                            $student_avg = $row['terms_attended'] > 0 ? $row['total'] / $row['terms_attended'] : 0;

                                                                            if ($row['student_id'] == $student_id) {
                                                                                break;
                                                                            }

                                                                            if ($student_avg != $previous_cumulative_avg) {
                                                                                $cumulative_position++;
                                                                            }

                                                                            $previous_cumulative_avg = $student_avg;
                                                                        }

                                                                        $cumulative_position_with_suffix = getPositionSuffix($cumulative_position);

                                                                        $sectionCumQuery = $con->prepare("
                                                    SELECT 
                                                        student_id,
                                                        SUM(total_score) AS total,
                                                        COUNT(DISTINCT term_id) AS terms_attended
                                                    FROM results
                                                    WHERE session_id = ?
                                                    AND term_id IN ($term_ids_in)
                                                    AND class = ?
                                                    AND section = ?
                                                    AND status = 'Approved'
                                                    GROUP BY student_id
                                                    ORDER BY (SUM(total_score) / COUNT(DISTINCT term_id)) DESC
                                                ");

                                                                        $sectionCumQuery->bind_param("iss", $session_id, $class, $section);
                                                                        $sectionCumQuery->execute();
                                                                        $sectionCumResult = $sectionCumQuery->get_result();

                                                                        $section_cum_position = 1;
                                                                        $section_prev_avg = null;

                                                                        while ($row = $sectionCumResult->fetch_assoc()) {

                                                                            $avg = $row['terms_attended'] > 0
                                                                                ? $row['total'] / $row['terms_attended']
                                                                                : 0;

                                                                            if ($row['student_id'] == $student_id) {
                                                                                break;
                                                                            }

                                                                            if ($avg != $section_prev_avg) {
                                                                                $section_cum_position++;
                                                                            }

                                                                            $section_prev_avg = $avg;
                                                                        }

                                                                        $section_cum_position_with_suffix = getPositionSuffix($section_cum_position);


                                                                        // Display cumulative data
                                                                        echo '<td class="text-center">' . $cumulative_mark_obtainable . '</td>';
                                                                        echo '<td class="text-center">' . $cumulative_total_score . '</td>';
                                                                        echo '<td class="text-center">' . $cumulative_percentage . '</td>';
                                                                        echo '<td class = "text-center">' . $section_cum_position_with_suffix . '</td>';
                                                                        echo '<td class="text-center">' . $cumulative_position_with_suffix . '</td>';

                                                                    } else {
                                                                        // Display term data (for single term cases)
                                                                        echo '<td class="text-center">' . $mark_obtainable . '</td>';
                                                                        echo '<td class="text-center">' . $total_score . '</td>';
                                                                        echo '<td class="text-center">' . $percentage . '</td>';
                                                                        echo '<td class = "text-center">' . $section_pos_with_suffix . '</td>';
                                                                        echo '<td class="text-center">' . $position_with_suffix . '</td>';
                                                                    }
                                                                    ?>
                                                                </tr>
                                                            </tbody>
                                                        </table>

                                                        <div class="row" style="margin-top: 20px;">
                                                            <div class="col-md-12 mb-3">
                                                                <strong>Class Teacher's Remarks:
                                                                    <?= htmlspecialchars($remarks) ?></strong>
                                                            </div>
                                                            <div class="col-md-12 mb-3">
                                                                <strong>Principal's Remarks:
                                                                    <?= htmlspecialchars($principal_remarks) ?> </strong>

                                                            </div>
                                                            <div class="col-md-12 mb-3">
                                                                <strong>Date:
                                                                    <?= date("F j, Y", strtotime($publish_date)) ?></strong>
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <!-- Second Column: Grades Table -->
                                                    <?php if ($class === 'JSS 1' || $class === 'JSS 2' || $class === 'JSS 3'): ?>
                                                        <table class="grades-table">
                                                            <thead>
                                                                <tr>
                                                                    <th colspan="2">GRADES RATING</th>
                                                                    <th colspan="2">PSYCHO-AFFECTIVE RATING</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody>
                                                                <tr>
                                                                    <td>A</td>
                                                                    <td>70 - 100</td>
                                                                    <td>5</td>
                                                                    <td>Excellent</td>
                                                                </tr>
                                                                <tr>
                                                                    <td>C</td>
                                                                    <td>50 - 69</td>
                                                                    <td>4</td>
                                                                    <td>High Level</td>
                                                                </tr>
                                                                <tr>
                                                                    <td>P</td>
                                                                    <td>40 - 49</td>
                                                                    <td>3</td>
                                                                    <td>Acceptable Level</td>
                                                                </tr>
                                                                <tr>
                                                                    <td>F</td>
                                                                    <td>0 - 39</td>
                                                                    <td>2</td>
                                                                    <td>Below Acceptable Level</td>
                                                                </tr>
                                                                <tr>
                                                                    <td colspan="2" style="border: none;"></td>
                                                                    <td>1</td>
                                                                    <td>No Regard to traits</td>
                                                                </tr>
                                                            </tbody>
                                                        </table>
                                                    <?php elseif ($class === 'SS 1' || $class === 'SS 2' || $class === 'SS 3'): ?>
                                                        <table class="grades-table">
                                                            <thead>
                                                                <tr>
                                                                    <th colspan="2">GRADES RATING</th>
                                                                    <th colspan="2">PSYCHO-AFFECTIVE RATING</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody>
                                                                <tr>
                                                                    <td>A1</td>
                                                                    <td>75 - 100</td>
                                                                    <td>5</td>
                                                                    <td>Excellent</td>
                                                                </tr>
                                                                <tr>
                                                                    <td>B2</td>
                                                                    <td>70 - 74</td>
                                                                    <td>4</td>
                                                                    <td>High Level</td>
                                                                </tr>
                                                                <tr>
                                                                    <td>B3</td>
                                                                    <td>65 - 69</td>
                                                                    <td>3</td>
                                                                    <td>Acceptable Level</td>
                                                                </tr>
                                                                <tr>
                                                                    <td>C4</td>
                                                                    <td>60 - 64</td>
                                                                    <td>2</td>
                                                                    <td>Below Acceptable Level</td>
                                                                </tr>
                                                                <tr>
                                                                    <td>C5</td>
                                                                    <td>55 - 59</td>
                                                                    <td>1</td>
                                                                    <td>No Regard to traits</td>
                                                                </tr>
                                                                <tr>
                                                                    <td>C6</td>
                                                                    <td>50 - 54</td>
                                                                    <td colspan="2" style="border: none;"></td>
                                                                </tr>
                                                                <tr>
                                                                    <td>D7</td>
                                                                    <td>45 - 49</td>
                                                                    <td colspan="2" style="border: none;"></td>
                                                                </tr>
                                                                <tr>
                                                                    <td>E8</td>
                                                                    <td>40 - 44</td>
                                                                    <td colspan="2" style="border: none;"></td>
                                                                </tr>
                                                                <tr>
                                                                    <td>F9</td>
                                                                    <td>0 - 39</td>
                                                                    <td colspan="2" style="border: none;"></td>
                                                                </tr>

                                                            </tbody>
                                                        </table>
                                                    <?php else: ?>
                                                        <table class="grades-table">
                                                            <thead>
                                                                <tr>
                                                                    <th colspan="2">GRADES RATING</th>
                                                                    <th colspan="2">PSYCHO-AFFECTIVE RATING</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody>
                                                                <tr>
                                                                    <td>A</td>
                                                                    <td>70 - 100</td>
                                                                    <td>5</td>
                                                                    <td>Excellent</td>
                                                                </tr>
                                                                <tr>
                                                                    <td>C</td>
                                                                    <td>50 - 69</td>
                                                                    <td>4</td>
                                                                    <td>High Level</td>
                                                                </tr>
                                                                <tr>
                                                                    <td>P</td>
                                                                    <td>40 - 59</td>
                                                                    <td>3</td>
                                                                    <td>Acceptable Level</td>
                                                                </tr>
                                                                <tr>
                                                                    <td>F</td>
                                                                    <td>0 - 39</td>
                                                                    <td>2</td>
                                                                    <td>Below Acceptable Level</td>
                                                                </tr>
                                                                <tr>
                                                                    <td colspan="2" style="border: none;"></td>
                                                                    <td>1</td>
                                                                    <td>No Regard to traits</td>
                                                                </tr>
                                                            </tbody>
                                                        </table>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="text-center mb-3">
                                        <!-- <button type="button" class="btn btn-primary" onclick="PrintFunction()" name="submit" target="_blank"><i class="fas fa-print"></i>
                                Print
                            </button> -->
                                        <a href="download_result.php?session_id=<?= $session_id ?>&term_id=<?= $term_id ?>&class=<?= urlencode($class) ?>"
                                            class="btn btn-success approve" target="_blank">
                                            <i class="fas fa-file-pdf"></i> Download as PDF
                                        </a>
                                    </div>
                                </div>
                            </section>

                        </div>
                    </div>
                </section>



            <?php else: ?>
                <section class="content">
                    <div class="container-fluid">
                        <div class="alert alert-warning mt-5">
                            <p class="mb-0">Result for <strong><?= $selected_term ?> Term</strong> of
                                <strong><?= $selected_session ?></strong> has not been published yet. Wait till
                                <?= date("l, jS F Y", strtotime($publish_date)) ?>
                            </p>
                        </div>
                    </div>
                </section>
            <?php endif; ?>

            <?php
            // AI Parent Recommendation Panel — inside content-wrapper
            if (isset($student_id) && isset($session_id) && isset($term_id)) {
                $ai_stmt = $con->prepare(
                    "SELECT parent_recommendation FROM ai_performance_reports
                     WHERE student_id = ? AND session_id = ? AND term_id = ?
                     LIMIT 1"
                );
                if ($ai_stmt) {
                    $ai_stmt->bind_param('iii', $student_id, $session_id, $term_id);
                    $ai_stmt->execute();
                    $ai_stmt->bind_result($ai_parent_rec);
                    $ai_stmt->fetch();
                    $ai_stmt->close();

                    if (!empty($ai_parent_rec)) {
                        echo '<section class="content" style="padding-top:0;">
                            <div class="container-fluid">
                                <div class="card shadow-sm border-0" style="border-left:4px solid #4a6fdc !important;margin-bottom:20px;">
                                    <div class="card-header" style="background:linear-gradient(135deg,#4a6fdc,#6a8fef);color:#fff;">
                                        <h5 class="mb-0"><i class="fas fa-robot mr-2"></i> AI Performance Recommendation</h5>
                                    </div>
                                    <div class="card-body">
                                        <p class="mb-0" style="font-size:1rem;line-height:1.7;">'
                            . htmlspecialchars($ai_parent_rec) .
                            '</p>
                                    </div>
                                </div>
                            </div>
                        </section>';
                    }
                }
            }
            ?>

        </div>
        <!-- /.content-wrapper -->

        <?php @include("includes/footer.php"); ?>

    </div>

    <!-- ./wrapper -->
    <?php @include("includes/foot.php"); ?>

    <!-- jQuery and Bootstrap JS -->
    <script src="dist/js/select2.min.js"></script>
    <script>
        $(document).ready(function () {
            $('.select2').select2();
            $('#session_id').change(function () {
                var selectedClass = $(this).val();
                if (selectedClass) {
                    $.ajax({
                        url: 'fetch_session.php',
                        type: 'POST',
                        data: {
                            class_name: selectedClass
                        },
                        success: function (response) {
                            $('#term_id').html(response);
                        }
                    });
                } else {
                    $('#term_id').html('<option value="">Select Section</option>');
                }
            });
        });
    </script>
    <script>
        function PrintFunction() {
            var session = "<?= $session_id ?>";
            var term = "<?= $term_id ?>";
            var classs = "<?= $class ?>";
            var tabid = "<?= $tabSessionID ?>";



            // Check if start and end dates are provided
            if (session && term && classs) {
                var url = "print_result.php?session_id=" + session + "&term_id=" + term + "&class=" + classs + "&tab_id=" + tabid;
                // Redirect to generate PDF
                window.location.href = url;
            } else {
                alert("Class and Section empty.");
            }
        }
    </script>

</body>

</html>