<?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');

if (!isset($_SESSION['sid']) || strlen($_SESSION['sid']) == 0) {
    header('location:logout.php');
    exit();
}

require_once('vendor/autoload.php');

use Dotenv\Dotenv;
use Mpdf\Mpdf;

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

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

if (!class_exists('ZipArchive')) {
    die('ZipArchive class is not enabled in PHP.');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['download_bulk'])) {
    $session_id = mysqli_real_escape_string($con, $_POST['session_id']);
    $term_id = mysqli_real_escape_string($con, $_POST['term_id']);
    $class = mysqli_real_escape_string($con, $_POST['class']);
    $section = mysqli_real_escape_string($con, $_POST['section']);

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

    $studentsQuery = mysqli_query($con, "SELECT * FROM students WHERE class = '$class' AND section = '$section'");
    $downloadFolder = 'downloads/' . uniqid('results_', true);
    mkdir($downloadFolder, 0777, true);

    function getPositionSuffix($position)
    {
        if (in_array($position % 100, [11, 12, 13])) {
            return $position . 'th';
        }
        switch ($position % 10) {
            case 1:
                return $position . 'st';
            case 2:
                return $position . 'nd';
            case 3:
                return $position . 'rd';
            default:
                return $position . 'th';
        }
    }

    function getGrade($score)
    {
        if ($score >= 90) return 'A+';
        elseif ($score >= 80) return 'A';
        elseif ($score >= 70) return 'B+';
        elseif ($score >= 60) return 'B';
        elseif ($score >= 50) return 'C+';
        elseif ($score >= 40) return 'C';
        elseif ($score >= 30) return 'D+';
        elseif ($score >= 20) return 'D';
        else return 'F';
    }

    while ($student = mysqli_fetch_assoc($studentsQuery)) {
        $student_id = $student['id'];
        $studentName = $student['studentName'];
        $studentImage = $student['studentImage'] ? 'studentimages/' . $student['studentImage'] : 'default.png';

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

        $results = [];
        $total_score = 0;
        $student_remark = '';

        while ($row = mysqli_fetch_assoc($resultQuery)) {
            $results[] = $row;
            $total_score += $row['total_score'];
            if (empty($student_remark)) {
                $student_remark = $row['remarks'];
            }
        }

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

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

        $position_with_suffix = getPositionSuffix($position);

        ob_start();
?>

        <!DOCTYPE html>
        <html>

        <head>
            <style>
                table {
                    width: 100%;
                    border-collapse: collapse;
                    font-size: 12px;
                }

                th,
                td {
                    padding: 8px;
                    text-align: center;
                }

                th {
                    background-color: #007bff;
                    color: white;
                }

                .text-center {
                    text-align: center;
                }

                .container {
                    width: 80%;
                    margin: auto;
                    border: 2px dotted #000;
                    padding: 20px;
                    line-height: 1.6;
                }
            </style>
        </head>

        <body>

            <div class="text-center">
                <img src="<?php echo $logo; ?>" width="70" height="70"><br>
                <h1><?php echo $school_name ?></h1>
                <b><i><?php echo $address ?></i></b><br>
            </div>

            <hr>
            <h5 class="text-center">STATEMENT OF EXAMINATION RESULTS</h5>
            <hr>

            <table style="width: 100%; border-collapse: collapse;">
                <tr>
                    <!-- Left Column -->
                    <td style="width: 50%; vertical-align: top; text-align: left;">
                        <strong>STUDENT'S NAME:</strong> <?= strtoupper($student['studentName']) ?><br><br>
                        <strong>CLASS:</strong> <?= strtoupper($class) ?><br><br>
                        <strong>TERM:</strong> <?= strtoupper($selected_term) ?>
                    </td>

                    <!-- Middle Column -->
                    <td style="width: 30%; vertical-align: top; text-align: left;">
                        <strong>ADMISSION NO:</strong> <?= strtoupper($student['studentno']) ?><br><br>
                        <strong>ARM:</strong> <?= strtoupper($section) ?><br><br>
                        <strong>SESSION:</strong> <?= strtoupper($selected_session) ?>
                    </td>

                    <!-- Right Column (Photo) -->
                    <td style="width: 20%; text-align: right;">
                        <img src="<?= $studentImage ?>" width="80" height="80" style="border-radius: 8px;" alt="Student Photo">
                    </td>
                </tr>
            </table>



            <table border="1">
                <thead>
                    <tr>
                        <th>SN</th>
                        <th>Subject</th>
                        <th>Test</th>
                        <th>Class Performance</th>
                        <th>Weekly Assessmrnt</th>
                        <th>Exam</th>
                        <th>Total</th>
                        <th>Grade</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $sn = 1;
                    foreach ($results as $r): ?>
                        <tr>
                            <td><?= $sn++ ?></td>
                            <td><?= strtoupper($r['subject']) ?></td>
                            <td><?= $r['test_score'] ?></td>
                            <td><?= $r['class_performance'] ?></td>
                            <td><?= $r['weekly_assessment'] ?></td>
                            <td><?= $r['exam_score'] ?></td>
                            <td><?= $r['total_score'] ?></td>
                            <td><?= getGrade($r['total_score']) ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <table style=" border-collapse: collapse; margin-top: 20px;">
                <tr>
                    <td style=" vertical-align: top; text-align:left;">
                        <strong>Total Score:</strong> <?= $total_score ?> / <?= $total_subjects * 100 ?>
                    </td>
                    <td style=" vertical-align: top; text-align:left;">
                        <strong>Average Score:</strong> <?= $average_score ?>
                    </td>
                    <td>

                    </td>

                    <td></td>

                    <td></td>
                    <td></td>
                    <td></td>
                    <td style=" vertical-align: top; text-align:left;">
                        <strong>Position in Class:</strong> <?= $position_with_suffix ?>
                    </td>
                </tr>
                <tr>
                    <td colspan="7" style=" vertical-align: top; text-align:left;">
                        <strong>Remarks:</strong> <?= htmlentities($r['remarks']) ?>
                    </td>
                    <td style=" vertical-align: top; text-align:left;">
                        <strong>Signature:</strong>
                        ___________________
                    </td>
                </tr>
            </table>



        </body>

        </html>

        </html>
<?php
        $content = ob_get_clean();
        $filePath = $downloadFolder . '/result_' . $studentName . '.pdf';

        try {
            $mpdf = new Mpdf();
            $mpdf->SetWatermarkImage($logo, 0.1, [100, 100], 'F');
            $mpdf->showWatermarkImage = true;
            $mpdf->WriteHTML($content);
            $mpdf->Output($filePath, 'F');
        } catch (Exception $e) {
            echo 'Error generating PDF: ' . $e->getMessage();
        }
    }

    $zipFile = 'downloads/result_bundle_' . uniqid() . '.zip';
    $zip = new ZipArchive();

    if ($zip->open($zipFile, ZipArchive::CREATE) === TRUE) {
        $pdfFiles = glob($downloadFolder . '/*.pdf');
        if (count($pdfFiles) > 0) {
            foreach ($pdfFiles as $file) {
                $zip->addFile($file, basename($file));
            }
            $zip->close();
            array_map('unlink', $pdfFiles);
            rmdir($downloadFolder);

            // Clear output buffers
            while (ob_get_level()) {
                ob_end_clean();
            }

            // Set headers and output the ZIP file
            header('Content-Type: application/zip');
            header('Content-Disposition: attachment; filename="' . basename($zipFile) . '"');
            header('Content-Length: ' . filesize($zipFile));
            flush();
            readfile($zipFile);
            unlink($zipFile);
            exit;
        } else {
            echo 'No PDFs generated.';
        }
    } else {
        echo 'Failed to create ZIP archive.';
    }
}
?>