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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Prepare and execute query to get teacher details
    $sql = "SELECT teacher_id, password FROM teachers WHERE username = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->store_result();
    
    // Check if username exists
    if ($stmt->num_rows > 0) {
        $stmt->bind_result($teacher_id, $hashed_password);
        $stmt->fetch();
        
        // Verify password
        if (password_verify($password, $hashed_password)) {
            // Set session variables
            $_SESSION['teacher_id'] = $teacher_id;
            $_SESSION['username'] = $username;
            $_SESSION['role'] = 'teacher'; // Set role if needed
            
            // Redirect to teacher dashboard or another page
            header("Location: teacher_dashboard.php");
            exit();
        } else {
            $_SESSION['error'] = "Invalid password.";
        }
    } else {
        $_SESSION['error'] = "No account found with that username.";
    }

    // Close statement and connection
    $stmt->close();
    $conn->close();

    // Redirect back to login page with error
    header("Location: teacher_login.php");
    exit();
}
?>
