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

$error = "";

/* Already logged in */
if (isset($_SESSION['institution_id'])) {
    header("Location: /rs_lab/institution/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 {

        /* 🔥 UPDATED: temp_password also fetch */
        $stmt = $pdo->prepare("
            SELECT id, password_hash, temp_password
            FROM institutions
            WHERE username = ?
            LIMIT 1
        ");
        $stmt->execute([$username]);
        $inst = $stmt->fetch(PDO::FETCH_ASSOC);

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

            $_SESSION['institution_id'] = $inst['id'];

            /* 🔥 CLEAR TEMP PASSWORD AFTER FIRST LOGIN */
            if (!empty($inst['temp_password'])) {
                $clear = $pdo->prepare("
                    UPDATE institutions 
                    SET temp_password = NULL 
                    WHERE id = ?
                ");
                $clear->execute([$inst['id']]);
            }

            header("Location: /rs_lab/institution/dashboard.php");
            exit;

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

<!DOCTYPE html>
<html>
<head>
<title>Institution Login</title>
<style>
body{
    background:#020617;
    font-family:Arial;
    color:white;
    display:flex;
    justify-content:center;
    align-items:center;
    height:100vh;
}
.box{
    background:#0f172a;
    padding:30px;
    border-radius:12px;
    width:350px;
}
input{
    width:100%;
    padding:10px;
    margin-top:10px;
    background:#020617;
    color:white;
    border:none;
    border-radius:6px;
}
button{
    width:100%;
    padding:12px;
    margin-top:15px;
    background:#2563eb;
    border:none;
    border-radius:8px;
    cursor:pointer;
}
.error{color:red;}
</style>
</head>

<body>

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

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

<form method="POST">
<input type="text" name="username" placeholder="Institution Username" required>
<input type="password" name="password" placeholder="Password" required>
<button type="submit">Login</button>
</form>

</div>

</body>
</html>