<?php
/**
 * Web-based Migration Runner: Roles and Permissions System
 * Access this file in your browser to run the migration
 */

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

// Auto-load Role model
spl_autoload_register(function(string $class) {
    $paths = [
        __DIR__ . '/models/' . $class . '.php',
    ];
    foreach ($paths as $path) {
        if (file_exists($path)) { require_once $path; return; }
    }
});

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Roles Migration - TellerPro</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            max-width: 800px;
            margin: 50px auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            margin-top: 0;
            color: #333;
        }
        .success {
            background: #d4edda;
            color: #155724;
            padding: 15px;
            border-radius: 4px;
            margin: 20px 0;
            border: 1px solid #c3e6cb;
        }
        .error {
            background: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 4px;
            margin: 20px 0;
            border: 1px solid #f5c6cb;
        }
        .info {
            background: #d1ecf1;
            color: #0c5460;
            padding: 15px;
            border-radius: 4px;
            margin: 20px 0;
            border: 1px solid #bee5eb;
        }
        pre {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            overflow-x: auto;
            font-size: 12px;
        }
        .btn {
            display: inline-block;
            padding: 12px 24px;
            background: #007bff;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            border: none;
            cursor: pointer;
            font-size: 16px;
        }
        .btn:hover {
            background: #0056b3;
        }
        .step {
            margin: 10px 0;
            padding: 10px;
            background: #f8f9fa;
            border-left: 3px solid #007bff;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔐 Roles & Permissions Migration</h1>
        
        <?php if (!isset($_POST['confirm'])): ?>
            <div class="info">
                <strong>⚠️ Important:</strong> This migration will:
                <ul>
                    <li>Create roles, permissions, and role_permissions tables</li>
                    <li>Seed 40+ menu-based permissions</li>
                    <li>Create default system roles (Owner, Admin, Manager, Teller) for all existing tenants</li>
                    <li>Assign appropriate permissions to each default role</li>
                </ul>
                <p><strong>This is safe to run and will not delete any existing data.</strong></p>
            </div>
            
            <form method="POST">
                <input type="hidden" name="confirm" value="1">
                <button type="submit" class="btn">Run Migration</button>
            </form>
        <?php else: ?>
            <?php
            echo "<h2>Migration Progress:</h2>";
            
            // Read migration file
            $migrationFile = __DIR__ . '/database/migrations/add_roles_and_permissions.sql';
            if (!file_exists($migrationFile)) {
                echo '<div class="error">❌ Error: Migration file not found at ' . htmlspecialchars($migrationFile) . '</div>';
                exit;
            }

            $sql = file_get_contents($migrationFile);
            $statements = array_filter(array_map('trim', explode(';', $sql)));

            try {
                echo '<div class="step">✓ Step 1: Creating database tables...</div>';
                foreach ($statements as $i => $statement) {
                    if (empty($statement)) continue;
                    try {
                        db()->exec($statement);
                    } catch (PDOException $e) {
                        // Ignore "table already exists" and "duplicate column" errors
                        if (strpos($e->getMessage(), 'already exists') === false && strpos($e->getMessage(), 'duplicate column') === false) {
                            throw $e;
                        }
                    }
                }
                
                echo '<div class="step">✓ Step 2: Seeding permissions...</div>';
                
                echo '<div class="step">✓ Step 3: Creating default roles for existing tenants...</div>';
                
                $stmt = db()->query("SELECT id FROM tenants");
                $tenants = $stmt->fetchAll();
                
                if (empty($tenants)) {
                    echo '<div class="info">ℹ️ No existing tenants found. Default roles will be created when new tenants register.</div>';
                } else {
                    foreach ($tenants as $tenant) {
                        echo '<div class="step">  - Creating default roles for tenant ID: ' . htmlspecialchars($tenant['id']) . '...</div>';
                        Role::createDefaultRoles($tenant['id']);
                        Role::assignDefaultPermissions($tenant['id']);
                    }
                }
                
                echo '<div class="success">✅ Migration completed successfully!</div>';
                echo '<p><strong>Next Steps:</strong></p>';
                echo '<ul>';
                echo '<li>Go to <a href="' . APP_URL . '/users">Users & Roles</a> to manage your team</li>';
                echo '<li>Go to <a href="' . APP_URL . '/roles">Manage Roles</a> to create custom roles and assign permissions</li>';
                echo '<li>The sidebar menu will now respect individual permissions</li>';
                echo '</ul>';
                
            } catch (Exception $e) {
                echo '<div class="error">❌ Migration failed: ' . htmlspecialchars($e->getMessage()) . '</div>';
                echo '<div class="error">Error details: ' . htmlspecialchars($e->getMessage()) . '</div>';
                echo '<pre>' . htmlspecialchars($e->getTraceAsString()) . '</pre>';
            }
            ?>
            
            <p><a href="<?= APP_URL ?>/users" class="btn">Go to Users & Roles</a></p>
        <?php endif; ?>
    </div>
</body>
</html>
