<?php
require_once __DIR__ . '/includes/db_connect.php';

// Check if running from command line or web
$isCli = (php_sapi_name() === 'cli');

// Function to output messages
function output($message, $type = 'info') {
    global $isCli;
    if ($isCli) {
        echo "[${type}] ${message}\n";
    } else {
        $color = 'black';
        switch($type) {
            case 'success': $color = 'green'; break;
            case 'error': $color = 'red'; break;
            case 'warning': $color = 'orange'; break;
        }
        echo "<div style='color:${color};margin:5px 0;'>${message}</div>";
    }
}

// Admin user details - Using your specified table structure
$adminData = [
    'username' => 'luckylucy',
    'password' => 'Temporary123!', // You should change this immediately after login
    'role' => 'superadmin'  // Must be either 'superadmin' or 'reviewer'
];

try {
    // Check if admin already exists
    $stmt = $pdo->prepare("SELECT id FROM admins WHERE username = ?");
    $stmt->execute([$adminData['username']]);
    
    if ($stmt->rowCount() > 0) {
        output("Error: An admin with this username already exists.", 'error');
        exit(1);
    }
    
    // Hash the password
    $hashedPassword = password_hash($adminData['password'], PASSWORD_DEFAULT);
    
    // Insert the new admin
    $stmt = $pdo->prepare("\n        INSERT INTO admins (username, password_hash, role, created_at)\n        VALUES (?, ?, ?, NOW())\n    ");
    
    $stmt->execute([
        $adminData['username'],
        $hashedPassword,
        $adminData['role']
    ]);
    
    $adminId = $pdo->lastInsertId();
    
    output("Admin user created successfully!", 'success');
    output("Username: " . $adminData['username'], 'info');
    output("Password: " . $adminData['password'], 'warning');
    output("IMPORTANT: Please change this password immediately after logging in!", 'warning');
    
} catch (PDOException $e) {
    output("Error creating admin user: " . $e->getMessage(), 'error');
    exit(1);
}

// Add HTML wrapper if accessed via web
if (!$isCli):
?>
<!DOCTYPE html>
<html>
<head>
    <title>Create Admin User</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; line-height: 1.6; }
        .success { color: green; }
        .error { color: red; }
        .warning { color: orange; }
        .info { color: blue; }
    </style>
</head>
<body>
    <h1>Admin User Creation</h1>
    <p><a href="login.php">Go to Login Page</a></p>
</body>
</html>
<?php endif; ?>
