<?php
/**
 * Create Admin User Script
 * Creates a super admin user for testing the CMS
 */

// Database configuration
$host = 'localhost';
$dbname = 'obgyn_research_platform';
$username = 'adminGRCE';
$password = '2UFAT605IQCLmyyd';

echo "===========================================\n";
echo "Create Admin User Script\n";
echo "===========================================\n\n";

try {
    // Create PDO connection
    echo "Connecting to database...\n";
    $dsn = "mysql:host=$host;dbname=$dbname;charset=utf8mb4";
    $options = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ];
    
    $pdo = new PDO($dsn, $username, $password, $options);
    echo "✓ Connected successfully!\n\n";
    
    // Admin user details
    $adminEmail = 'admin@obgynresearch.com';
    $adminPassword = 'Admin@123456'; // Change this to your desired password
    $firstName = 'Super';
    $lastName = 'Admin';
    
    // Check if admin user already exists
    $stmt = $pdo->prepare("SELECT id, email FROM users WHERE email = ?");
    $stmt->execute([$adminEmail]);
    $existingUser = $stmt->fetch();
    
    if ($existingUser) {
        echo "⚠ Admin user already exists!\n";
        echo "Email: {$existingUser['email']}\n";
        echo "User ID: {$existingUser['id']}\n\n";
        
        echo "Do you want to:\n";
        echo "1. Update the password\n";
        echo "2. Keep existing user\n";
        echo "3. Delete and recreate\n\n";
        
        echo "Enter choice (1-3): ";
        if (defined('STDIN')) {
            $choice = trim(fgets(STDIN));
        } else {
            // Running via web server, default to updating password
            echo "Running in web mode, defaulting to update password.\n";
            $choice = '1';
        }
        
        if ($choice == '1') {
            // Update password
            $hashedPassword = password_hash($adminPassword, PASSWORD_BCRYPT, ['cost' => 12]);
            $stmt = $pdo->prepare("UPDATE users SET password = ?, status = 'active', email_verified = 1 WHERE id = ?");
            $stmt->execute([$hashedPassword, $existingUser['id']]);
            echo "✓ Password updated successfully!\n";
            $userId = $existingUser['id'];
        } elseif ($choice == '3') {
            // Delete and recreate
            $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
            $stmt->execute([$existingUser['id']]);
            echo "✓ Existing user deleted.\n";
            $existingUser = null;
        } else {
            echo "✓ Keeping existing user.\n";
            $userId = $existingUser['id'];
        }
    }
    
    if (!$existingUser || $choice == '3') {
        // Create new admin user
        echo "Creating new admin user...\n";
        
        // Hash password
        $hashedPassword = password_hash($adminPassword, PASSWORD_BCRYPT, ['cost' => 12]);
        
        // Insert user
        $stmt = $pdo->prepare("
            INSERT INTO users (
                email, password, first_name, last_name, 
                role_id, status, email_verified, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
        ");
        
        $stmt->execute([
            $adminEmail,
            $hashedPassword,
            $firstName,
            $lastName,
            1, // role_id = 1 (super_admin)
            'active',
            1 // email_verified = true
        ]);
        
        $userId = $pdo->lastInsertId();
        echo "✓ Admin user created successfully!\n";
        echo "User ID: $userId\n\n";
        
        // Create researcher profile
        echo "Creating researcher profile...\n";
        $stmt = $pdo->prepare("
            INSERT INTO researcher_profiles (
                user_id, title, specialization, bio, verified_badge, created_at
            ) VALUES (?, ?, ?, ?, ?, NOW())
        ");
        
        $stmt->execute([
            $userId,
            'Platform Administrator',
            'System Administration',
            'Super administrator with full access to all platform features.',
            1 // verified badge
        ]);
        
        echo "✓ Researcher profile created!\n\n";
    }
    
    // Verify role
    $stmt = $pdo->prepare("
        SELECT u.*, r.name as role_name 
        FROM users u 
        LEFT JOIN roles r ON u.role_id = r.id 
        WHERE u.id = ?
    ");
    $stmt->execute([$userId]);
    $user = $stmt->fetch();
    
    echo "===========================================\n";
    echo "Admin User Details\n";
    echo "===========================================\n";
    echo "User ID: {$user['id']}\n";
    echo "Email: {$user['email']}\n";
    echo "Password: $adminPassword\n";
    echo "Name: {$user['first_name']} {$user['last_name']}\n";
    echo "Role: {$user['role_name']} (ID: {$user['role_id']})\n";
    echo "Status: {$user['status']}\n";
    echo "Email Verified: " . ($user['email_verified'] ? 'Yes' : 'No') . "\n";
    echo "===========================================\n\n";
    
    echo "✓ Admin user is ready to use!\n\n";
    
    echo "Login URL: http://localhost/obgyn-research-platform/login.php\n";
    echo "Admin Panel: http://localhost/obgyn-research-platform/admin/\n\n";
    
    echo "IMPORTANT: Change the password after first login!\n";
    
} catch (PDOException $e) {
    echo "\n✗ Database Error: " . $e->getMessage() . "\n";
    echo "\nPlease check:\n";
    echo "1. Database credentials are correct\n";
    echo "2. Database exists\n";
    echo "3. Tables are created (run cms_migration.sql first)\n";
    exit(1);
} catch (Exception $e) {
    echo "\n✗ Error: " . $e->getMessage() . "\n";
    exit(1);
}
