<?php
require_once '../config/database.php';
require_once '../app/helpers/rbac.php';
require_once '../app/helpers/api_security.php';
require_once '../app/helpers/audit.php';

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

requireApiLogin();
enforceCsrfForUnsafeRequest();

if (!can('user.manage')) {
    apiRespond(['status' => 'error', 'message' => 'Unauthorized'], 403);
}

$action = $_GET['action'] ?? '';

switch ($action) {

case 'matrix':

    $roles = $pdo->query("SELECT id, name FROM roles")->fetchAll();
    $permissions = $pdo->query("SELECT id, code FROM permissions")->fetchAll();

    $assignedRaw = $pdo->query("SELECT role_id, permission_id FROM role_permissions")->fetchAll();

    $assigned = [];
    foreach ($assignedRaw as $a) {
        $assigned[] = $a['role_id'] . '_' . $a['permission_id'];
    }

    echo json_encode([
        'roles' => $roles,
        'permissions' => $permissions,
        'assigned' => $assigned
    ]);
    break;


case 'toggle':

    $role = (int)($_POST['role_id'] ?? 0);
    $perm = (int)($_POST['permission_id'] ?? 0);
    $checked = (int)($_POST['checked'] ?? 0);

    if ($role <= 0 || $perm <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid role or permission ID']);
        exit;
    }

    // Verify both IDs exist
    $roleExists = $pdo->prepare("SELECT 1 FROM roles WHERE id = ?");
    $roleExists->execute([$role]);
    if (!$roleExists->fetchColumn()) {
        echo json_encode(['status' => 'error', 'message' => 'Role not found']);
        exit;
    }
    $permExists = $pdo->prepare("SELECT 1 FROM permissions WHERE id = ?");
    $permExists->execute([$perm]);
    if (!$permExists->fetchColumn()) {
        echo json_encode(['status' => 'error', 'message' => 'Permission not found']);
        exit;
    }

    $label = '';
    if ($checked) {
        $stmt = $pdo->prepare("
            INSERT IGNORE INTO role_permissions (role_id, permission_id)
            VALUES (?,?)
        ");
        $stmt->execute([$role, $perm]);
        $label = 'granted';
    } else {
        $stmt = $pdo->prepare("
            DELETE FROM role_permissions
            WHERE role_id=? AND permission_id=?
        ");
        $stmt->execute([$role, $perm]);
        $label = 'revoked';
    }

    audit($pdo, (int)$_SESSION['user_id'], 'update', 'role_permission', $role, "Permission {$label}: role_id={$role}, permission_id={$perm}", null, null);

    echo json_encode(['status' => 'success']);
    break;
}
