<?php
session_start();
require_once '../db_config.php';

if (!isset($_SESSION['institution_id'])) {
    die("Unauthorized");
}

$error = "";

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

    $new = trim($_POST['new_password'] ?? '');
    $confirm = trim($_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_hash = ?, first_login = 0 
            WHERE id = ?
        ");
        $stmt->execute([$hash, $_SESSION['institution_id']]);

        header("Location: dashboard.php");
        exit;
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Change Password</title>
    <style>
        body {
            background: radial-gradient(circle at top, #0c1a2b, #050b14);
            color: #eaf2ff;
            font-family: Inter, sans-serif;
        }
        .box {
            width: 400px;
            margin: 120px auto;
            background: rgba(255,255,255,0.05);
            padding: 30px;
            border-radius: 14px;
        }
        input, button {
            width: 100%;
            padding: 12px;
            margin-top: 12px;
            border-radius: 8px;
            border: none;
        }
        button {
            background: linear-gradient(135deg, #22c55e, #16a34a);
            font-weight: bold;
        }
        .error {
            color: #f87171;
            margin-top: 10px;
        }
    </style>
</head>

<body>
<div class="box">
    <h2>Change Password</h2>

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

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