<?php
// include/get_role_permissions.php
require_once __DIR__ . '/db_connection.php';
require_once __DIR__ . '/PermissionManager.php';
require_once __DIR__ . '/AuthMiddleware.php';

if (session_status() === PHP_SESSION_NONE) session_start();

header('Content-Type: application/json');

function sendJsonResponse($success, $message, $data = []) {
    echo json_encode(array_merge(['success' => $success, 'message' => $message], $data));
    exit;
}

if (!isset($_SESSION['user_id'])) {
    sendJsonResponse(false, 'Not authenticated');
}

// Only users who can manage permissions may view the full permission catalogue
// and a role's current permission set.
$perm_manager = new PermissionManager($conn);
$auth         = new AuthMiddleware($perm_manager);
$auth->requirePermission('manage_permissions');

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['role_id'])) {
    sendJsonResponse(false, 'Invalid request');
}

$role_id = intval($_POST['role_id']);

if ($role_id <= 0) {
    sendJsonResponse(false, 'Invalid role ID');
}

// Get all permissions
$all_permissions_query = "SELECT * FROM permissions ORDER BY module, id";
$all_permissions_result = $conn->query($all_permissions_query);
if (!$all_permissions_result) {
    sendJsonResponse(false, 'Database error: ' . $conn->error);
}

$all_permissions = [];
$permissions_grouped = [];

while ($perm = $all_permissions_result->fetch_assoc()) {
    $perm['id'] = (int)$perm['id']; // ← cast to int to avoid JS type mismatch
    $all_permissions[] = $perm;
    $module = $perm['module'] ?? 'General';
    if (!isset($permissions_grouped[$module])) {
        $permissions_grouped[$module] = [];
    }
    $permissions_grouped[$module][] = $perm;
}

// Get role permissions
$role_perms_query = "SELECT permission_id FROM role_permissions WHERE role_id = ?";
$stmt = $conn->prepare($role_perms_query);
if (!$stmt) {
    sendJsonResponse(false, 'Prepare failed: ' . $conn->error);
}

$stmt->bind_param("i", $role_id);
$stmt->execute();
$result = $stmt->get_result();

$role_permission_ids = [];
while ($row = $result->fetch_assoc()) {
    $role_permission_ids[] = (int)$row['permission_id']; // ← cast to int
}
$stmt->close();

sendJsonResponse(true, 'Permissions loaded successfully', [
    'permissions_grouped' => $permissions_grouped,
    'role_permissions'    => $role_permission_ids,
    'permissions'         => $all_permissions,
    'role_id'             => $role_id,
    'count'               => count($role_permission_ids)
]);
?>