<?php
/**
 * ===================================================================================
 * Create Initial Super Admin User (One-Time Use)
 * ===================================================================================
 *
 * File: create_admin.php
 * Location: /homework_portal/create_admin.php
 *
 * --- IMPORTANT ---
 * This script is for initial setup only. You MUST delete this file from your
 * server immediately after you run it successfully. Leaving it on the server
 * is a major security risk.
 *
 * How to use:
 * 1. Upload this file to your /homework_portal/ directory.
 * 2. Open your browser and navigate to: http://school.e-cars.co.ke/homework_portal/create_admin.php
 * 3. Verify you see the success message.
 * 4. Delete this file from your server.
 */

require_once 'config.php';

// --- Default Admin Credentials to Create ---
// You will use these to log in for the first time.
$username = 'admin';
$password = 'admin1234';

echo "<h1>Admin Creation Script</h1>";

// --- Check if admin already exists ---
try {
    $stmt = $pdo->prepare("SELECT id FROM super_admins WHERE username = ?");
    $stmt->execute([$username]);
    if ($stmt->fetch()) {
        die("<p style='color: orange; font-weight: bold;'>Admin user '{$username}' already exists. No action was taken.</p><p style='color: red; font-weight: bold;'>Please delete this file from your server now.</p>");
    }
} catch(PDOException $e) {
    die("Database error during check: " . $e->getMessage());
}

// --- If admin does not exist, proceed to create it ---
echo "<p>Attempting to create admin user '{$username}'...</p>";

// Securely hash the password
$password_hash = password_hash($password, PASSWORD_DEFAULT);

// Prepare the SQL INSERT statement
$sql = "INSERT INTO super_admins (username, password_hash) VALUES (?, ?)";

try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$username, $password_hash]);
    
    echo "<h2>Success!</h2>";
    echo "<p>Admin user '<b>{$username}</b>' was created successfully.</p>";
    echo "<p>Your password is: '<b>{$password}</b>'.</p>";
    echo "<p style='color: red; font-weight: bold; font-size: 1.2em;'>For security, you must now delete this 'create_admin.php' file from your server.</p>";

} catch (PDOException $e) {
    echo "<h2>Error!</h2>";
    echo "<p>Could not create the admin user. The error was: " . $e->getMessage() . "</p>";
}

?>
