<?php
// DB Connection
$conn = new mysqli("localhost", "root", "", "rs_lab");
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

/*
 ACTIVE LEARNERS:
 - Practiced at least once in last 7 days
*/

$sql = "
SELECT 
    pa.roll_no,
    MAX(pa.last_attempt_at) AS last_practice_date,
    DATEDIFF(NOW(), MAX(pa.last_attempt_at)) AS days_gap
FROM practice_attempts pa
GROUP BY pa.roll_no
HAVING 
    MAX(pa.last_attempt_at) >= NOW() - INTERVAL 7 DAY
ORDER BY last_practice_date DESC
";

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

<!DOCTYPE html>
<html>
<head>
    <title>Active Learners</title>
    <style>
        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background: #0f172a;
            color: #e5e7eb;
        }
        h2 {
            text-align: center;
            margin-top: 40px;
            color: #22c55e;
        }
        .context {
            text-align: center;
            color: #9ca3af;
            margin-top: 10px;
        }
        table {
            width: 60%;
            margin: 30px auto;
            border-collapse: collapse;
            background: #020617;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 0 15px rgba(0,0,0,0.6);
        }
        th, td {
            padding: 14px;
            border-bottom: 1px solid #1e293b;
            text-align: left;
        }
        th {
            background: #14532d;
            color: #bbf7d0;
        }
        td {
            color: #e5e7eb;
        }
        .gap-good {
            color: #22c55e;
            font-weight: bold;
        }
        .empty {
            text-align: center;
            padding: 20px;
            color: #9ca3af;
        }
    </style>
</head>
<body>

<h2>🟢 Active Learners (Last 7 Days)</h2>
<div class="context">
    These students are maintaining learning continuity.
</div>

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

    <?php
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            echo "<tr>
                    <td>{$row['roll_no']}</td>
                    <td>{$row['last_practice_date']}</td>
                    <td class='gap-good'>{$row['days_gap']} day(s)</td>
                  </tr>";
        }
    } else {
        echo "<tr>
                <td colspan='3' class='empty'>No active learners yet</td>
              </tr>";
    }
    ?>

</table>

</body>
</html>

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