<?php
session_start();
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/vendor/autoload.php';

use Dompdf\Dompdf;

if (!isset($_SESSION['user_id'])) {
    exit("Unauthorized");
}

// Fetch data
$stmt = $pdo->prepare("
    SELECT roll_number, student_name, learning_style
    FROM learning_styles
    WHERE user_id = ?
    ORDER BY roll_number
");
$stmt->execute([$_SESSION['user_id']]);
$students = $stmt->fetchAll(PDO::FETCH_ASSOC);

// HTML for PDF
$html = '
<style>
    body { font-family: DejaVu Sans, sans-serif; }
    h2 { text-align:center; }
    table { width:100%; border-collapse: collapse; margin-top:20px; }
    th, td { border:1px solid #444; padding:8px; font-size:12px; }
    th { background:#f2f2f2; }
</style>

<h2>RS Learning Lab – Class Learning Report</h2>

<p><strong>Teacher:</strong> '.htmlspecialchars($_SESSION['teacher_name']).'</p>
<p><strong>Class:</strong> '.htmlspecialchars($_SESSION['class_name']).'</p>
<p><strong>Date:</strong> '.date("d M Y").'</p>

<table>
<tr>
    <th>Roll No</th>
    <th>Student Name</th>
    <th>Learning Style</th>
</tr>
';

foreach ($students as $s) {
    $html .= '
    <tr>
        <td>'.htmlspecialchars($s['roll_number']).'</td>
        <td>'.htmlspecialchars($s['student_name']).'</td>
        <td>'.htmlspecialchars($s['learning_style']).'</td>
    </tr>
    ';
}

$html .= '</table>';

// Generate PDF
$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream("Class_Learning_Report.pdf", ["Attachment" => true]);
