<?php
session_start();
if (!isset($_SESSION['teacher_id'])) {
    header("Location: teacher_login.php");
    exit();
}

$conn = new mysqli("localhost", "root", "", "rs_lab");
if ($conn->connect_error) die("DB Connection failed");

/*
STATUS LOGIC:
Active   -> last practice <= 7 days
Slowing  -> 8–10 days
Stalled  -> >10 days OR never practiced
*/

$sql = "
SELECT 
    lp.roll_no,
    MAX(pa.last_attempt_at) AS last_practice,
    DATEDIFF(CURDATE(), MAX(pa.last_attempt_at)) AS days_gap
FROM learning_profiles lp
LEFT JOIN practice_attempts pa 
    ON pa.roll_no = lp.roll_no
GROUP BY lp.roll_no
ORDER BY days_gap DESC
";

$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html>
<head>
<title>Students | RS Learning Lab</title>
<style>
body{
margin:0;
font-family:Arial, sans-serif;
background:radial-gradient(circle at top,#020617,#0f172a);
color:#e5e7eb;
padding:40px;
}

h1{margin-bottom:6px}
.subtitle{color:#9ca3af;margin-bottom:25px}

table{
width:100%;
border-collapse:collapse;
background:#020617;
border-radius:18px;
overflow:hidden;
box-shadow:0 0 30px rgba(0,0,0,.7);
}

th,td{
padding:14px;
border-bottom:1px solid #1e293b;
font-size:14px;
text-align:left;
}

th{color:#cbd5f5}

tr:hover{
background:rgba(148,163,184,0.06);
}

.badge{
padding:6px 14px;
border-radius:999px;
font-size:12px;
font-weight:bold;
display:inline-block;
}

.active{
background:rgba(34,197,94,.18);
color:#22c55e;
}

.slowing{
background:rgba(234,179,8,.18);
color:#eab308;
}

.stalled{
background:rgba(239,68,68,.18);
color:#ef4444;
}

.back{
margin-bottom:20px;
}
.back a{
color:#60a5fa;
text-decoration:none;
font-size:14px;
}
</style>
</head>

<body>

<div class="back">
    <a href="teacher_dashboard.php">← Back to Dashboard</a>
</div>

<h1>Students</h1>
<div class="subtitle">
Learning behaviour overview (focus on consistency, not scores)
</div>

<table>
<tr>
    <th>Roll No</th>
    <th>Last Practice</th>
    <th>Days Since Last Practice</th>
    <th>Status</th>
</tr>

<?php while($row = $result->fetch_assoc()): 

    $days = $row['days_gap'];

    if ($row['last_practice'] === null) {
        $status = "stalled";
        $statusLabel = "Stalled";
    } elseif ($days <= 7) {
        $status = "active";
        $statusLabel = "Active";
    } elseif ($days <= 10) {
        $status = "slowing";
        $statusLabel = "Slowing";
    } else {
        $status = "stalled";
        $statusLabel = "Stalled";
    }
?>

<tr>
    <td>
  <a href="student_profile.php?roll_no=<?= urlencode($row['roll_no']) ?>"
     style="color:#60a5fa;text-decoration:none;">
     <?= htmlspecialchars($row['roll_no']) ?>
  </a>
</td>

    <td>
        <?= $row['last_practice'] ? date("d M Y", strtotime($row['last_practice'])) : "Never" ?>
    </td>
    <td>
        <?= $days !== null ? $days." days" : "—" ?>
    </td>
    <td>
        <span class="badge <?= $status ?>">
            <?= $statusLabel ?>
        </span>
    </td>
</tr>

<?php endwhile; ?>
</table>

</body>
</html>

<?php $conn->close(); ?>
