<?php
/**
 * Create or Reset Superadmin Account
 * 
 * This script creates a new superadmin account or resets an existing one.
 * Run this from the command line or browser.
 */

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/core/Security.php';

echo "========================================\n";
echo "SUPERADMIN ACCOUNT CREATION\n";
echo "========================================\n\n";

// Default credentials
$defaultName = 'Platform Admin';
$defaultEmail = 'superadmin@tellerpro.com';
$defaultPassword = 'SuperAdmin@123';

// Check if running from browser
if (php_sapi_name() !== 'cli') {
    echo "<pre>";
}

try {
    $db = db();
    
    // Check if superadmin already exists
    $stmt = $db->prepare("SELECT * FROM superadmins WHERE email = ? LIMIT 1");
    $stmt->execute([$defaultEmail]);
    $existing = $stmt->fetch();
    
    if ($existing) {
        echo "Superadmin account already exists.\n";
        echo "Email: $defaultEmail\n";
        echo "Updating password...\n";
        
        // Update password
        $hashedPassword = Security::hashPassword($defaultPassword);
        $stmt = $db->prepare("UPDATE superadmins SET password = ? WHERE email = ?");
        $stmt->execute([$hashedPassword, $defaultEmail]);
        
        echo "✓ Password updated successfully.\n";
    } else {
        echo "Creating new superadmin account...\n";
        
        // Create new superadmin
        $hashedPassword = Security::hashPassword($defaultPassword);
        $stmt = $db->prepare("INSERT INTO superadmins (name, email, password, is_active) VALUES (?, ?, ?, 1)");
        $stmt->execute([$defaultName, $defaultEmail, $hashedPassword]);
        
        echo "✓ Superadmin account created successfully.\n";
    }
    
    echo "\n========================================\n";
    echo "LOGIN CREDENTIALS\n";
    echo "========================================\n";
    echo "Email: $defaultEmail\n";
    echo "Password: $defaultPassword\n";
    echo "Login URL: http://localhost/TellerPro/superadmin/login\n";
    echo "========================================\n";
    
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage() . "\n";
    exit(1);
}

if (php_sapi_name() !== 'cli') {
    echo "</pre>";
}
