<?php
// export_teacher_pdf.php
// RS Learning Lab – Teacher Dashboard PDF Export (wkhtmltopdf)

$db_host = "localhost";
$db_name = "rs_learning_lab";
$db_user = "root";
$db_pass = "";

$class = $_GET['class'] ?? '10-A';

try {
    $pdo = new PDO(
        "mysql:host=$db_host;dbname=$db_name;charset=utf8mb4",
        $db_user,
        $db_pass,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );
} catch (PDOException $e) {
    die("DB connection failed");
}

$stmt = $pdo->prepare("
    SELECT 
        lp.roll_no,
        lp.student_name,
        lm.momentum_state,
        lm.momentum_score
    FROM learning_profiles lp
    LEFT JOIN learning_momentum lm
        ON lp.roll_no = lm.roll_no
    WHERE lp.class = :class
    ORDER BY lp.roll_no ASC
");
$stmt->execute([':class' => $class]);
$students = $stmt->fetchAll();

$html = "
<h2>RS Learning Lab – Class Momentum Report</h2>
<p>Class: {$class}</p>
<table border='1' cellpadding='8' cellspacing='0' width='100%'>
<tr>
    <th>Roll No</th>
    <th>Student Name</th>
    <th>Momentum State</th>
    <th>Momentum Score</th>
</tr>
";

foreach ($students as $s) {
    $html .= "
    <tr>
        <td>{$s['roll_no']}</td>
        <td>{$s['student_name']}</td>
        <td>".($s['momentum_state'] ?? 'Building')."</td>
        <td>".($s['momentum_score'] ?? 50)."</td>
    </tr>
    ";
}

$html .= "</table>";

$tmp = __DIR__ . "/teacher_report.html";
$pdf = __DIR__ . "/Class_{$class}_Momentum_Report.pdf";

file_put_contents($tmp, $html);

shell_exec("wkhtmltopdf \"$tmp\" \"$pdf\"");

header("Content-Type: application/pdf");
header("Content-Disposition: inline; filename=Class_Momentum_Report.pdf");
readfile($pdf);
exit;
