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

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

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

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

    $new = $_POST['new_password'];
    $confirm = $_POST['confirm_password'];

    if ($new === "" || $confirm === "") {
        $error = "All fields required";
    } elseif ($new !== $confirm) {
        $error = "Passwords do not match";
    } else {

        $hash = password_hash($new, PASSWORD_DEFAULT);

        $stmt = $pdo->prepare("
            UPDATE institutions 
            SET password = ? 
            WHERE id = ?
        ");
        $stmt->execute([$hash, $_SESSION['institution_id']]);

        $success = "Password updated successfully";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Change Password | RS Learning Lab</title>
</head>
<body>

<h2>Change Password</h2>

<?php if ($error): ?>
<p style="color:red;"><?php echo $error; ?></p>
<?php endif; ?>

<?php if ($success): ?>
<p style="color:green;"><?php echo $success; ?></p>
<a href="/rs_lab/institution/dashboard.php">Go to Dashboard</a>
<?php endif; ?>

<form method="POST">
    <input type="password" name="new_password" placeholder="New Password" required><br><br>
    <input type="password" name="confirm_password" placeholder="Confirm Password" required><br><br>
    <button type="submit">Update Password</button>
</form>

</body>
</html>
