<?php
use MintyPHP\Router;

$canCreateDepartments = can('departments.create');
$activeTenant = trim((string) ($_GET['tenant'] ?? ''));
$activeStatus = trim((string) ($_GET['active'] ?? ''));
$showTenantTabs = isset($tenants) && is_array($tenants) && count($tenants) > 1;
?>
<?php
$breadcrumbs = [
  ['label' => t('Home'), 'path' => 'admin'],
  ['label' => t('Departments')],
];
require templatePath('partials/app-breadcrumb.phtml');
?>
<div class="app-list-titlebar">
  <h1><?php e(t('Departments')); ?></h1>
  <div class="app-list-titlebar-actions">
    <button
      class="outline secondary"
      type="button"
      data-toolbar-toggle
      data-toolbar-target="#departments-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 ($canCreateDepartments): ?>
      <a role="button" class="primary" href="admin/departments/create">
        <i class="bi bi-plus"></i> <?php e(t('Create department')); ?>
      </a>
    <?php endif; ?>
  </div>
</div>
<?php if ($showTenantTabs): ?>
  <div class="app-list-tabs" id="departments-tabs">
    <a href="admin/departments" class="<?php e($activeTenant === '' ? 'tab-link is-active' : 'tab-link'); ?>">
      <?php e(t('All')); ?>
    </a>
    <?php foreach ($tenants ?? [] as $tenant): ?>
      <?php if (!empty($tenant['uuid'])): ?>
        <?php $isActive = $activeTenant === $tenant['uuid']; ?>
        <a href="admin/departments?tenant=<?php e($tenant['uuid']); ?>" class="<?php e($isActive ? 'tab-link is-active' : 'tab-link'); ?>">
          <?php e($tenant['description'] ?? ''); ?>
        </a>
      <?php endif; ?>
    <?php endforeach; ?>
  </div>
<?php endif; ?>
<div class="app-list-toolbar" id="departments-toolbar">
  <input type="hidden" id="department-tenant-filter" value="<?php e($activeTenant); ?>">
  <label class="app-field">
    <span><?php e(t('Search')); ?></span>
    <input type="search" id="department-search" placeholder="<?php e(t('Search...')); ?>">
  </label>
  <label class="app-field">
    <span><?php e(t('Status')); ?></span>
    <select id="department-status-filter">
      <option value="all" <?php if ($activeStatus === '' || $activeStatus === 'all') { ?>selected<?php } ?>>
        <?php e(t('All')); ?>
      </option>
      <option value="active" <?php if ($activeStatus === 'active' || $activeStatus === '1') { ?>selected<?php } ?>>
        <?php e(t('Active')); ?>
      </option>
      <option value="inactive" <?php if ($activeStatus === 'inactive' || $activeStatus === '0') { ?>selected<?php } ?>>
        <?php e(t('Inactive')); ?>
      </option>
    </select>
  </label>
</div>
<div class="app-list-table">
  <div id="departments-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 initDepartmentsGrid = () => {
    const formatBadge = (value) => badgeHtml(gridjs, value);
    const formatCount = (value) => {
      const number = Number(value ?? 0);
      return Number.isFinite(number) ? number : 0;
    };
    const statusLabels = {
      active: "<?php e(t('Active')); ?>",
      inactive: "<?php e(t('Inactive')); ?>"
    };
    const formatStatus = (value) => {
      const normalized = String(value ?? '1').toLowerCase();
      const isInactive = ['0', 'false', 'inactive'].includes(normalized);
      const variant = isInactive ? 'danger' : 'success';
      const label = isInactive ? statusLabels.inactive : statusLabels.active;
      return gridjs.html(`<span class="badge" data-variant="${variant}">${label}</span>`);
    };
    const gridConfig = createServerGrid({
      gridjs: window.gridjs,
      container: '#departments-grid',
      dataUrl: 'admin/departments/data',
      appBase,
      columns: [
        { name: "<?php e(t('Description')); ?>", sort: true },
        {
          name: "<?php e(t('Status')); ?>",
          sort: false,
          formatter: (cell) => formatStatus(cell)
        },
        { name: "<?php e(t('Code')); ?>", sort: true },
        { name: "<?php e(t('Cost center')); ?>", sort: true },
        {
          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('Created')); ?>",
          sort: true,
          formatter: (cell) => formatBadge(cell)
        },
        {
          name: "<?php e(t('Modified')); ?>",
          sort: true,
          formatter: (cell) => formatBadge(cell)
        },
        {
          name: "UUID",
          hidden: true
        }
      ],
      sortColumns: ['description', null, 'code', 'cost_center', null, null, 'created', 'modified', null],
      paginationLimit: 10,
      language: <?php MintyPHP\Buffer::get('grid_lang'); ?>,
      mapData: (data) => data.data.map((row) => [
        row.description,
        row.active,
        row.code,
        row.cost_center,
        row.active_users ?? 0,
        row.inactive_users ?? 0,
        row.created,
        row.modified,
        row.uuid
      ]),
      actions: { enabled: false },
      search: {
        input: '#department-search',
        param: 'search',
        debounce: 250
      },
      filters: [
        {
          input: '#department-tenant-filter',
          param: 'tenant'
        },
        {
          input: '#department-status-filter',
          param: 'active',
          default: 'all',
          normalize: (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/departments/edit/${uuid}`, appBase).toString() : '';
        }
      }
    });

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

    return gridConfig;
  };

  initDepartmentsGrid();
</script>
