<?php
require_once '../core/bootstrap.php';

// --- Security Check ---
// Only allow access if running from CLI or if logged in as Super Admin
$is_cli = (php_sapi_name() === 'cli');
$is_super_admin = (isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'super_admin');

if (!$is_cli && !$is_super_admin) {
    die('Access Denied. You must be logged in as a Super Admin to run this script.');
}

$db = new Database();

echo "<h1>Initializing Roles and Permissions</h1>";

// 1. Ensure Roles Exist
echo "Checking roles...<br>";
$roles_definitions = [
    'super_admin' => 'Has all permissions, including role management.',
    'admin' => 'General administrator with wide-ranging access.',
    'club_manager' => 'Manages a club, its teams, and staff.',
    'commissioner' => 'Manages live scoring for assigned matches.',
    'fan' => 'General user, can view content and play fantasy.',
    'fantasy_manager' => 'A user who plays fantasy football.',
    'fixtures_manager' => 'Manages league fixtures.',
    'league_manager' => 'Manages a specific league, its clubs and seasons.',
    'player' => 'A registered player in a team.',
    'referee' => 'Officiates matches.',
    'team_manager' => 'Manages a specific team roster and lineups.',
    'super_fantasy_manager' => 'Manages the backend of the Fantasy module (prices, points, gameweeks).'
];

foreach ($roles_definitions as $name => $desc) {
    $db->query("SELECT id FROM roles WHERE name = :name");
    $db->bind(':name', $name);
    if (!$db->single()) {
        $db->query("INSERT INTO roles (name, description) VALUES (:name, :desc)");
        $db->bind(':name', $name);
        $db->bind(':desc', $desc);
        $db->execute();
        echo "<span style='color:green'>Created role: $name</span><br>";
    }
}

// 2. Ensure Permissions Exist
echo "Checking permissions definitions... ";
$permissions_list = [
    // League & Season
    ['leagues:create', 'Leagues'], ['leagues:edit', 'Leagues'], ['leagues:delete', 'Leagues'], ['leagues:view', 'Leagues'],
    ['seasons:create', 'Seasons'], ['seasons:edit', 'Seasons'], ['seasons:delete', 'Seasons'], ['seasons:view', 'Seasons'],
    // Fixtures & Gameweeks
    ['gameweeks:create', 'Gameweeks'], ['gameweeks:edit', 'Gameweeks'], ['gameweeks:delete', 'Gameweeks'], ['gameweeks:view', 'Gameweeks'],
    ['fixtures:create', 'Fixtures'], ['fixtures:edit', 'Fixtures'], ['fixtures:delete', 'Fixtures'], ['fixtures:view', 'Fixtures'], ['fixtures:generate', 'Fixtures'],
    // Clubs & Teams
    ['clubs:create', 'Clubs'], ['clubs:edit', 'Clubs'], ['clubs:delete', 'Clubs'], ['clubs:view', 'Clubs'],
    ['teams:create', 'Teams'], ['teams:edit', 'Teams'], ['teams:delete', 'Teams'], ['teams:view', 'Teams'],
    ['rosters:approve', 'Rosters'], ['rosters:view', 'Rosters'],
    // Users & Roles
    ['users:create', 'Users'], ['users:edit', 'Users'], ['users:delete', 'Users'], ['users:view', 'Users'],
    ['roles:create', 'Roles & Permissions'], ['roles:edit', 'Roles & Permissions'], ['roles:delete', 'Roles & Permissions'], ['roles:view', 'Roles & Permissions'],
    // Finance
    ['fines:create', 'Finance'], ['fines:delete', 'Finance'], ['fines:view', 'Finance'], ['payments:view', 'Finance'],
    ['withdrawals:view', 'Finance'], ['withdrawals:manage', 'Finance'],
    // Fantasy Backend
    ['fantasy:manage_prices', 'Fantasy'], ['fantasy:process_points', 'Fantasy'], ['fantasy:season_rollover', 'Fantasy'], ['fantasy:view_management', 'Fantasy'],
    // System
    ['settings:edit', 'System'], ['announcements:create', 'System'], ['announcements:delete', 'System']
];

$db->query("INSERT IGNORE INTO permissions (name, module, description) VALUES (:name, :module, :desc)");
foreach ($permissions_list as $perm) {
    $db->bind(':name', $perm[0]);
    $db->bind(':module', $perm[1]);
    $db->bind(':desc', 'Permission to ' . str_replace(':', ' ', $perm[0]));
    $db->execute();
}
echo "<span style='color:green'>Verified.</span><br>";

// 3. Fetch IDs for Mapping
$db->query("SELECT id, name FROM roles");
$roles = $db->resultSet();
$roleMap = [];
foreach ($roles as $r) $roleMap[$r->name] = $r->id;

$db->query("SELECT id, name FROM permissions");
$permissions = $db->resultSet();
$permMap = [];
foreach ($permissions as $p) $permMap[$p->name] = $p->id;

// 4. Define Role -> Permission Assignments
$assignments = [
    'super_admin' => array_keys($permMap), // All permissions
    'admin' => array_keys($permMap), // All permissions
    
    'league_manager' => [
        'leagues:view', 'leagues:edit',
        'seasons:create', 'seasons:edit', 'seasons:delete', 'seasons:view',
        'gameweeks:create', 'gameweeks:edit', 'gameweeks:delete', 'gameweeks:view',
        'fixtures:create', 'fixtures:edit', 'fixtures:delete', 'fixtures:view', 'fixtures:generate',
        'clubs:view', 'teams:view', 'rosters:view', 'rosters:approve'
    ],
    
    'fixtures_manager' => [
        'fixtures:create', 'fixtures:edit', 'fixtures:delete', 'fixtures:view', 'fixtures:generate',
        'gameweeks:view', 'gameweeks:edit',
        'seasons:view'
    ],
    
    'club_manager' => [
        'clubs:view', 'clubs:edit',
        'teams:create', 'teams:edit', 'teams:delete', 'teams:view',
        'rosters:view', 'rosters:approve',
        'fines:view', 'payments:view'
    ],
    
    'team_manager' => [
        'teams:view', 'teams:edit',
        'rosters:view'
    ],
    
    'super_fantasy_manager' => [
        'fantasy:manage_prices', 'fantasy:process_points', 'fantasy:season_rollover', 'fantasy:view_management',
        'gameweeks:view', 'gameweeks:edit', // Needed to manage deadlines
        'users:view' // Needed to see players
    ],
    
    'commissioner' => [
        'fixtures:view'
    ],
    
    'referee' => [
        'fixtures:view'
    ],
    
    // Standard users (fan, player, fantasy_manager) get NO backend permissions by default
    'fan' => [],
    'player' => [],
    'fantasy_manager' => [] 
];

// Add Finance Manager specific permissions
$assignments['finance_manager'] = [
    'fines:view', 'fines:create', 'fines:delete',
    'payments:view',
    'withdrawals:view', 'withdrawals:manage'
];

// 5. Apply Assignments
echo "<h3>Assigning Permissions...</h3>";
$db->query("DELETE FROM role_permissions"); // Reset to ensure clean state
$db->execute();

$insertSql = "INSERT INTO role_permissions (role_id, permission_id) VALUES (:rid, :pid)";

foreach ($assignments as $roleName => $perms) {
    if (!isset($roleMap[$roleName])) {
        echo "Skipping $roleName (Role not found in DB)<br>";
        continue;
    }
    $rid = $roleMap[$roleName];
    $count = 0;
    
    foreach ($perms as $pName) {
        if (isset($permMap[$pName])) {
            $pid = $permMap[$pName];
            $db->query($insertSql);
            $db->bind(':rid', $rid);
            $db->bind(':pid', $pid);
            $db->execute();
            $count++;
        }
    }
    echo "Assigned $count permissions to <strong>$roleName</strong>.<br>";
}

echo "<br><strong>Success!</strong> <a href='manage_roles.php'>Return to Roles Management</a>";
?>