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

use Dompdf\Dompdf;
use Dompdf\Options;

$student_id = filter_input(INPUT_GET, 'student_id', FILTER_VALIDATE_INT);
$class_id   = filter_input(INPUT_GET, 'class_id', FILTER_VALIDATE_INT);
$term_id    = filter_input(INPUT_GET, 'term_id', FILTER_VALIDATE_INT);

if (!$student_id || !$class_id || !$term_id) die("Error: Missing Parameters");

// 1. Fetch Metadata
$school = $pdo->query("SELECT * FROM school_settings LIMIT 1")->fetch(PDO::FETCH_ASSOC);

$st = $pdo->query("SELECT s.student_name, s.father_name, e.roll_no, c.class_name, t.term_name, t.max_marks as term_ceiling 
                    FROM students s 
                    JOIN enrollments e ON e.student_id = s.id 
                    JOIN classes c ON e.class_id = c.id
                    JOIN exam_terms t ON t.id = $term_id
                    WHERE s.id = $student_id AND e.class_id = $class_id")->fetch(PDO::FETCH_ASSOC);

$subjects = $pdo->query("SELECT id, subject_name, theory_max, practical_max, pass_marks 
                         FROM subjects WHERE class_id = $class_id ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);

$marks_raw = $pdo->query("SELECT subject_id, theory_marks, practical_marks 
                          FROM marks_entry 
                          WHERE student_id = $student_id AND exam_term_id = $term_id")
                  ->fetchAll(PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC);

// --- LOGIC CONFIGURATION ---
$termMaxPerSub = (float)($st['term_ceiling'] ?? 100);
$isAnnual = (intval($st['term_ceiling']) === 100);
$passThreshold = $termMaxPerSub * 0.3; // 30% Pass Rule

// --- Prepare Base64 Principal Signature ---
$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);
}

// --- CSS & HTML ---
$html = '<html><head>
<style>
@page {
    size: A4 portrait;
    margin-right: 30mm;
}
* { box-sizing: border-box; }
body { font-family: Helvetica, sans-serif; margin: 0; padding: 0; background: #fff; }

/* Page wrapper */
.page-wrapper {
    padding: 8mm;
    width: 100%;
    position: relative;
}

/* Watermark */
.page-wrapper::before {
    content: "'.htmlspecialchars($school['school_name']).'";
    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);
    white-space: nowrap;
    z-index: 0;
}

/* ================= 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 */

   
}

/* Header */
.header { text-align: center; border-bottom: 2px solid #000; padding-bottom: 6px; margin-bottom: 8px; }
.school-name { font-size: 22px; font-weight: bold; text-transform: uppercase; margin: 0; }
.report-title { font-size: 17px; font-weight: bold; text-decoration: underline; margin: 8px 0; }

/* Info Table */
.info-table { width: 100%; margin-bottom: 6px; border-collapse: collapse; }
.info-table td { padding: 3px; font-size: 12px; }

/* Marks Table */
.marks-table { width: 100%; border-collapse: collapse; margin-bottom: 8px; }
.marks-table th, .marks-table td { border: 1px solid #000; padding: 5px; font-size: 12px; text-align: center; }
.marks-table th { background: #f2f2f2; }
.fail-text { color: red; font-weight: bold; }

/* Result Section */
.result-section { margin-top: 10px; border: 1px solid #000; }
.result-table td { padding: 8px; border: 1px solid #000; font-size: 13px; text-align: center; }

/* ================= 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>';

$html .= '<div class="page-wrapper">
    <div class="outer-border">
        <div class="inner-border">
            <div class="header">
                <h1 class="school-name">'.htmlspecialchars($school['school_name']).'</h1>
                <div style="font-size:11px;">'.htmlspecialchars($school['school_address']).'</div>
            </div>
            <div class="report-title">PROGRESS REPORT</div>

            <table class="info-table">
                <tr>
                    <td width="20%"><b>Student Name:</b></td><td width="35%">'.htmlspecialchars($st['student_name']).'</td>
                    <td width="20%"><b>Roll No:</b></td><td>'.$st['roll_no'].'</td>
                </tr>
                <tr>
                    <td><b>Father\'s Name:</b></td><td>'.htmlspecialchars($st['father_name']).'</td>
                    <td><b>Class:</b></td><td>'.$st['class_name'].'</td>
                </tr>
                <tr>
                    <td><b>Examination:</b></td><td>'.$st['term_name'].'</td>
                    <td><b>Session:</b></td><td>'.APP_YEAR_ID.'</td>
                </tr>
            </table>

            <table class="marks-table">
                <thead>
                    <tr>
                        <th style="text-align:left;">SUBJECTS</th>
                        <th>MAX</th>
                        <th>THEORY</th>
                        <th>PRACTICAL</th>
                        <th>TOTAL</th>
                    </tr>
                </thead>
                <tbody>';

$grandTotal = 0;
$allPassed = true;
$totalMaxPossible = count($subjects) * $termMaxPerSub;

foreach ($subjects as $sub) {
    $m = $marks_raw[$sub['id']] ?? ['theory_marks'=>0,'practical_marks'=>0];
    $total = (float)$m['theory_marks'] + (float)$m['practical_marks'];
    $grandTotal += $total;

    $isFail = ($total < $passThreshold);
    if ($isFail) $allPassed = false;

    $lMark = ($isAnnual && $total >= 80) ? '<span style="color:red;font-weight:bold;"> (L)</span>' : '';
    $totalStyle = $isFail ? 'class="fail-text"' : '';

    $html .= "<tr>
                <td style='text-align:left;'>".htmlspecialchars($sub['subject_name'])."</td>
                <td>".(int)$termMaxPerSub."</td>
                <td>".number_format($m['theory_marks'],2)."</td>
                <td>".number_format($m['practical_marks'],2)."</td>
                <td {$totalStyle}><b>".(int)$total.$lMark."</b></td>
              </tr>";
}

$percentage = ($totalMaxPossible>0) ? ($grandTotal/$totalMaxPossible)*100 : 0;
$division = "FAILED";
$honorsBadge = "";

if($allPassed){
    if($percentage>=60) $division="1st Division";
    elseif($percentage>=45) $division="2nd Division";
    elseif($percentage>=30) $division="3rd Division";

    if($isAnnual){
        if($percentage>=95) $honorsBadge="STAND MARK";
        elseif($percentage>=85) $honorsBadge="DISTINCTION";
        elseif($percentage>=75) $honorsBadge="STAR MARK";
    }
}

$html .= '</tbody></table>
<div class="result-section">
    <table class="result-table">
        <tr>
            <td width="33%"><b>GRAND TOTAL:</b><br>'.$grandTotal.' / '.$totalMaxPossible.'</td>
            <td width="33%"><b>PERCENTAGE:</b><br>'.round($percentage,2).'%</td>
            <td width="33%">
                <b>RESULT:</b><br>
                <span style="font-size:16px;font-weight:bold;color:'.($division=="FAILED"?'red':'black').';">'.$division.'</span>
                '.($honorsBadge?'<span class="badge">['.$honorsBadge.']</span>':'').'
            </td>
        </tr>
    </table>
</div>

<div class="footer">
    <table class="footer-table">
        <tr>
            <td><div class="sig-line">Class Teacher</div></td>
            <td><div style="font-size:10px;color:#999;">(School Seal)</div></td>
            <td>'.($base64Sig?'<img src="'.$base64Sig.'" style="height:50px;">':'<div style="height:50px;"></div>').'
                <div class="sig-line">Principal</div>
            </td>
        </tr>
    </table>
</div>

        </div> <!-- inner-border -->
    </div> <!-- outer-border -->
</div> <!-- page-wrapper -->
</body></html>';

// --- DOMPDF Rendering ---
$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("Marksheet_".$st['student_name'].".pdf", ["Attachment" => false]);
?>
