<?php
session_start();
require_once(__DIR__ . "/../config/db.php");

$error = "";

/* Already logged in */
if (isset($_SESSION['teacher_id'])) {
    header("Location: /rs_lab/teacher/dashboard.php");
    exit;
}

/* HANDLE LOGIN */
if ($_SERVER["REQUEST_METHOD"] === "POST") {

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

    if ($username === "" || $password === "") {
        $error = "Username and password required";
    } else {

        $stmt = $pdo->prepare("
            SELECT id, password_hash, must_change_password
            FROM teachers
            WHERE username = ?
            LIMIT 1
        ");
        $stmt->execute([$username]);
        $teacher = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($teacher && password_verify($password, $teacher['password_hash'])) {

            $_SESSION['teacher_id'] = $teacher['id'];

            if ((int)$teacher['must_change_password'] === 1) {
                header("Location: /rs_lab/teacher/change_password.php");
            } else {
                header("Location: /rs_lab/teacher/dashboard.php");
            }
            exit;

        } else {
            $error = "Invalid login credentials";
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Teacher Login | RS Learning Lab</title>
    <style>
        body {
            background: radial-gradient(circle at top, #0f172a, #020617);
            font-family: Arial;
            color: #e5e7eb;
        }
        .box {
            width: 400px;
            margin: 90px auto;
            background: rgba(15,23,42,.95);
            padding: 30px;
            border-radius: 14px;
            box-shadow: 0 0 40px rgba(11,140,159,.25);
        }
        input, button {
            width: 100%;
            padding: 12px;
            margin-top: 12px;
            border-radius: 8px;
            border: 1px solid #334155;
            background: #020617;
            color: #fff;
        }
        button {
            background: linear-gradient(135deg,#2563eb,#22c55e);
            border: none;
            cursor: pointer;
        }
        .err {
            color: #f87171;
            text-align: center;
        }
    </style>
</head>
<body>

<div class="box">
    <h2>Teacher Login</h2>

    <?php if ($error): ?>
        <p class="err"><?= htmlspecialchars($error) ?></p>
    <?php endif; ?>

    <!-- ✅ FIXED: correct form action -->
    <form method="POST">
        <input type="text" name="username" placeholder="Teacher Username" required>
        <input type="password" name="password" placeholder="Password" required>
        <button type="submit">Login</button>
    </form>
</div>

</body>
</html>