<?php

use MintyPHP\Router;
use MintyPHP\Support\Guard;
use MintyPHP\Service\Access\PermissionService;

Guard::requireLogin();
Guard::requirePermission(PermissionService::PERMISSIONS_VIEW);
if (!isset($_SESSION['user'])) {
    http_response_code(401);
    Router::json(['data' => [], 'total' => 0]);
}

$limit = (int) ($_GET['limit'] ?? 10);
$offset = (int) ($_GET['offset'] ?? 0);
$search = trim((string) ($_GET['search'] ?? ''));
$order = (string) ($_GET['order'] ?? 'key');
$dir = (string) ($_GET['dir'] ?? 'asc');
$active = (string) ($_GET['active'] ?? '');

$result = permissionGateway()->listPaged([
    'limit' => $limit,
    'offset' => $offset,
    'search' => $search,
    'order' => $order,
    'dir' => $dir,
    'active' => $active,
]);

$rows = [];
foreach ($result['data'] ?? [] as $row) {
    $rows[] = [
        'id' => $row['id'] ?? null,
        'key' => $row['key'] ?? '',
        'description' => $row['description'] ?? '',
        'active' => (int) ($row['active'] ?? 1),
        'is_system' => (int) ($row['is_system'] ?? 0),
        'created' => dt($row['created'] ?? ''),
    ];
}

Router::json([
    'data' => $rows,
    'total' => $result['total'] ?? 0,
]);
