<?php

use MintyPHP\Session;

$canPurge = can('settings.update');
?>
<?php
$breadcrumbs = [
  ['label' => t('Home'), 'path' => 'admin'],
  ['label' => t('User lifecycle logs')],
];
require templatePath('partials/app-breadcrumb.phtml');
?>
<div class="app-list-titlebar">
  <h1><?php e(t('User lifecycle logs')); ?></h1>
  <div class="app-list-titlebar-actions">
    <?php if ($canPurge): ?>
      <form id="user-lifecycle-audit-purge-form" method="post" action="admin/user-lifecycle-audit/purge">
        <?php Session::getCsrfInput(); ?>
      </form>
      <button
        type="submit"
        form="user-lifecycle-audit-purge-form"
        class="outline secondary"
        onclick="return confirm('<?php e(t('Purge entries older than 365 days?')); ?>');"
      >
        <i class="bi bi-trash"></i> <?php e(t('Purge user lifecycle logs')); ?>
      </button>
    <?php endif; ?>
    <button
      class="outline secondary"
      type="button"
      data-toolbar-toggle
      data-toolbar-target="#user-lifecycle-audit-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>
  </div>
</div>

<div class="app-list-toolbar" id="user-lifecycle-audit-toolbar">
  <label class="app-field">
    <span><?php e(t('Search')); ?></span>
    <input type="search" id="user-lifecycle-audit-search" placeholder="<?php e(t('Search...')); ?>">
  </label>
  <label class="app-field">
    <span><?php e(t('Action')); ?></span>
    <select id="user-lifecycle-audit-action-filter">
      <option value=""><?php e(t('All actions')); ?></option>
      <option value="deactivate"><?php e(t('Deactivate')); ?></option>
      <option value="delete"><?php e(t('Delete')); ?></option>
      <option value="restore"><?php e(t('Restore')); ?></option>
    </select>
  </label>
  <label class="app-field">
    <span><?php e(t('Status')); ?></span>
    <select id="user-lifecycle-audit-status-filter">
      <option value=""><?php e(t('All statuses')); ?></option>
      <option value="success"><?php e(t('Success')); ?></option>
      <option value="skipped"><?php e(t('Skipped')); ?></option>
      <option value="failed"><?php e(t('Failed')); ?></option>
    </select>
  </label>
  <label class="app-field">
    <span><?php e(t('Trigger')); ?></span>
    <select id="user-lifecycle-audit-trigger-filter">
      <option value=""><?php e(t('All triggers')); ?></option>
      <option value="manual"><?php e(t('Manual')); ?></option>
      <option value="cron"><?php e(t('Cron')); ?></option>
      <option value="system"><?php e(t('System')); ?></option>
    </select>
  </label>
  <label class="app-field">
    <span><?php e(t('Created from')); ?></span>
    <input type="date" id="user-lifecycle-audit-created-from">
  </label>
  <label class="app-field">
    <span><?php e(t('Created to')); ?></span>
    <input type="date" id="user-lifecycle-audit-created-to">
  </label>
</div>

<div class="app-list-table">
  <div id="user-lifecycle-audit-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 { getAppBase } from "<?php e(asset('js/pages/app-list-utils.js')); ?>";

  const appBase = getAppBase();
  const labelMap = {
    deactivate: "<?php e(t('Deactivate')); ?>",
    delete: "<?php e(t('Delete')); ?>",
    restore: "<?php e(t('Restore')); ?>",
    success: "<?php e(t('Success')); ?>",
    skipped: "<?php e(t('Skipped')); ?>",
    failed: "<?php e(t('Failed')); ?>",
    manual: "<?php e(t('Manual')); ?>",
    cron: "<?php e(t('Cron')); ?>",
    system: "<?php e(t('System')); ?>"
  };
  const toLabel = (value) => labelMap[String(value || '').toLowerCase()] || String(value || '-');

  createServerGrid({
    gridjs: window.gridjs,
    container: '#user-lifecycle-audit-grid',
    dataUrl: 'admin/user-lifecycle-audit/data',
    appBase,
    columns: [
      {name: "<?php e(t('Created')); ?>", sort: true},
      {
        name: "<?php e(t('Status')); ?>",
        sort: true,
        formatter: (cell) => {
          if (!cell || typeof cell !== 'object') {
            return gridjs.html('-');
          }
          return gridjs.html(`<span class="badge" data-variant="${cell.variant || 'neutral'}">${toLabel(cell.label || '')}</span>`);
        }
      },
      {name: "<?php e(t('Action')); ?>", sort: true, formatter: (cell) => toLabel(cell)},
      {name: "<?php e(t('Trigger')); ?>", sort: true, formatter: (cell) => toLabel(cell)},
      {name: "<?php e(t('Target email')); ?>", sort: false},
      {name: "<?php e(t('Target UUID')); ?>", sort: false},
      {name: "<?php e(t('Reason code')); ?>", sort: false},
      {name: "<?php e(t('Restored at')); ?>", sort: true},
      {name: 'ID', hidden: true}
    ],
    sortColumns: ['created_at', 'status', 'action', 'trigger_type', null, null, null, 'restored_at', null],
    paginationLimit: 10,
    language: <?php MintyPHP\Buffer::get('grid_lang'); ?>,
    mapData: (data) => data.data.map((row) => [
      row.created_at,
      {variant: row.status_badge, label: row.status || ''},
      row.action || '',
      row.trigger_type || '',
      row.target_user_email || '-',
      row.target_user_uuid || '-',
      row.reason_code || '-',
      row.restored_at || '-',
      row.id
    ]),
    actions: {enabled: false},
    search: {
      input: '#user-lifecycle-audit-search',
      param: 'search',
      debounce: 250
    },
    filters: [
      {input: '#user-lifecycle-audit-action-filter', param: 'action'},
      {input: '#user-lifecycle-audit-status-filter', param: 'status'},
      {input: '#user-lifecycle-audit-trigger-filter', param: 'trigger_type'},
      {input: '#user-lifecycle-audit-created-from', param: 'created_from'},
      {input: '#user-lifecycle-audit-created-to', param: 'created_to'}
    ],
    urlSync: true,
    rowDblClick: {
      getUrl: (rowData) => {
        const id = rowData?.cells?.[8]?.data;
        return id ? new URL(`admin/user-lifecycle-audit/view/${id}`, appBase).toString() : '';
      }
    }
  });
</script>

