<?php
$pageTitle = 'Manage Roles';
include_once 'includes/header.php';

// --- Admin Authentication & Authorization ---
// Check if user has permission to view roles
requirePermission('roles:view');

$roleModel = new Role();
$message = '';
$error = '';

// Handle deletion
if (isset($_GET['delete_id'])) {
    if (!hasPermission('roles:delete')) {
        $_SESSION['flash_error'] = 'You do not have permission to delete roles.';
    } else {
        $delete_id = filter_input(INPUT_GET, 'delete_id', FILTER_VALIDATE_INT);
        
        // Fetch role to check name
        $roleToDelete = $roleModel->getById($delete_id);
        $core_roles = ['admin', 'super_admin', 'league_manager', 'club_manager', 'team_manager', 'referee', 'commissioner', 'fan', 'player', 'fantasy_manager', 'fixtures_manager', 'super_fantasy_manager'];

        if ($roleToDelete && !in_array($roleToDelete->name, $core_roles)) { 
            if ($roleModel->delete($delete_id)) {
                $_SESSION['flash_message'] = 'Role deleted successfully!';
            } else {
                $_SESSION['flash_error'] = 'Failed to delete role. It might be in use.';
            }
        } else {
            $_SESSION['flash_error'] = 'Cannot delete a core system role.';
        }
    }
    header('Location: manage_roles.php');
    exit();
}

// Handle form submission for creating a new role
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_role'])) {
    if (!hasPermission('roles:create')) {
        $error = 'You do not have permission to create roles.';
    } else {
        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');

        if (empty($name)) {
            $error = 'Role name is required.';
        } else {
            // Basic validation for role name format if needed
            $name = strtolower(str_replace(' ', '_', $name));
            
            if ($roleModel->create(['name' => $name, 'description' => $description])) {
                $_SESSION['flash_message'] = 'Role created successfully!';
                header('Location: manage_roles.php');
                exit();
            } else {
                $error = 'Failed to create role. It might already exist.';
            }
        }
    }
}

// Check for flash messages from redirects
if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    unset($_SESSION['flash_message']);
}
if (isset($_SESSION['flash_error'])) {
    $error = $_SESSION['flash_error'];
    unset($_SESSION['flash_error']);
}

$all_roles = $roleModel->getAll();

include_once 'includes/sidebar.php';
?>

<h1>Manage User Roles</h1>

<?php if ($message): ?><div class="message success"><?php echo $message; ?></div><?php endif; ?>
<?php if ($error): ?><div class="message error"><?php echo $error; ?></div><?php endif; ?>

<!-- Create Role Form -->
<?php if (hasPermission('roles:create')): ?>
<div class="form-container">
    <h2>Create New Role</h2>
    <form action="manage_roles.php" method="POST">
        <div class="form-group">
            <label for="name">Role Name</label>
            <input type="text" name="name" id="name" required placeholder="e.g., content_editor">
            <small>Role name will be converted to lowercase with underscores (e.g., Content Editor -> content_editor)</small>
        </div>
        <div class="form-group">
            <label for="description">Description</label>
            <textarea name="description" id="description" rows="2" placeholder="Briefly describe what this role can do."></textarea>
        </div>
        <button type="submit" name="create_role" class="btn">Create Role</button>
    </form>
</div>
<?php endif; ?>

<!-- List of Existing Roles -->
<h2>Existing Roles</h2>
<table class="styled-table">
    <thead><tr><th>ID</th><th>Name</th><th>Description</th><th>Actions</th></tr></thead>
    <tbody>
        <?php foreach ($all_roles as $role): ?>
            <tr>
                <td><?php echo $role->id; ?></td>
                <td><strong><?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $role->name))); ?></strong></td>
                <td><?php echo htmlspecialchars($role->description); ?></td>
                <td class="actions-cell">
                    <?php if (hasPermission('roles:edit')): ?>
                        <a href="edit_role.php?id=<?php echo $role->id; ?>" class="btn-sm btn-edit">Manage Permissions</a>
                    <?php endif; ?>
                    
                    <?php if (hasPermission('roles:delete') && !in_array($role->name, ['admin', 'super_admin', 'league_manager', 'club_manager', 'team_manager', 'referee', 'commissioner', 'fan', 'player', 'fantasy_manager', 'fixtures_manager', 'super_fantasy_manager'])): ?>
                        <a href="?delete_id=<?php echo $role->id; ?>" class="btn-sm btn-delete" onclick="return confirm('Are you sure?');">Delete</a>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<?php include_once 'includes/footer.php'; ?>