<?php
session_name('super_admin_session');
if (!is_dir(dirname(__DIR__) . '/session_data/super')) { mkdir(dirname(__DIR__) . '/session_data/super', 0700, true); } session_save_path(dirname(__DIR__) . '/session_data/super');
session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);
session_start();
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'];

$section = isset($_GET['section']) ? filter_var($_GET['section'], FILTER_SANITIZE_STRING) : '';
$class = isset($_GET['class']) ? filter_var($_GET['class'], FILTER_SANITIZE_STRING) : '';
$session = isset($_GET['session']) ? filter_var($_GET['session'], FILTER_SANITIZE_STRING) : '';
$term = isset($_GET['term']) ? filter_var($_GET['term'], FILTER_SANITIZE_STRING) : '';
$result_type = isset($_GET['result_type']) ? filter_var($_GET['result_type'], FILTER_SANITIZE_STRING) : '';



// 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 subjects
$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 per subject
$results_by_subject = [];
foreach ($subjects as $subject) {
    $subject_name = $subject['subject'];
    $result_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 = $currentTermId AND r.session_id = $currentSessionId
    ");
    $result_stmt->bind_param("sss", $class, $section, $subject_name);
    $result_stmt->execute();
    $result_data = $result_stmt->get_result();
    $isMidterm = 0;
    $results_by_subject[] = [
        'subject' => $subject_name,
        'isMidterm' => $isMidterm,
        'data' => $result_data->fetch_all(MYSQLI_ASSOC)
    ];
}
    }
    else{
        // Fetch subjects
$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 per subject
$results_by_subject = [];
foreach ($subjects as $subject) {
    $subject_name = $subject['subject'];
    $result_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 = $currentTermId AND r.session_id = $currentSessionId
    ");
    $result_stmt->bind_param("sss", $class, $section, $subject_name);
    $result_stmt->execute();
    $result_data = $result_stmt->get_result();
    $isMidterm = 1;
    $results_by_subject[] = [
        'subject' => $subject_name,
        'isMidterm' => $isMidterm,
        'data' => $result_data->fetch_all(MYSQLI_ASSOC)
    ];
}
    }


// HTML Content
$html = "
<style>
    table { width: 100%; border-collapse: collapse; font-size: 12px; }
    th, td { padding: 8px; text-align: left; border: 1px solid #ddd; }
    th { background-color: #141618ff; color: white; }
    tr:nth-child(even) { background-color: #f9f9f9; }
    .text-center { text-align: center; }
    .card-header { color: black; text-align: center;}
</style>
<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 $class - $section</h4>
</div>
<div class='text-center'>
    <strong>Term:</strong> $currentTermName  || <strong>Session:</strong> $currentSessionName 
</div>
<hr>";
foreach ($results_by_subject as $subject_entry) {
    $subject = $subject_entry['subject'];
    $isMidterm = $subject_entry['isMidterm'];
    $results = $subject_entry['data'];


    $html .= "<div class='card mt-3'>
                <div class='card-header'>
                    <center><h5 class='mb-0'><i class='fas fa-book-open'></i> " . htmlspecialchars($subject) . " - " . ($isMidterm ? "Midterm" : "End of Term") . " Results</h5></center>
                </div>
                <div class='card-body'>
                    <table class='table table-bordered table-hover'>
                        <thead>
                        <tr>
                            <th>Admission No.</th>
                            <th>Student Name</th>
                            <th>1st Test (10)</th>
                            <th>2nd Test (10)</th>
                            <th>Class Ex. & Projects (5)</th>
                            <th>Assignment (5)</th>";
    if ($isMidterm == 0) {
        $html .= "
                            <th>Exam (70)</th>
                            <th>Total (100)</th>";
    }
    else{
    $html .= "
                            <th>Total (30)</th>";
    }
    $html .= "          </tr>
                        </thead>
                        <tbody>";

    foreach ($results as $result) {
            $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';
        $html .= "<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>";
                if ($isMidterm == 0) {
            $html .= "
                    <td>" . $exam . "</td>
                    <td>" . $total_exam. "</td>";
        }else{
        $html .= "
                    <td>" . $total_test. "</td>
                </tr>";
    }

}
    $html .= "</tbody></table></div></div>";

}

// Generate PDF
$mpdf = new Mpdf();
$mpdf->SetHeader($school_name . '||'.$class .'-'.$section . ' '. $name.' '.'Broadsheet');
$mpdf->SetFooter('Generated on ' . date("M d, Y H:i A") . '||Page {PAGENO}');
$mpdf->WriteHTML($html);
$mpdf->Output($class. '_'. $section .'_'.'class_result_broadsheet.pdf', 'D');
?>
