<?php
/**
 * Migration Runner: Roles and Permissions System
 * Run this script to set up the roles and permissions tables
 */

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

echo "=== Roles & Permissions Migration ===\n\n";

// Read migration file
$migrationFile = __DIR__ . '/database/migrations/add_roles_and_permissions.sql';
if (!file_exists($migrationFile)) {
    die("Error: Migration file not found at $migrationFile\n");
}

$sql = file_get_contents($migrationFile);

// Split by semicolons to get individual statements
$statements = array_filter(array_map('trim', explode(';', $sql)));

try {
    db()->beginTransaction();
    
    foreach ($statements as $statement) {
        if (empty($statement)) continue;
        
        echo "Executing: " . substr($statement, 0, 50) . "...\n";
        db()->exec($statement);
    }
    
    db()->commit();
    echo "\n✓ Migration completed successfully!\n\n";
    
    // Seed default roles for existing tenants
    echo "Seeding default roles for existing tenants...\n";
    
    $stmt = db()->query("SELECT id FROM tenants");
    $tenants = $stmt->fetchAll();
    
    foreach ($tenants as $tenant) {
        echo "  Creating default roles for tenant ID: {$tenant['id']}...\n";
        Role::createDefaultRoles($tenant['id']);
        Role::assignDefaultPermissions($tenant['id']);
    }
    
    echo "\n✓ Default roles seeded for all tenants!\n";
    
} catch (Exception $e) {
    db()->rollBack();
    echo "\n✗ Migration failed: " . $e->getMessage() . "\n";
    exit(1);
}
