<?php
// export_teacher_excel.php
// RS Learning Lab – Teacher Dashboard Excel Export

$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,
        lp.class,
        lm.momentum_state,
        lm.momentum_score,
        lm.updated_at
    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]);
$data = $stmt->fetchAll();

header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=Class_{$class}_Momentum_Report.xls");

echo "Roll No\tStudent Name\tClass\tMomentum State\tMomentum Score\tLast Activity\n";

foreach ($data as $row) {
    echo
        $row['roll_no'] . "\t" .
        $row['student_name'] . "\t" .
        $row['class'] . "\t" .
        ($row['momentum_state'] ?? 'Building') . "\t" .
        ($row['momentum_score'] ?? 50) . "\t" .
        ($row['updated_at'] ?? '-') . "\n";
}
exit;
