<?php
/**
 * bin/create_admin.php — create or reset a super-admin account from a browser.
 *
 * Place this file in the same location as the original script.
 * It continues to use ../config.php and the existing db() connection.
 *
 * IMPORTANT: Remove or restrict this file after use.
 */

require_once __DIR__ . '/../config.php';

$message = '';
$messageType = '';
$email = '';
$name = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim((string) ($_POST['email'] ?? ''));
    $name  = trim((string) ($_POST['name'] ?? ''));
    $pass  = (string) ($_POST['password'] ?? '');

    if ($email === '' || $name === '') {
        $message = 'Name and email are required.';
        $messageType = 'error';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $message = 'Invalid email address.';
        $messageType = 'error';
    } elseif (strlen($pass) < 8) {
        $message = 'Password must be at least 8 characters.';
        $messageType = 'error';
    } else {
        try {
            $hash = password_hash($pass, PASSWORD_BCRYPT);
            $db   = db();

            $exists = $db->prepare('SELECT id FROM admins WHERE email = ?');
            $exists->execute([$email]);
            $id = $exists->fetchColumn();

            if ($id) {
                $db->prepare("UPDATE admins SET password=?, role='super_admin', status='active', activation_token=NULL WHERE id=?")
                   ->execute([$hash, $id]);

                $message = "Updated existing account ({$email}) as active super_admin (ID {$id}).";
            } else {
                $db->prepare("INSERT INTO admins (name, email, password, role, status) VALUES (?,?,?,'super_admin','active')")
                   ->execute([$name, $email, $hash]);

                $message = "Created super_admin {$email} (ID " . $db->lastInsertId() . ').';
            }

            $messageType = 'success';
            $email = '';
            $name = '';
        } catch (Throwable $e) {
            error_log('Create admin error: ' . $e->getMessage());
            $message = 'The admin account could not be saved. Please check the database connection and server error log.';
            $messageType = 'error';
        }
    }
}

function escape(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="robots" content="noindex, nofollow">
    <title>Create Super Admin</title>
    <style>
        * { box-sizing: border-box; }

        body {
            margin: 0;
            min-height: 100vh;
            display: grid;
            place-items: center;
            padding: 24px;
            font-family: Arial, Helvetica, sans-serif;
            color: #172033;
            background: #f4f6f9;
        }

        .card {
            width: 100%;
            max-width: 480px;
            padding: 32px;
            border: 1px solid #dfe4ec;
            border-radius: 18px;
            background: #ffffff;
            box-shadow: 0 18px 45px rgba(23, 32, 51, 0.10);
        }

        h1 {
            margin: 0 0 8px;
            font-size: 28px;
        }

        .intro {
            margin: 0 0 24px;
            color: #657087;
            line-height: 1.5;
        }

        .alert {
            margin-bottom: 20px;
            padding: 13px 15px;
            border-radius: 10px;
            line-height: 1.45;
        }

        .alert.success {
            color: #176b3a;
            border: 1px solid #b9e6ca;
            background: #ecf9f1;
        }

        .alert.error {
            color: #9d2030;
            border: 1px solid #f0c3ca;
            background: #fff1f3;
        }

        .field {
            margin-bottom: 18px;
        }

        label {
            display: block;
            margin-bottom: 7px;
            font-size: 14px;
            font-weight: 700;
        }

        input {
            width: 100%;
            height: 48px;
            padding: 0 14px;
            border: 1px solid #cfd6e1;
            border-radius: 10px;
            font: inherit;
            outline: none;
        }

        input:focus {
            border-color: #315efb;
            box-shadow: 0 0 0 3px rgba(49, 94, 251, 0.14);
        }

        button {
            width: 100%;
            height: 50px;
            border: 0;
            border-radius: 10px;
            color: #ffffff;
            background: #172033;
            font: inherit;
            font-weight: 700;
            cursor: pointer;
        }

        button:hover {
            background: #27344d;
        }

        .note {
            margin: 18px 0 0;
            color: #7b8495;
            font-size: 13px;
            line-height: 1.45;
        }
    </style>
</head>
<body>
    <main class="card">
        <h1>Create Super Admin</h1>
        <p class="intro">Enter the account details below. If the email already exists, its password and admin access will be reset.</p>

        <?php if ($message !== ''): ?>
            <div class="alert <?= escape($messageType) ?>" role="alert">
                <?= escape($message) ?>
            </div>
        <?php endif; ?>

        <form method="post" action="">
            <div class="field">
                <label for="name">Full name</label>
                <input
                    type="text"
                    id="name"
                    name="name"
                    value="<?= escape($name) ?>"
                    autocomplete="name"
                    required
                >
            </div>

            <div class="field">
                <label for="email">Email address</label>
                <input
                    type="email"
                    id="email"
                    name="email"
                    value="<?= escape($email) ?>"
                    autocomplete="email"
                    required
                >
            </div>

            <div class="field">
                <label for="password">Password</label>
                <input
                    type="password"
                    id="password"
                    name="password"
                    minlength="8"
                    autocomplete="new-password"
                    required
                >
            </div>

            <button type="submit">Create or Update Admin</button>
        </form>

        <p class="note">For security, delete or restrict this file immediately after the admin account has been created.</p>
    </main>
</body>
</html>
