<?php
include('includes/session.php');
error_reporting(0);
// Connect to the database
include('includes/dbconnection.php');
// Fetch student ID (e.g., via GET parameter)
$student_id = $_SESSION['student_id'];


// Fetch current session and term
// Fetch active session ordered by earliest start_date
$currentSessionQuery = "
    SELECT id, session_name 
    FROM school_sessions 
    WHERE start_date <= CURDATE() 
    AND end_date >= CURDATE() 
    ORDER BY start_date ASC 
    LIMIT 1";
$currentSessionResult = $con->query($currentSessionQuery);

if ($currentSessionResult && $currentSessionResult->num_rows > 0) {
    $currentSession = $currentSessionResult->fetch_assoc();
    $currentSessionId = $currentSession['id'];
    $currentSessionName = $currentSession['session_name'];
} else {
    $currentSessionId = null;
    $currentSessionName = null;
}

// Fetch the current term
$termQuery = "SELECT id, term_name FROM school_terms WHERE session_id = '$currentSessionId'
              AND start_date <= CURDATE() 
              AND end_date >= CURDATE() 
              ORDER BY start_date ASC 
              LIMIT 1";
$termResult = mysqli_query($con, $termQuery);
$termRow = mysqli_fetch_assoc($termResult);
$currentTermId = $termRow['id'];
$currentTermName = $termRow['term_name'];

// Handle POST selections or fallback to defaults
$session_id = $_POST['session_id'];
$term_id = $_POST['term_id'];
$class = $_POST['class'];

// 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'] ?? '';

// 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() : [];

// Total Attendance
$sql1 = "SELECT COUNT(*) AS total_attendance FROM attendance WHERE class = ? AND section = ? AND status ='present' AND term_id =? AND session_id =?";
$stmt1 = $con->prepare($sql1);
$stmt1->bind_param("ssii", $class, $section, $currentTermId, $currentSessionId);
$stmt1->execute();
$res1 = $stmt1->get_result();
$totalAttendance = $res1->fetch_assoc()['total_attendance'] ?? 0;

$sqlTermDates = "SELECT start_date, end_date FROM school_terms WHERE id = ? AND session_id = ?";
$stmtTermDates = $con->prepare($sqlTermDates);
$stmtTermDates->bind_param("ii", $currentTermId, $currentSessionId);
$stmtTermDates->execute();
$resTermDates = $stmtTermDates->get_result();
if ($rowTermDates = $resTermDates->fetch_assoc()) {
    $startDate = new DateTime($rowTermDates['start_date']);
    $endDate = new DateTime($rowTermDates['end_date']);
}

$totalDays = 0;
$period = new DatePeriod($startDate, new DateInterval('P1D'), $endDate->modify('+1 day'));

foreach ($period as $date) {
    $dayOfWeek = $date->format('N'); // 1=Monday, 7=Sunday
    if ($dayOfWeek < 6) { // Weekdays only
        $totalDays++;
    }
}

// Get selected session and term
$selected_session_id = $_POST['session_id'];
$selected_term_id = $_POST['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);


$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 ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['view_result'])) {
    // Initialize result variables


    // Fetch academic results

    $results_sql = "SELECT term_id, subject, test_score, test_score2, class_performance, weekly_assessment, exam_score, total_score,remarks
                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);

    $subjects_results = [];
    // Process results
    if ($results_result && $results_result->num_rows > 0) {
        while ($row = $results_result->fetch_assoc()) {
            $term_id = $row['term_id'];
            $subject = $row['subject'];

            if (!isset($subjects_results[$subject])) {
                $subjects_results[$subject] = [
                    'current_term' => [],
                    'previous_terms' => []
                ];
            }

            if ($term_id == $selected_term_id) {
                $subjects_results[$subject]['current_term'] = $row;
            } else {
                $subjects_results[$subject]['previous_terms'][$term_id] = $row['total_score'];
            }
        }

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

        // Sum all current term total scores
        $total_score = 0;
        foreach ($subjects_results as $subject_data) {
            $total_score += $subject_data['current_term']['total_score'] ?? 0;
        }

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

// 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)
$nextResumptionQuery = "
    SELECT session_id, term_name, start_date, end_date 
    FROM school_terms 
    WHERE start_date > NOW() 
    -- AND status = 'active' -- Uncomment if you have a status column
    ORDER BY start_date ASC 
    LIMIT 1";
$nextResumptionResult = mysqli_query($con, $nextResumptionQuery);

if ($nextResumptionResult && mysqli_num_rows($nextResumptionResult) > 0) {
    $nextResumptionRow = mysqli_fetch_assoc($nextResumptionResult);
    $nextSessionId = $nextResumptionRow['session_id'];
    $nextTermName = $nextResumptionRow['term_name'] ?? 'N/A';
    $nextStartDate = $nextResumptionRow['start_date'] ?? 'N/A';
    $nextEndDate = $nextResumptionRow['end_date'] ?? 'N/A';
} else {
    // If no next term found, set default values
    $nextStartDate = 'N/A';
    $nextEndDate = 'N/A';
}

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

$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'];
}


// 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);


// Grading Logic
function getGrade($score)
{
    $class = $_POST['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'];
$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">
                <div class="container-fluid">
                    <div class="row mb-2">
                        <div class="col-sm-8">
                            <h3 class="text-primary font-weight-bold">
                                <i class="fas fa-clipboard-list"></i> Result Management →
                                <span class="font-italic text-secondary" style="font-size: 0.5em;">View Result</span>
                            </h3>
                        </div>
                        <div class="col-sm-4">
                            <ol class="breadcrumb float-sm-right">
                                <li class="breadcrumb-item"><a href="oldstdday.php">Home</a></li>
                                <li class="breadcrumb-item active">View Result</li>
                            </ol>
                        </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>
                    </div>
                </div>
            </section>

            <?php if (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 -->
                            <img src="<?php echo $logo; ?>" alt="Watermark"
                                style="position: absolute;
                                                top: 50%;
                                                left: 50%;
                                                transform: translate(-50%, -50%);
                                                opacity: 0.10;
                                                width: 50%;
                                                max-width: 200px;
                                                z-index: 0;
                                                pointer-events: none;">
                            <!-- 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;"><?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;">
                                                Web Address: <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"><?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-7 mb-3">
                                                <strong> Name:</strong> <?= (htmlentities($student['studentName'])) ?>
                                            </div>
                                            <div class="col-md-5 mb-3">
                                                <strong>Gender:</strong> <?= ($student['gender']) ?>
                                            </div>
                                            <div class="col-md-7 mb-3">
                                                <strong> Class:</strong> <?= ($class) ?>
                                            </div>
                                            <div class="col-md-5 mb-3">
                                                <strong>No. in Class:</strong> <?= ($numStudents) ?>
                                            </div>
                                            <div class="col-md-7 mb-3">
                                                <strong>Average Age:</strong> <?= ($average_age) ?>
                                            </div>
                                            <div class="col-md-5 mb-3">
                                                <strong>Student's Age:</strong> <?= date_diff(date_create($student['age']), date_create('today'))->y ?>

                                            </div>
                                            <div class="col-md-7 mb-3">
                                                <strong>Session:</strong> <?= ($selected_session) ?>
                                            </div>
                                            <div class="col-md-5 mb-3">
                                                <strong>Term:</strong> <?= ($selected_term) ?>
                                            </div>
                                            <div class="col-md-7 mb-3">
                                                <strong>Total Attendance Per Term:</strong> <?= ($totalDays) ?>
                                            </div>
                                            <div class="col-md-5 mb-3">
                                                <strong>Individual Attendance:</strong> <?= ($totalAttendance) ?>
                                            </div>
                                            <div class="col-md-7 mb-3">
                                                <strong>Next Resupmtion Date:</strong> <?= date("F j, Y", strtotime($nextStartDate)) ?>
                                            </div>
                                            <div class="col-md-5 mb-3">
                                                <strong>Next Terminal 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);
                                            $extra_columns = $previous_term_count > 0 ? $previous_term_count + 2 : 0;

                                            $total_colspan = $base_columns + $extra_columns;
                                            ?>

                                            <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">Class 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 > 0): ?>
                                                        <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></td>
                                                    <td></td>
                                                    <td></td>
                                                    <td>70</td>
                                                    <td>100</td>
                                                    <td></td>
                                                    <?php foreach ($previous_term_ids as $prev_id): ?>
                                                        <td></td>
                                                    <?php endforeach; ?>
                                                    <?php if (count($previous_term_ids) > 0): ?>
                                                        <td> </td>
                                                        <td> </td>
                                                    <?php endif; ?>
                                                </tr>
                                                <?php foreach ($subjects_results as $subject => $data) :
                                                    $current = $data['current_term'];
                                                    $test_score1 = $current['test_score'] ?? 0;
                                                    $test_score2 = $current['test_score2'] ?? 0;
                                                    $test_score = $test_score1 + $test_score2;
                                                    $class_performance = $current['class_performance'] ?? 0;
                                                    $weekly_assessment = $current['weekly_assessment'] ?? 0;
                                                    $exam_score = $current['exam_score'] ?? 0;
                                                    $total_score = $current['total_score'] ?? 0;
                                                    $remarks = $current['remarks'] ?? 'N/A';

                                                    // Prepare previous scores
                                                    $previous_scores = [];
                                                    foreach ($previous_term_ids as $prev_id) {
                                                        $previous_scores[] = $data['previous_terms'][$prev_id] ?? 0;
                                                    }

                                                    // Calculate cumulative total and average
                                                    $all_scores = array_merge($previous_scores, [$total_score]);
                                                    $cumm_total = array_sum($all_scores);
                                                    $terms_count = count(array_filter($all_scores, function ($score) {
                                                        return $score > 0;
                                                    }));
                                                    $cumm_average = $terms_count > 0 ? round($cumm_total / $terms_count, 2) : 0;
                                                ?>
                                                    <tr>
                                                        <td><?= htmlspecialchars($subject) ?></td>
                                                        <td><?= htmlspecialchars($test_score) ?></td>
                                                        <td><?= htmlspecialchars($class_performance) ?></td>
                                                        <td><?= htmlspecialchars($weekly_assessment) ?></td>
                                                        <td><?= htmlspecialchars($exam_score) ?></td>
                                                        <td><?= htmlspecialchars($total_score) ?></td>
                                                        <td><?= getGrade($total_score) ?></td>

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

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

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

                                                <tr>
                                                    <th>PSYCHOMOTOR</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</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>Total Mark Obtainable</th>
                                                        <th>Mark Obtained</th>
                                                        <th>%</th>
                                                        <th>Position</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr>
                                                        <td><?= $mark_obtainable ?></td>
                                                        <td><?= $total_score ?></td>
                                                        <td><?= $percentage ?></td>
                                                        <td><?= $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 Signature: </strong> <img src="<?php echo $signature; ?>" width="70" height="30" alt="School Logo">

                                                </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 - 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 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>



            <?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.</p>
                        </div>
                    </div>
                </section>
            <?php endif; ?>
        </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>