<?php
session_start();
require_once(__DIR__ . "/../config/db.php");

if (!isset($_SESSION['teacher_id'])) {
    header("Location: /rs_lab/teacher/login.php");
    exit;
}

/* Get teacher */
$stmt = $pdo->prepare("
    SELECT username, class_handled
    FROM teachers
    WHERE id = ?
");
$stmt->execute([$_SESSION['teacher_id']]);
$teacher = $stmt->fetch(PDO::FETCH_ASSOC);

$class = $teacher['class_handled'];

/* Total */
$stmt = $pdo->prepare("SELECT COUNT(*) FROM students WHERE class = ?");
$stmt->execute([$class]);
$total_students = $stmt->fetchColumn();

/* Active */
$stmt = $pdo->prepare("
    SELECT COUNT(DISTINCT pa.roll_no)
    FROM practice_attempts pa
    JOIN students s ON s.roll_no = pa.roll_no
    WHERE s.class = ?
      AND pa.last_attempt_at >= NOW() - INTERVAL 7 DAY
");
$stmt->execute([$class]);
$active = $stmt->fetchColumn();

/* Slowing */
$stmt = $pdo->prepare("
    SELECT COUNT(DISTINCT pa.roll_no)
    FROM practice_attempts pa
    JOIN students s ON s.roll_no = pa.roll_no
    WHERE s.class = ?
      AND pa.last_attempt_at BETWEEN
          NOW() - INTERVAL 10 DAY AND NOW() - INTERVAL 8 DAY
");
$stmt->execute([$class]);
$slowing = $stmt->fetchColumn();

/* Stalled */
$stmt = $pdo->prepare("
    SELECT COUNT(*)
    FROM (
        SELECT pa.roll_no
        FROM practice_attempts pa
        JOIN students s ON s.roll_no = pa.roll_no
        WHERE s.class = ?
        GROUP BY pa.roll_no
        HAVING MAX(pa.last_attempt_at) < NOW() - INTERVAL 10 DAY
    ) t
");
$stmt->execute([$class]);
$stalled = $stmt->fetchColumn();
?>

<!DOCTYPE html>
<html>
<head>
<title>Reports</title>

<style>
body{
    background:#020617;
    color:white;
    font-family:Arial;
}
.container{
    width:900px;
    margin:60px auto;
}
.cards{
    display:flex;
    gap:20px;
}
.card{
    flex:1;
    background:#0f172a;
    padding:25px;
    border-radius:14px;
    text-align:center;
}
.green{border-left:6px solid #22c55e;}
.yellow{border-left:6px solid #eab308;}
.red{border-left:6px solid #ef4444;}
</style>

</head>

<body>

<div class="container">

<h2>Reports</h2>

<div class="cards">

<div class="card green">
<p>Total Students</p>
<h2><?= $total_students ?></h2>
</div>

<div class="card green">
<p>Active Learners</p>
<h2><?= $active ?></h2>
</div>

<div class="card yellow">
<p>Slowing Learners</p>
<h2><?= $slowing ?></h2>
</div>

<div class="card red">
<p>Stalled Learners</p>
<h2><?= $stalled ?></h2>
</div>

</div>

</div>

</body>
</html>