<?php
$pageTitle = 'Edit Role Permissions';
include_once 'includes/header.php';

// --- Admin Authentication & Authorization ---
// Ensure only super_admin can edit roles/permissions
requirePermission('roles:edit');

$roleModel = new Role();
$permissionModel = new Permission();

$role_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

if (!$role_id) {
    header('Location: manage_roles.php');
    exit();
}

$role = $roleModel->getById($role_id);
 
if (!$role) {
    $_SESSION['flash_error'] = 'Role not found.';
    header('Location: manage_roles.php');
    exit();
}

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $permissions = $_POST['permissions'] ?? [];
    
    // Sanitize permission IDs
    $permission_ids = array_map('intval', $permissions);
    
    if ($roleModel->syncPermissions($role_id, $permission_ids)) {
        $_SESSION['flash_message'] = 'Permissions updated successfully!';
    } else {
        $_SESSION['flash_error'] = 'Failed to update permissions.';
    }
    
    // Refresh to show updated state
    header("Location: edit_role.php?id=$role_id");
    exit();
}

// Fetch Data for View
$all_permissions_grouped = $permissionModel->getAllGrouped();
$role_permissions = $roleModel->getPermissions($role_id);
$role_permission_ids = array_map(fn($p) => $p->id, $role_permissions);

include_once 'includes/sidebar.php';
?>

<div class="admin-header-row">
    <h1>Edit Role: <?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $role->name))); ?></h1>
    <a href="manage_roles.php" class="btn-sm btn-secondary">Back to Roles</a>
</div>

<?php if (isset($_SESSION['flash_message'])): ?>
    <div class="message success"><?php echo $_SESSION['flash_message']; unset($_SESSION['flash_message']); ?></div>
<?php endif; ?>
<?php if (isset($_SESSION['flash_error'])): ?>
    <div class="message error"><?php echo $_SESSION['flash_error']; unset($_SESSION['flash_error']); ?></div>
<?php endif; ?>

<div class="form-container">
    <form action="edit_role.php?id=<?php echo $role_id; ?>" method="POST">
        
        <div class="permissions-grid">
            <?php foreach ($all_permissions_grouped as $module => $permissions): ?>
                <div class="permission-group">
                    <h3><?php echo htmlspecialchars($module); ?></h3>
                    <div class="permission-list">
                        <?php foreach ($permissions as $perm): ?>
                            <label class="permission-item">
                                <input type="checkbox" name="permissions[]" value="<?php echo $perm->id; ?>" 
                                    <?php echo in_array($perm->id, $role_permission_ids) ? 'checked' : ''; ?>>
                                <div>
                                    <span class="perm-name"><?php echo htmlspecialchars($perm->name); ?></span>
                                    <span class="perm-desc"><?php echo htmlspecialchars($perm->description); ?></span>
                                </div>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <div class="form-actions" style="margin-top: 20px; border-top: 1px solid #eee; padding-top: 20px;">
            <button type="submit" class="btn">Save Permissions</button>
        </div>
    </form>
</div>

<style>
.admin-header-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.permissions-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; }
.permission-group { background: #fff; border: 1px solid #eee; border-radius: 8px; padding: 15px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
.permission-group h3 { margin-top: 0; border-bottom: 1px solid #f0f0f0; padding-bottom: 10px; font-size: 1.1rem; color: #2c3e50; margin-bottom: 15px; }
.permission-list { display: flex; flex-direction: column; gap: 10px; }
.permission-item { display: flex; align-items: flex-start; gap: 10px; cursor: pointer; padding: 8px; border-radius: 4px; transition: background 0.1s; border: 1px solid transparent; }
.permission-item:hover { background: #f9f9f9; border-color: #eee; }
.permission-item input { margin-top: 5px; }
.perm-name { font-weight: 600; font-size: 0.9rem; display: block; color: #333; }
.perm-desc { font-size: 0.8rem; color: #777; display: block; line-height: 1.3; }
</style>

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