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

if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: admin_login.php");
    exit;
}

if (!isset($_GET['id'])) {
    die("Invalid request");
}

$institution_id = (int) $_GET['id'];

/* Fetch institution */
$stmt = $pdo->prepare("SELECT institution_name, institution_type FROM institutions WHERE id = ?");
$stmt->execute([$institution_id]);
$inst = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$inst) {
    die("Institution not found");
}

/* Generate credentials */
$username = strtoupper(substr($inst['institution_type'], 0, 3)) . "_RS_" . $institution_id;
$password_plain = substr(str_shuffle("ABCDEFGHJKLMNPQRSTUVWXYZ23456789"), 0, 8);
$password_hash = password_hash($password_plain, PASSWORD_DEFAULT);

/* Save credentials */
$update = $pdo->prepare("
    UPDATE institutions
    SET username = ?, password_hash = ?, credentials_created = 1
    WHERE id = ?
");
$update->execute([$username, $password_hash, $institution_id]);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Credentials Generated</title>
    < style >
        body {
            background: #050b14;
            color: #eaf2ff;
            font-family: Inter, sans-serif;
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
        }

        .card {
            background: rgba(255,255,255,0.05);
            padding: 30px 40px;
            border-radius: 14px;
            text-align: center;
            width: 420px;
        }

        h2 {
            margin-bottom: 10px;
        }

        p {
            color: #b8c6de;
            font-size: 14px;
        }

        .cred {
            margin-top: 20px;
            font-size: 15px;
            background: rgba(255,255,255,0.08);
            padding: 14px;
            border-radius: 10px;
        }

        a {
            display: inline-block;
            margin-top: 20px;
            color: #7fd4ff;
            text-decoration: none;
        }
    </ style >
</head>

<body>

<div class="card">
    <h2>Credentials Created</h2>
    <p>Send these credentials to the institution</p>

    <div class="cred">
        <strong>Username:</strong><br><?= $username ?><br><br>
        <strong>Password:</strong><br><?= $password_plain ?>
    </div>

    <p style="margin-top:14px;font-size:12px;">
        Institution will be forced to change password on first login.
    </p>

    <a href="admin_dashboard.php">← Back to Dashboard</a>
</div>

</body>
</html>
