<?php
session_start();
include 'db_connection.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $regNumber = trim($_POST['regNumber']);

    $sql = "SELECT s.student_id, s.class_id, s.name, s.user_id, u.role
            FROM students s
            INNER JOIN users u ON s.user_id = u.user_id
            WHERE s.regNumber = ? LIMIT 1";

    $stmt = $conn->prepare($sql);

    if (!$stmt) {
        die("Prepare failed: " . $conn->error);
    }

    $stmt->bind_param("s", $regNumber);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 1) {

        $row = $result->fetch_assoc();

        /* ================= ROLE CHECK ================= */
        if ($row['role'] !== 'student') {
            header("Location: student_login.php?error=Access denied!");
            exit();
        }

        /* ================= SESSION ================= */
        $_SESSION['student_id'] = $row['student_id'];
        $_SESSION['class_id']   = $row['class_id'];
        $_SESSION['name']       = $row['name'];
        $_SESSION['role']       = $row['role'];

        /* ================= ONLINE STATUS ================= */
        $update = $conn->prepare("
            UPDATE students 
            SET online_status = 'online' 
            WHERE student_id = ?
        ");

        if ($update) {
            $update->bind_param("i", $row['student_id']);
            $update->execute();
        }

        header("Location: student_dashboard.php");
        exit();

    } else {
        header("Location: student_login.php?error=Invalid registration number");
        exit();
    }
}
?>