<?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. Get Parameters (stream_id removed)
$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 (Class, Term, or Medium)");
}

// 2. Fetch Metadata for Header
$school = $pdo->query("SELECT * FROM school_settings LIMIT 1")->fetch(PDO::FETCH_ASSOC);
$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();

// 3. Fetch Subjects (Stream logic removed - fetches all subjects for the class)
$stmtSub = $pdo->prepare("SELECT id, subject_name FROM subjects WHERE class_id = ? ORDER BY id ASC");
$stmtSub->execute([$class_id]);
$subjects = $stmtSub->fetchAll(PDO::FETCH_ASSOC);

// 4. Fetch Max Marks & Grades
$max_per_sub = (int)($pdo->query("SELECT max_marks FROM exam_terms WHERE id = $term_id")->fetchColumn() ?: 100);
$grades = $pdo->query("SELECT * FROM grading_system ORDER BY min_percentage DESC")->fetchAll(PDO::FETCH_ASSOC);

// 5. THE MAIN QUERY (Stream join and filter removed)
$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 e.academic_year_id = :year
            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);

// Build Matrix
$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' => (float)$row['th'],
        'pr' => (float)$row['pr'],
        'tot' => (float)$row['th'] + (float)$row['pr']
    ];
}

// 6. Build HTML (Landscape Layout)
$html = '<html><head><style>
    @page { size: A4 landscape; margin: 0.5cm; }
    body { font-family: "DejaVu Sans", sans-serif; font-size: 7px; color: #333; }
    .header { text-align: center; margin-bottom: 10px; }
    table { width: 100%; border-collapse: collapse; table-layout: fixed; }
    th, td { border: 1px solid #000; padding: 2px; text-align: center; word-wrap: break-word; }
    .bg-light { background-color: #f2f2f2; }
    .letter { color: red; font-weight: bold; font-size: 5px; }
</style></head><body>';

$html .= '<div class="header">
    <h2 style="margin:0;">'.htmlspecialchars($school['school_name']).'</h2>
    <p style="margin:2px;"><b>TABULATION SHEET:</b> '.$className.' | <b>MEDIUM:</b> '.$mediumName.' | <b>TERM:</b> '.$termName.'</p>
</div>';

$html .= '<table>
    <thead>
        <tr class="bg-light">
            <th rowspan="2" style="width:25px;">Roll</th>
            <th rowspan="2" style="width:100px;">Student Name</th>';
            foreach ($subjects as $sub) {
                $html .= '<th colspan="3">'.htmlspecialchars($sub['subject_name']).'</th>';
            }
$html .= '  <th rowspan="2" style="width:35px;">Total</th>
            <th rowspan="2" style="width:30px;">%</th>
            <th rowspan="2" style="width:45px;">Division</th>
        </tr>
        <tr class="bg-light">';
            foreach ($subjects as $sub) {
                $html .= '<th>TH</th><th>PR</th><th>TOT</th>';
            }
$html .= '</tr></thead><tbody>';

if (empty($students)) {
    $html .= '<tr><td colspan="'.(count($subjects)*3 + 5).'">No student records found for this filter.</td></tr>';
} else {
    foreach ($students as $st) {
        $rowTotal = 0;
        $html .= '<tr><td>'.$st['roll'].'</td><td style="text-align:left;">'.$st['name'].'</td>';
        
        foreach ($subjects as $sub) {
            $m = $st['marks'][$sub['id']] ?? null;
            if ($m) {
                $rowTotal += $m['tot'];
                $lMark = ($m['tot'] / $max_per_sub * 100 >= 80) ? '<span class="letter"> L</span>' : '';
                $html .= '<td>'.$m['th'].'</td><td>'.$m['pr'].'</td><td class="bg-light">'.$m['tot'].$lMark.'</td>';
            } else {
                $html .= '<td>-</td><td>-</td><td class="bg-light">-</td>';
            }
        }

        $perc = (count($subjects) > 0) ? ($rowTotal / (count($subjects) * $max_per_sub)) * 100 : 0;
        
        $div = "Failed";
        foreach ($grades as $g) {
            if ($perc >= $g['min_percentage'] && $perc <= $g['max_percentage']) {
                $div = $g['grade_name'];
                break;
            }
        }

        $html .= '<td style="font-weight:bold;">'.$rowTotal.'</td>
                  <td>'.round($perc, 1).'%</td>
                  <td>'.$div.'</td></tr>';
    }
}

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

// 7. Generate PDF
$options = new Options();
$options->set('isHtml5ParserEnabled', true);
$dompdf = new Dompdf($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'landscape');
$dompdf->render();

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