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

require_once('vendor/autoload.php');

use Mpdf\Mpdf;
use Dotenv\Dotenv;

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

$school_name = $_ENV['SCHOOL_NAME'];
$logo = $_ENV['WEBSITE_LOGO'];
$address = $_ENV['SCHOOL_ADDRESS'];

// --- Student and Filter Initialization ---
$student_id = $_SESSION['student_id'];

// Fetch student info
$studentQuery = mysqli_query($con, "SELECT * FROM students WHERE id = '$student_id'");
$student = mysqli_fetch_assoc($studentQuery);
$default_class = $student['class'];
$section = $student['section'];
$studentImage = "studentimages/" . htmlspecialchars($student['studentImage']);

// Handle GET selections
$session_id = $_GET['session_id'];
$term_id = $_GET['term_id'];
$class = $_GET['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 approved results, total score, and student position
$results = [];
$total_score = 0;
// NEW: Variable to hold the Class Teacher's Remark (using the first subject's remark as a proxy)
$class_teacher_remarks = ''; 

$resultQuery = mysqli_query($con, "
    SELECT subject, test_score, class_performance, weekly_assessment, exam_score, total_score, remarks, teacher_id
    FROM results 
    WHERE student_id = '$student_id' 
    AND session_id = '$session_id' 
    AND term_id = '$term_id'
    AND class = '$class'
    AND status = 'Approved'
");

while ($row = mysqli_fetch_assoc($resultQuery)) {
    $results[] = $row;
    $total_score += $row['total_score'];
    
    // Capture the remark from the first result (or if a remark is available)
    if (empty($class_teacher_remarks) && !empty($row['remarks'])) {
        $class_teacher_remarks = $row['remarks'];
    }
}

$total_subjects = count($results);
$average_score = $total_subjects ? round($total_score / $total_subjects, 2) : 0;

// --- Position Calculation Functions ---

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

// Get the position in the class
$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['total'] != $previous_score && $previous_score !== null) {
        $position++;
    }

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

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

// Grading Logic
function getGrade($score) {
    if ($score >= 80) return 'A';
    if ($score >= 70) return 'B';
    if ($score >= 60) return 'C';
    if ($score >= 50) return 'D';
    if ($score >= 40) return 'E';
    return 'F';
}

// --- HTML Content Generation (using Heredoc for clean string management) ---

$student_name_upper = strtoupper(htmlentities($student['studentName']));
$student_no_upper = strtoupper(htmlentities($student['studentno']));
$class_upper = strtoupper($class);
$section_upper = strtoupper($section);
$selected_term_upper = strtoupper($selected_term);
$selected_session_upper = strtoupper($selected_session);
$student_image_html = htmlentities($studentImage);
$total_obtainable = $total_subjects * 100;
$average_score_rounded = $average_score;
$remarks_html = htmlentities($class_teacher_remarks);


$html = <<<EOD
<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>Score Sheet</title>
    <link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css'>
    <style>
        body { font-family: sans-serif; }
        @media print {
            body {
                -webkit-print-color-adjust: exact;
            }
        }
        .card-header h1 { margin-bottom: 0; }
        .table-bordered th, .table-bordered td { border: 1px solid #000 !important; }
        .row { display: flex; flex-wrap: wrap; margin-left: -15px; margin-right: -15px; }
        .col-md-4, .col-md-8, .col-md-12 { padding-left: 15px; padding-right: 15px; }
    </style>
</head>
<body>
<section class='content'>
    <div class='container-fluid'>
        <div class='card shadow-sm'>
            <div id='result-content'>
                <div class='card border-5' style='position: relative;'>
                    <img src='$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;'>

                    <div style='position: relative; z-index: 1;'>
                        <div class='card-header text-center'>
                            <img src=' $logo' width='70' height ='70' alt='School Logo'>
                            <h1><strong> $school_name</strong></h1>
                            $address
                        </div>

                        <div class='card-body'>
                            <h5 class='text-center'><strong>STATEMENT OF EXAMINATION RESULTS</strong></h5>
                            <hr>
                            <div class='row mb-3'>
                                <div class='col-md-8'>
                                    <div class='row'>
                                        <div class='col-md-8'>
                                            <strong> STUDENT'S NAME:</strong> $student_name_upper
                                        </div>
                                        <div class='col-md-4'>
                                            <strong>ADMISSION NO:</strong> $student_no_upper
                                        </div>
                                        <div class='col-md-8'>
                                            <strong> CLASS:</strong> $class_upper
                                        </div>
                                        <div class='col-md-4'>
                                            <strong>ARM:</strong> $section_upper
                                        </div>
                                    </div>
                                    <div class='row'>
                                        <div class='col-md-8'>
                                            <strong>TERM:</strong> $selected_term_upper
                                        </div>
                                        <div class='col-md-4'>
                                            <strong>SESSION:</strong> $selected_session_upper
                                        </div>
                                    </div>
                                </div>
                                
                                <div class='col-md-4 text-right'>
                                    <img src='$student_image_html' class='img-thumbnail' width='100' alt='Passport Photo'>
                                </div>
                            </div>
                            
                            <div>
                                <table class='table table-bordered text-center' id='example1'>
                                    <thead class='thead-dark'>
                                        <tr>
                                            <th>SN</th>
                                            <th>SUBJECT</th>
                                            <th>TEST</th>
                                            <th>CLASS PERF</th>
                                            <th>WEEKLY</th>
                                            <th>EXAM</th>
                                            <th>TOTAL</th>
                                            <th>GRADE</th>
                                        </tr>
                                    </thead>
                                    <tbody>
EOD;

                                    // Inserting the PHP loop logic back into the HTML string
                                    $sn = 1;
                                    foreach ($results as $row) {
                                        $html .= "<tr>
                                            <td>" . $sn++ . "</td>
                                            <td>" . strtoupper($row['subject']) . "</td>
                                            <td>" . htmlentities($row['test_score']) . "</td>
                                            <td>" . htmlentities($row['class_performance']) . "</td>
                                            <td>" . htmlentities($row['weekly_assessment']) . "</td>
                                            <td>" . htmlentities($row['exam_score']) . "</td>
                                            <td>" . htmlentities($row['total_score']) . "</td>
                                            <td>" . getGrade(htmlentities($row['total_score'])) . "</td>
                                        </tr>";
                                    }

$html .= <<<EOD
                                    </tbody>
                                </table>
                            </div>
                            
                            <div class='row mb-3'>
                                <div class='col-md-12'>
                                    <div class='row'>
                                        <div class='col-md-4'>
                                            <strong>Total Score:</strong> $total_score / $total_obtainable
                                        </div>
                                        <div class='col-md-4'>
                                            <strong>Average:</strong> $average_score_rounded
                                        </div>
                                        <div class='col-md-4'>
                                            <strong>Position in Class:</strong> $position_with_suffix
                                        </div>
                                    </div><br>
                                    <div class='row'>
                                        <div class='col-md-8'>
                                            <strong>Class Teacher Remarks: </strong>$remarks_html
                                        </div>
                                        <div class='col-md-4'>
                                            <strong>Signature: ______________________</strong>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
</body>
</html>
EOD;

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

?>