<?php
session_name('super_admin_session');
error_reporting(0);
include('includes/dbconnection.php');


require_once('vendor/autoload.php');

use Mpdf\Mpdf;
use Dotenv\Dotenv;

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

$school_name = $_ENV['SCHOOL_NAME'];
$school_address = $_ENV['SCHOOL_ADDRESS'];


// Assuming the class teacher is viewing results for a class
$class = $_GET['class'];  // Get the class from URL parameter
$section = $_GET['section'];  // Get the section from URL parameter
$session = $_GET['session'];
$term = $_GET['term'];
$result_type =$_GET['result_type'];





// Fetch current session and term
$sessionRow = mysqli_fetch_assoc(mysqli_query($con, "SELECT id, session_name FROM school_sessions WHERE id ='$session' ORDER BY id DESC LIMIT 1"));
$currentSessionId = $sessionRow['id'];
$currentSessionName = $sessionRow['session_name'];

$termRow = mysqli_fetch_assoc(mysqli_query($con, "SELECT id, term_name FROM school_terms WHERE id = '$term' AND session_id = '$currentSessionId' ORDER BY id DESC LIMIT 1"));
$currentTermId = $termRow['id'];
$currentTermName = $termRow['term_name'];

    if ($result_type === 'Endterm'){
        $name = 'End of Term';
    }
    else{
        $name = 'Mid Term';
    }



    if ($result_type === 'Endterm'){

    // Fetch all subjects for this class
    $subject_stmt = $con->prepare("
    SELECT DISTINCT subject 
    FROM results 
    WHERE class = ? AND section = ? AND term_id = $currentTermId AND session_id = $currentSessionId
");
    $subject_stmt->bind_param("ss", $class, $section);
    $subject_stmt->execute();
    $subject_result = $subject_stmt->get_result();
    $subjects = $subject_result->fetch_all(MYSQLI_ASSOC);

    // Fetch results for each subject
    $results_by_subject = [];
    $result_type_by_subject = [];

    foreach ($subjects as $subject) {
        $subject_name = $subject['subject'];

        // First try fetching end-of-term results
        $end_stmt = $con->prepare("
        SELECT s.studentName, s.studentno, r.test_score, r.test_score2, r.class_performance, r.weekly_assessment, r.exam_score, r.total_score,
        r.test_absent, r.test2_absent, r.class_performance_absent, r.weekly_assessment_absent, r.exam_absent
        FROM results r
        JOIN students s ON r.student_id = s.id
        WHERE r.class = ? AND r.section = ? AND r.subject = ?
        AND r.status = 'Approved'
        AND r.term_id = ? AND r.session_id = ?
    ");
        $end_stmt->bind_param("sssii", $class, $section, $subject_name, $currentTermId, $currentSessionId);
        $end_stmt->execute();
        $end_results = $end_stmt->get_result();

        if ($end_results->num_rows > 0) {
            $results_by_subject[$subject_name] = $end_results->fetch_all(MYSQLI_ASSOC);
            $result_type_by_subject[$subject_name] = 'Endterm';
        } 
    }
}
else{
    // Fetch all subjects for this class
    $subject_stmt = $con->prepare("
    SELECT DISTINCT subject 
    FROM result2 
    WHERE class = ? AND section = ? AND term_id = $currentTermId AND session_id = $currentSessionId
");
    $subject_stmt->bind_param("ss", $class, $section);
    $subject_stmt->execute();
    $subject_result = $subject_stmt->get_result();
    $subjects = $subject_result->fetch_all(MYSQLI_ASSOC);

    // Fetch results for each subject
    $results_by_subject = [];
    $result_type_by_subject = [];

    foreach ($subjects as $subject) {
        $subject_name = $subject['subject'];

        // First try fetching end-of-term results
        $end_stmt = $con->prepare("
        SELECT s.studentName, s.studentno, r.test_score, r.test_score2, r.class_performance, r.weekly_assessment, r.exam_score, r.total_score,
        r.test_absent, r.test2_absent, r.class_performance_absent, r.weekly_assessment_absent, r.exam_absent
        FROM result2 r
        JOIN students s ON r.student_id = s.id
        WHERE r.class = ? AND r.section = ? AND r.subject = ?
        AND r.status_test = 'Approved'
        AND r.term_id = ? AND r.session_id = ?
    ");
        $end_stmt->bind_param("sssii", $class, $section, $subject_name, $currentTermId, $currentSessionId);
        $end_stmt->execute();
        $end_results = $end_stmt->get_result();

        if ($end_results->num_rows > 0) {
            $results_by_subject[$subject_name] = $end_results->fetch_all(MYSQLI_ASSOC);
            $result_type_by_subject[$subject_name] = 'Midterm';
        }
    }
}


?>

<!-- HTML to display the results -->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Class Result Broadsheet</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
        @media print {
            body {
                -webkit-print-color-adjust: exact;
            }
        }
    </style>
</head>

<body>
    <div class="container mt-5">
        <div class='text-center'>
            <img src='company/logo.jpeg' alt='logo' width='70' height='70'><br>
            <h1><?= strtoupper($school_name) ?></h1>
            <b><i><?= $school_address ?></i></b><br>
            <hr>
            <h4 class="text-center"><?= $name;?> Result Broadsheet for <?= htmlspecialchars($class . " - " . $section); ?></h4>
        </div>
        <div class='text-center'>
            <strong>Term:</strong> <?= $currentTermName ?> || <strong>Session:</strong> <?= $currentSessionName ?>
        </div>
    </div>

    <div class="container">
        <?php foreach ($results_by_subject as $subject => $results): ?>
            <div class="card mt-3">
                <div class="card-header bg-info text-white">
                    <h6 class="mb-0">
                        <i class="fas fa-book-open"></i> <?= htmlspecialchars($subject); ?> - <?= $result_type_by_subject[$subject] ?> Results
                    </h6>
                </div>
                <div class="card-body">
                    <table class="table table-bordered table-hover">
                        <thead>
                            <tr>
                                <th>Admission No.</th>
                                <th>Student Name</th>
                                <?php if ($result_type_by_subject[$subject] === 'Endterm'): ?>                                
                                <th>C.A. Test 1 (10)</th>
                                <th>C.A. Test 2 (10)</th>
                                <?php else: ?>
                                <th>1st C.A. Test (10)</th>
                                <th>2nd C.A. Test (10)</th>
                                <?php endif; ?>
                                <th>Ex. & Projects (5)</th>
                                <th>Assignment (5)</th>
                                <?php if ($result_type_by_subject[$subject] === 'Endterm'): ?>
                                    <th>Exam (70)</th>
                                <?php endif; ?>
                                <th>Total (<?= $result_type_by_subject[$subject] === 'Endterm' ? '100' : '30' ?>)</th>

                            </tr>
                        </thead>
                        <tbody>
                                                        <?php foreach ($results as $result): ?>
    <?php
    // Determine each score display
    $test_score = ($result['test_absent'] == "1") ? 'AB' : (int)$result['test_score'];
    $test_score2 = ($result['test2_absent'] == "1") ? 'AB' : (int)$result['test_score2'];
    $class_performance = ($result['class_performance_absent'] == "1") ? 'AB' : (int)$result['class_performance'];
    $weekly_assessment = ($result['weekly_assessment_absent'] == "1") ? 'AB' : (int)$result['weekly_assessment'];
    $exam = ($result['exam_absent'] == "1") ? 'AB' : (int)$result['exam_score'];
    // Collect scores for numeric sum
    $scores_exam = [$test_score, $test_score2, $class_performance, $weekly_assessment, $exam];
    $numeric_scores_exam = array_filter($scores_exam, 'is_numeric');

    // Calculate total or show AB if all absent
    $total_exam = count($numeric_scores_exam) ? array_sum($numeric_scores_exam) : 'AB';
    // Collect scores for numeric sum
    $scores_test = [$test_score, $test_score2, $class_performance, $weekly_assessment];
    $numeric_scores_test = array_filter($scores_test, 'is_numeric');

    // Calculate total or show AB if all absent
    $total_test = count($numeric_scores_test) ? array_sum($numeric_scores_test) : 'AB';
    ?>                                                    
                                                            <tr>
                                                                <td><?= htmlspecialchars($result['studentno']); ?></td>
                                                                <td><?= htmlspecialchars($result['studentName']); ?></td>
                                                                <td><?= $test_score ?></td>
                                                                <td><?= $test_score2 ?></td>
                                                                <td><?= $class_performance ?></td>
                                                                <td><?= $weekly_assessment ?></td>
                                                                <?php if ($result_type_by_subject[$subject] === 'Endterm'): ?>
                                                                <td><?= $exam ?></td>
                                                                <td><?= $total_exam ?></td>
                                                                <?php else: ?>
                                                                <td><?= $total_test ?></td>
                                                                <?php endif; ?>
                                                            </tr>
                                                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
    <script>
        window.print();
    </script>
</body>

</html>