<?php
/**
 * Migration script to add RBAC tables and default admin user
 * Run this once to upgrade from the old hardcoded auth system to RBAC
 */

require_once '../db_config.php';

echo "<h2>XChange 2025 - RBAC Migration Script</h2>\n";
echo "<pre>\n";

try {
    $db = getDBConnection();
    
    // Check if admin_users table already exists
    $stmt = $db->query("SHOW TABLES LIKE 'admin_users'");
    if ($stmt->rowCount() > 0) {
        echo "✓ admin_users table already exists, skipping creation...\n";
    } else {
        echo "Creating admin_users table...\n";
        $db->exec("
            CREATE TABLE admin_users (
                id INT AUTO_INCREMENT PRIMARY KEY,
                username VARCHAR(50) UNIQUE NOT NULL,
                password_hash VARCHAR(255) NOT NULL,
                full_name VARCHAR(100) NOT NULL,
                email VARCHAR(255) NOT NULL,
                role ENUM('super_admin', 'manager', 'viewer') NOT NULL DEFAULT 'viewer',
                is_active BOOLEAN DEFAULT TRUE,
                last_login TIMESTAMP NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                created_by INT,
                
                INDEX idx_username (username),
                INDEX idx_role (role),
                INDEX idx_is_active (is_active),
                FOREIGN KEY (created_by) REFERENCES admin_users(id) ON DELETE SET NULL
            )
        ");
        echo "✓ admin_users table created successfully\n";
    }
    
    // Check if default admin user exists
    $stmt = $db->prepare("SELECT id FROM admin_users WHERE username = 'admin'");
    $stmt->execute();
    if ($stmt->rowCount() > 0) {
        echo "✓ Default admin user already exists, skipping creation...\n";
    } else {
        echo "Creating default admin user...\n";
        // Password: XChange2025!Admin
        $passwordHash = password_hash('XChange2025!Admin', PASSWORD_DEFAULT);
        $stmt = $db->prepare("
            INSERT INTO admin_users (username, password_hash, full_name, email, role, is_active) 
            VALUES ('admin', ?, 'System Administrator', 'admin@xchange2025.com', 'super_admin', TRUE)
        ");
        $stmt->execute([$passwordHash]);
        echo "✓ Default admin user created (username: admin, password: XChange2025!Admin)\n";
    }
    
    // Check if admin_activity_log table exists
    $stmt = $db->query("SHOW TABLES LIKE 'admin_activity_log'");
    if ($stmt->rowCount() > 0) {
        echo "✓ admin_activity_log table already exists, skipping creation...\n";
    } else {
        echo "Creating admin_activity_log table...\n";
        $db->exec("
            CREATE TABLE admin_activity_log (
                id INT AUTO_INCREMENT PRIMARY KEY,
                admin_user_id INT NOT NULL,
                action VARCHAR(100) NOT NULL,
                target_type VARCHAR(50),
                target_id INT,
                details TEXT,
                ip_address VARCHAR(45),
                user_agent TEXT,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                
                FOREIGN KEY (admin_user_id) REFERENCES admin_users(id) ON DELETE CASCADE,
                INDEX idx_admin_user_id (admin_user_id),
                INDEX idx_action (action),
                INDEX idx_created_at (created_at)
            )
        ");
        echo "✓ admin_activity_log table created successfully\n";
    }
    
    echo "\n=== MIGRATION COMPLETED SUCCESSFULLY ===\n";
    echo "\nNext Steps:\n";
    echo "1. Login with username: admin, password: XChange2025!Admin\n";
    echo "2. Create additional admin users as needed\n";
    echo "3. Test the role-based access control\n";
    echo "4. Change the default admin password\n";
    echo "\nRole Permissions:\n";
    echo "- Super Admin: Full access to everything\n";
    echo "- Manager: All operations except Settings and User Management\n";
    echo "- Viewer: Read-only access to data\n";
    
} catch (Exception $e) {
    echo "❌ Migration failed: " . $e->getMessage() . "\n";
    echo "\nPlease check your database connection and try again.\n";
}

echo "</pre>\n";
?>

<!DOCTYPE html>
<html>
<head>
    <title>RBAC Migration - XChange 2025</title>
    <?php include '../includes/favicon.php'; ?>
    <style>
        body { font-family: Arial, sans-serif; margin: 2rem; }
        pre { background: #f5f5f5; padding: 1rem; border-radius: 5px; }
        h2 { color: #333; }
    </style>
</head>
<body>
    <p><a href="login.php">← Go to Admin Login</a></p>
</body>
</html>
