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

// only institution access
if (!isset($_SESSION['institution_id'])) {
    header("Location: /rs_lab/institution/login.php");
    exit;
}

$success = "";
$error = "";

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

    $teacher_name  = trim($_POST['teacher_name'] ?? '');
    $class_handled = trim($_POST['class_handled'] ?? '');

    if ($teacher_name == "" || $class_handled == "") {
        $error = "All fields required";
    } else {

        // ✅ better username (unique)
        $username = strtolower(str_replace(" ", "", $teacher_name)) . "_" . $class_handled . rand(100,999);

        // ✅ temp password
        $tempPassword = substr(str_shuffle("ABCDEFGHJKLMNPQRSTUVWXYZ23456789"), 0, 6);

        // ✅ HASH password (IMPORTANT)
        $password_hash = password_hash($tempPassword, PASSWORD_DEFAULT);

        $stmt = $pdo->prepare("
            INSERT INTO teachers 
            (institution_id, username, class_handled, password_hash, temp_password, must_change_password)
            VALUES (?, ?, ?, ?, ?, 1)
        ");

        try {
            $stmt->execute([
                $_SESSION['institution_id'],
                $username,
                $class_handled,
                $password_hash,
                $tempPassword
            ]);

            $success = "Teacher Created ✅ <br>
                        Username: $username <br>
                        Password: $tempPassword";

        } catch (PDOException $e) {
            $error = "Username exists or DB error";
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Add Teacher</title>

<style>
body{
    background:#0f172a;
    font-family:Arial;
    color:white;
    display:flex;
    justify-content:center;
    align-items:center;
    height:100vh;
}

.box{
    background:#020617;
    padding:30px;
    border-radius:12px;
    width:350px;
}

input, select{
    width:100%;
    padding:10px;
    margin-top:10px;
    background:#0f172a;
    color:white;
    border:none;
    border-radius:6px;
}

button{
    width:100%;
    padding:12px;
    margin-top:15px;
    background:#22c55e;
    border:none;
    border-radius:8px;
    cursor:pointer;
}

.success{color:lightgreen;}
.error{color:red;}
</style>

</head>

<body>

<div class="box">

<h2>Add Teacher</h2>

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

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

<form method="POST">

<input type="text" name="teacher_name" placeholder="Teacher Name" required>

<select name="class_handled" required>
<option value="">Select Class</option>
<option value="6">Class 6</option>
<option value="7">Class 7</option>
<option value="8">Class 8</option>
<option value="9">Class 9</option>
<option value="10">Class 10</option>
<option value="11">Class 11</option>
<option value="12">Class 12</option>
</select>

<button type="submit">Create Teacher</button>

</form>

</div>

</body>
</html>