<?php
use MintyPHP\Router;

$canCreateRoles = can('roles.create');
?>
<?php
$breadcrumbs = [
  ['label' => t('Home'), 'path' => 'admin'],
  ['label' => t('Roles')],
];
require templatePath('partials/app-breadcrumb.phtml');
?>
<div class="app-list-titlebar">
  <h1><?php e(t('Roles')); ?></h1>
  <div class="app-list-titlebar-actions">
    <button class="outline secondary" type="button" data-toolbar-toggle data-toolbar-target="#roles-toolbar"
      data-toolbar-text-show="<?php e(t('Show filters')); ?>" data-toolbar-text-hide="<?php e(t('Hide filters')); ?>">
      <i class="bi bi-funnel-fill"></i> <span data-toolbar-label><?php e(t('Hide filters')); ?></span>
    </button>
    <?php if ($canCreateRoles): ?>
      <a role="button" class="primary" href="admin/roles/create">
        <i class="bi bi-plus"></i> <?php e(t('Create role')); ?>
      </a>
    <?php endif; ?>
  </div>
</div>
<div class="app-list-toolbar" id="roles-toolbar">
  <label class="app-field">
    <span>Suche</span>
    <input type="search" id="role-search" placeholder="<?php e(t('Search...')); ?>">
  </label>
  <label class="app-field">
    <span><?php e(t('Status')); ?></span>
    <select id="role-status-filter">
      <option value="all"><?php e(t('All')); ?></option>
      <option value="active"><?php e(t('Active')); ?></option>
      <option value="inactive"><?php e(t('Inactive')); ?></option>
    </select>
  </label>
</div>
<div class="app-list-table">
  <div id="roles-grid"></div>
</div>

<script src="<?php e(asset('vendor/gridjs/gridjs.umd.js')); ?>"></script>
<script type="module">
  import { createServerGrid } from "<?php e(assetVersion('js/core/app-grid-factory.js')); ?>";
  import { badgeHtml, getAppBase } from "<?php e(asset('js/pages/app-list-utils.js')); ?>";

  const appBase = getAppBase();
  const labels = {
    active: "<?php e(t('Active')); ?>",
    inactive: "<?php e(t('Inactive')); ?>"
  };

  const initRolesGrid = () => {
    const formatBadge = (value) => badgeHtml(gridjs, value);
    const formatCount = (value) => {
      const number = Number(value ?? 0);
      return Number.isFinite(number) ? number : 0;
    };
    const gridConfig = createServerGrid({
      gridjs: window.gridjs,
      container: '#roles-grid',
      dataUrl: 'admin/roles/data',
      appBase,
      columns: [
        {
          name: "<?php e(t('Description')); ?>",
          sort: true,
          formatter: (cell) => {
            if (!cell || typeof cell !== 'object') {
              return gridjs.html(String(cell ?? ''));
            }
            const label = cell.label ?? '';
            return gridjs.html(`${label}`);
          }
        },
        {
          name: "<?php e(t('Status')); ?>",
          sort: true,
          formatter: (cell) => cell
            ? gridjs.html(`<span class="badge" data-variant="success">${labels.active}</span>`)
            : gridjs.html(`<span class="badge" data-variant="danger">${labels.inactive}</span>`)
        },
        {
          name: "<?php e(t('Code')); ?>",
          sort: true,
          formatter: (cell) => gridjs.html(String(cell ?? ''))
        },
        {
          name: "<?php e(t('Active users')); ?>",
          sort: false,
          formatter: (cell) => formatCount(cell)
        },
        {
          name: "<?php e(t('Inactive users')); ?>",
          sort: false,
          formatter: (cell) => formatCount(cell)
        },
        {
          name: "<?php e(t('Permissions')); ?>",
          sort: false,
          formatter: (cell) => formatCount(cell)
        },
        {
          name: "<?php e(t('Created')); ?>",
          sort: true,
          formatter: (cell) => formatBadge(cell)
        },
        {
          name: "<?php e(t('Modified')); ?>",
          sort: true,
          formatter: (cell) => formatBadge(cell)
        },
        {
          name: "UUID",
          hidden: true
        }
      ],
      sortColumns: ['description', 'active', 'code', null, null, null, 'created', 'modified', null],
      paginationLimit: 10,
      language: <?php MintyPHP\Buffer::get('grid_lang'); ?>,
      mapData: (data) => data.data.map((row) => [
        {
          label: row.description,
          is_default: row.is_default ? 1 : 0
        },
        row.active,
        row.code,
        row.active_users ?? 0,
        row.inactive_users ?? 0,
        row.permission_count ?? 0,
        row.created,
        row.modified,
        row.uuid
      ]),
      actions: { enabled: false },
      search: {
        input: '#role-search',
        param: 'search',
        debounce: 250
      },
      filters: [
        {
          input: '#role-status-filter',
          param: 'active',
          default: 'all',
          normalize: (value) => (value && value !== 'all' ? value : '')
        }
      ],
      urlSync: true,
      rowDataset: (row) => ({
        uuid: row?.cells?.[8]?.data
      }),
      rowDblClick: {
        getUrl: (rowData) => {
          const uuid = rowData?.cells?.[8]?.data;
          return uuid ? new URL(`admin/roles/edit/${uuid}`, appBase).toString() : '';
        }
      }
    });

    if (!gridConfig || !gridConfig.grid) {
      console.warn('Roles grid init failed');
      return null;
    }

    return gridConfig;
  };

  initRolesGrid();
</script>
