<?php
require_once("../../includes/config.php");
require_once("../../includes/auth_check.php");
require_once '../../dompdf/vendor/autoload.php';

use Dompdf\Dompdf;
use Dompdf\Options;

/* 1. Parameters */
$class_id = filter_input(INPUT_GET, 'class_id', FILTER_VALIDATE_INT);
$term_id = filter_input(INPUT_GET, 'term_id', FILTER_VALIDATE_INT);
$medium_id = filter_input(INPUT_GET, 'medium_id', FILTER_VALIDATE_INT);
$section_id = filter_input(INPUT_GET, 'section_id', FILTER_VALIDATE_INT);

if (!$class_id || !$term_id || !$medium_id) {
    die("Error: Missing required filters");
}

/* 2. Fetch School & Metadata */
$school = $pdo->query("SELECT * FROM school_settings LIMIT 1")->fetch(PDO::FETCH_ASSOC);
/* --- Signature Image Logic --- */
$signaturePath = "../../uploads/settings/" . $school['principal_signature'];
$base64Sig = "";

if (!empty($school['principal_signature']) && file_exists($signaturePath)) {
    $type = pathinfo($signaturePath, PATHINFO_EXTENSION);
    $data = file_get_contents($signaturePath);
    $base64Sig = 'data:image/' . $type . ';base64,' . base64_encode($data);
}
$className = $pdo->query("SELECT class_name FROM classes WHERE id = $class_id")->fetchColumn();
$termName = $pdo->query("SELECT term_name FROM exam_terms WHERE id = $term_id")->fetchColumn();
$mediumName = $pdo->query("SELECT medium_name FROM mediums WHERE id = $medium_id")->fetchColumn();
$max_per_sub = (int) ($pdo->query("SELECT max_marks FROM exam_terms WHERE id = $term_id")->fetchColumn() ?: 100);

$isAnnual = ($max_per_sub === 100);
$passThreshold = $max_per_sub * 0.3;

/* 3. Subjects */
$stmtSub = $pdo->prepare("SELECT id, subject_name FROM subjects WHERE class_id = ? ORDER BY id ASC");
$stmtSub->execute([$class_id]);
$subjectsList = $stmtSub->fetchAll(PDO::FETCH_ASSOC);

/* 4. Query Students */
$sql = "SELECT 
            s.id AS sid, e.roll_no, s.student_name, sub.id AS subject_id,
            IFNULL(m.theory_marks, 0) AS th, IFNULL(m.practical_marks, 0) AS pr
        FROM enrollments e
        INNER JOIN students s ON s.id = e.student_id
        INNER JOIN subjects sub ON sub.class_id = e.class_id
        LEFT JOIN marks_entry m ON m.student_id = s.id 
            AND m.subject_id = sub.id 
            AND m.exam_term_id = :term
            AND m.academic_year_id = :year
        WHERE e.class_id = :class 
          AND e.medium_id = :medium 
          AND s.status = 1";

if ($section_id > 0)
    $sql .= " AND e.section_id = :section";
$sql .= " ORDER BY CAST(e.roll_no AS UNSIGNED) ASC";

$stmt = $pdo->prepare($sql);
$params = [
    ':term' => $term_id,
    ':class' => $class_id,
    ':medium' => $medium_id,
    ':year' => APP_YEAR_ID
];
if ($section_id > 0)
    $params[':section'] = $section_id;

$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* Organize student data */
$students = [];
foreach ($rows as $row) {
    $sid = $row['sid'];
    if (!isset($students[$sid])) {
        $students[$sid] = [
            'roll' => $row['roll_no'],
            'name' => $row['student_name'],
            'marks' => []
        ];
    }
    $students[$sid]['marks'][$row['subject_id']] = [
        'th' => $row['th'],
        'pr' => $row['pr'],
        'tot' => $row['th'] + $row['pr']
    ];
}

/* 5. HTML + CSS */
$html = '<html><head><style>
/* ================================
   PAGE SETUP
================================ */
@page {
    size: A4 portrait;
    margin: 0;
}

* {
    box-sizing: border-box;
    -webkit-print-color-adjust: exact;
}

body {
    margin: 0;
    padding: 0;
    font-family: Helvetica, Arial, sans-serif;
}

/* ================= PAGE ================= */
.page-wrapper {
    position: relative;
    width: 210mm;
    height: 297mm;
    page-break-after: always;
}

/* ================= BORDERS ================= */
.outer-border {
    position: absolute;
    top: 10mm;
    left: 10mm;
    right: 10mm;
    bottom: 10mm;
    border: 3px solid #000;
}

.inner-border {
    position: absolute;
    top: 3mm;
    left: 3mm;
    right: 3mm;
    bottom: 25mm;
    border: 1px solid #000;

    /* 🔥 VERY IMPORTANT */
    padding: 8mm;
    padding-bottom: 30mm; /* reserve footer space */

   
}

/* ================= WATERMARK ================= */
.watermark {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) rotate(-30deg);
    font-size: 60px;
    font-weight: bold;
    color: rgba(0, 0, 0, 0.06);
    z-index: 0;
    white-space: nowrap;
}

/* ================= HEADER ================= */
.header {
    text-align: center;
    border-bottom: 2px solid #000;
    padding-bottom: 8px;
    margin-bottom: 12px;
}

.school-name {
    font-size: 22px;
    font-weight: bold;
    margin: 0;
}

.report-title {
    font-size: 17px;
    font-weight: bold;
    text-decoration: underline;
    margin: 8px 0;
}

/* ================= TABLES ================= */
.info-table td {
    font-size: 13px;
    padding: 4px;
}

.marks-table {
    width: 100%;
    border-collapse: collapse;
}

.marks-table th,
.marks-table td {
    border: 1px solid #000;
    padding: 6px;
    font-size: 12px;
    text-align: center;
}

.marks-table th {
    background: #f2f2f2;
}

.result-section {
    margin-top: 12px;
    border: 1px solid #000;
}

.result-table td {
    padding: 8px;
    border: 1px solid #000;
}

/* ================= FOOTER ================= */
.footer {
    position: absolute;
    bottom: 30mm;
    left: 8mm;
    right: 8mm;
}

.footer-table {
    width: 100%;
    border-collapse: collapse;
}

.footer-table td {
    width: 33.33%;
    text-align: center;
    font-size: 13px;
    vertical-align: bottom;
}

.sig-line {
    border-top: 1.5px solid #000;
    width: 80%;
    margin: 0 auto;
    padding-top: 4px;
    font-weight: bold;
}

</style></head><body>';

foreach ($students as $st) {

    $rowTotal = 0;
    $allPassed = true;
    $grandMax = count($subjectsList) * $max_per_sub;

    $html .= '<div class="page-wrapper" >
                <div class="outer-border">
                <div class="inner-border"><div class="watermark">'.htmlspecialchars($school['school_name']).'</div>

                <div class="header">
                    <div class="school-name">' . htmlspecialchars($school['school_name']) . '</div>
                    <div style="font-size:10px;">' . htmlspecialchars($school['school_address']) . '</div>
                </div>

                <div class="report-title">PROGRESS REPORT</div>';

    /* Student Info */
    $html .= '<table class="info-table" width="100%">
                <tr>
                    <td width="15%"><b>NAME:</b></td><td width="45%">' . $st['name'] . '</td>
                    <td width="20%"><b>ROLL NO:</b></td><td>' . $st['roll'] . '</td>
                </tr>
                <tr>
                    <td><b>CLASS:</b></td><td>' . $className . '</td>
                    <td><b>MEDIUM:</b></td><td>' . $mediumName . '</td>
                </tr>
                <tr>
                    <td><b>EXAM:</b></td><td>' . $termName . '</td>
                    <td><b>SESSION:</b></td><td>' . APP_YEAR_ID . '</td>
                </tr>
              </table>';

    /* Marks Table */
    $html .= '<table class="marks-table">
                <tr>
                    <th style="text-align:left;">SUBJECT</th>
                    <th>MAX</th>
                    <th>TH</th>
                    <th>PR</th>
                    <th>TOTAL</th>
                </tr>';

    foreach ($subjectsList as $sub) {
        $m = $st['marks'][$sub['id']] ?? ['th' => 0, 'pr' => 0, 'tot' => 0];
        $tot = $m['tot'];
        $rowTotal += $tot;

        if ($tot < $passThreshold)
            $allPassed = false;

        $html .= '<tr>
                    <td style="text-align:left;">' . $sub['subject_name'] . '</td>
                    <td>' . $max_per_sub . '</td>
                    <td>' . $m['th'] . '</td>
                    <td>' . $m['pr'] . '</td>
                    <td ' . ($tot < $passThreshold ? 'class="fail-text"' : '') . '><b>' . $tot . '</b></td>
                  </tr>';
    }

    $perc = ($rowTotal / $grandMax) * 100;
    $result = $allPassed ? 'PASSED' : 'FAILED';

    $html .= '</table>

              <div class="result-section">
                <table class="result-table">
                    <tr>
                        <td><b>GRAND TOTAL</b><br>' . $rowTotal . ' / ' . $grandMax . '</td>
                        <td><b>PERCENTAGE</b><br>' . round($perc, 2) . '%</td>
                        <td><b>RESULT</b><br><span style="color:' . ($result == 'FAILED' ? 'red' : 'black') . '">' . $result . '</span></td>
                    </tr>
                </table>
              </div>

              <div class="footer">
                <table class="footer-table" width="100%">
                    <tr>
                        <td><div class="sig-line">Class Teacher</div></td>
                        <td>(School Seal)</td>
                        <td>
                         ' . ($base64Sig ? '<img src="' . $base64Sig . '" height="45"><br>' : '<div style="height:45px;"></div>') . '
                                <div class="sig-line">Principal</div>
                         </td>
                    </tr>
                </table>
              </div>

              </div></div></div>';
}

$html .= '</body></html>';

/* PDF */
$options = new Options();
$options->set('isHtml5ParserEnabled', true);
$options->set('isRemoteEnabled', true);

$dompdf = new Dompdf($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();

ob_end_clean();
$dompdf->stream("Class_" . $className . "_Marksheets.pdf", ["Attachment" => false]);
?>