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

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

    $username = trim($_POST['username']);
    $password = $_POST['password'];

    $sql = "SELECT 
                u.user_id, 
                u.password, 
                u.role,
                t.teacher_id, 
                t.name
            FROM users u
            INNER JOIN teachers t ON u.user_id = t.user_id
            WHERE u.username = ? 
            LIMIT 1";

    if ($stmt = $conn->prepare($sql)) {

        $stmt->bind_param("s", $username);
        $stmt->execute();
        $stmt->store_result();

        $stmt->bind_result($user_id, $hashed_password, $role, $teacher_id, $name);

        if ($stmt->num_rows == 1) {
            $stmt->fetch();

            // ✅ STRICT ROLE CHECK (IMPORTANT)
            if ($role !== 'teacher') {
                $_SESSION['error'] = "Access denied. You are not authorized as a teacher.";
                header("Location: teacher_login.php");
                exit();
            }

            // Password verification
            if (password_verify($password, $hashed_password)) {

                // Set teacher session
                $_SESSION['user_id'] = $user_id;
                $_SESSION['teacher_id'] = $teacher_id;
                $_SESSION['name'] = $name;
                $_SESSION['role'] = $role;
                $_SESSION['logged_in'] = true;

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

            } else {
                $_SESSION['error'] = "Invalid password.";
            }

        } else {
            $_SESSION['error'] = "Invalid username or account does not exist.";
        }

        $stmt->close();
    } else {
        $_SESSION['error'] = "Database error occurred.";
    }

    $conn->close();
    header("Location: teacher_login.php");
    exit();
}
?>