<?php
include('includes/dbconnection.php');

// Fetch student ID and other parameters
$student_id = $_POST['student_id'] ?? 1;
$selected_session_id = $_POST['session_id'] ?? 1;
$selected_term_id = $_POST['term_id'] ?? 1;

// Fetch session and term details
$session_query = mysqli_query($con, "SELECT session_name FROM school_sessions WHERE id = '$selected_session_id'");
$session_row = mysqli_fetch_assoc($session_query);
$session_name = $session_row['session_name'] ?? 'N/A';

$term_query = mysqli_query($con, "SELECT term_name FROM school_terms WHERE id = '$selected_term_id'");
$term_row = mysqli_fetch_assoc($term_query);
$term_name = $term_row['term_name'] ?? 'N/A';

// Fetch student bio and class details
$student_query = mysqli_query($con, "SELECT studentName, gender, class, section FROM students WHERE id = '$student_id'");
$student_row = mysqli_fetch_assoc($student_query);
$student_name = $student_row['studentName'] ?? '';
$student_gender = $student_row['gender'] ?? '';
$student_class = $student_row['class'] ?? '';
$student_section = $student_row['section'] ?? '';

// Now use the student's class directly
$results_sql = "SELECT term_id, subject, test_score, 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 = '$selected_term_id'
                AND class = '$student_class'"; // Removed $_POST class and used actual class

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

$subjects_results = [];
$total_score = 0;
$total_subjects = 0;
$mark_obtainable = 0;
$percentage = 0;
$average_score = 0;
$error_message = '';

if ($results_result && $results_result->num_rows > 0) {
    while ($row = $results_result->fetch_assoc()) {
        $subjects_results[] = $row;
    }

    $total_subjects = count($subjects_results);
    $mark_obtainable = $total_subjects * 100;

    foreach ($subjects_results as $result) {
        $total_score += $result['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;
} else {
    $error_message = "No results found for this student.";
}
?>


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mid-Term Report</title>
    <style>
        body {
            font-family: 'Times New Roman', Times, serif, sans-serif;
            margin: 20px;
        }

        .header {
            text-align: center;
            margin-bottom: 20px;
        }

        .logo {
            float: left;
            margin-right: 20px;
        }

        .school-name {
            font-size: 18px;
            font-weight: bold;
        }

        .address {
            font-size: 12px;
            margin-top: 5px;
        }

        .report-title {
            font-size: 14px;
            font-weight: bold;
            background-color: #ff0000;
            color: white;
            padding: 5px;
            text-align: center;
            width: fit-content;
            margin: 10px auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

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

        th {
            background-color: #f2f2f2;
        }

        .comment-section,
        .signature-section {
            margin-top: 20px;
        }

        .line {
            border-bottom: 1px solid #000;
            margin: 5px 0;
        }

        .print-btn {
            margin: 20px 0;
        }
    </style>
    <script>
        function printReport() {
            window.print();
        }
    </script>
</head>

<body>

    <div class="header">
        <img src="path/to/logo.png" alt="School Logo" class="logo" style="width: 50px; height: 50px;">
        <div class="school-name">ADESINA COLLEGE, IBADAN</div>
        <div class="address">
            No. 2 Kolawole Ajadi Crescent, Alagbayun, Akobo, Ibadan<br>
            Web Address: www.adesinacollegeibadan.net | E-mail: info@adesinacollegeibadan.net
        </div>
        <div class="report-title">MID-TERM REPORT</div>
    </div>

    <!-- Student Bio -->
    <div>
        
        <strong>Name:</strong> <?php echo htmlspecialchars($student_name); ?><br>
        <strong>Gender:</strong> <?php echo htmlspecialchars($student_gender); ?><br>
        <strong>Class:</strong> <?php echo htmlspecialchars($student_class); ?><br>
        <strong>Section:</strong> <?php echo htmlspecialchars($student_section); ?><br>
        <strong>Session:</strong> <?php echo htmlspecialchars($session_name); ?><br>
        <strong>Term:</strong> <?php echo htmlspecialchars($term_name); ?><br>
    </div>

    <?php if (!empty($error_message)) : ?>
        <p style="color:red;"><?php echo $error_message; ?></p>
    <?php endif; ?>

    <!-- Results Table -->
    <table>
        <thead>
            <tr>
                <th>Subject</th>
                <th>1st CA</th>
                <th>2nd CA</th>
                <th>Axv Exe</th>
                <th>Total</th>
                <th>Grade</th>
            </tr>
        </thead>
        <tbody>
            <?php if (!empty($subjects_results)) : ?>
                <?php foreach ($subjects_results as $result) : ?>
                    <?php
                    $test_score = $result['test_score'] ?? '';
                    $class_performance = $result['class_performance'] ?? '';
                    $weekly_assessment = $result['weekly_assessment'] ?? '';
                    $total = $result['total_score'] ?? '';
                    $grade = '';

                    if ($total >= 70) $grade = 'A';
                    elseif ($total >= 60) $grade = 'B';
                    elseif ($total >= 50) $grade = 'C';
                    elseif ($total >= 45) $grade = 'D';
                    elseif ($total > 0) $grade = 'E';
                    else $grade = 'F';
                    ?>
                    <tr>
                        <td><?php echo htmlspecialchars($result['subject']); ?></td>
                        <td><?php echo htmlspecialchars($test_score); ?></td>
                        <td><?php echo htmlspecialchars($class_performance); ?></td>
                        <td><?php echo htmlspecialchars($weekly_assessment); ?></td>
                        <td><?php echo htmlspecialchars($total); ?></td>
                        <td><?php echo $grade; ?></td>
                    </tr>
                <?php endforeach; ?>
            <?php else : ?>
                <tr>
                    <td colspan="6" style="text-align: center;">No results found.</td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>

    <!-- Comment Section -->
    <div class="comment-section">
        <label for="class-teacher-comment">Class Teacher's Comment</label>
        <textarea id="class-teacher-comment" rows="3" cols="80" style="width: 100%; margin-top: 5px;"></textarea>
    </div>

    <!-- Signature Section -->
    <div class="signature-section">
        <div>
            <span>Signature</span>
            <div class="line" style="width: 200px; display: inline-block;"></div>
        </div>
        <div>
            <span>Parent's Name and Signature</span>
            <div class="line" style="width: 200px; display: inline-block;"></div>
        </div>
        <div style="float: right;">
            <span>Date</span>
            <div class="line" style="width: 100px; display: inline-block;"></div>
        </div>
    </div>

    <!-- Print Button -->
    <div class="print-btn">
        <button onclick="printReport()">Print Report</button>
    </div>

</body>

</html>