<?php
use MintyPHP\Router;
?>
<?php
$breadcrumbs = [
  ['label' => t('Home'), 'path' => 'admin'],
  ['label' => t('Mail logs')],
];
require templatePath('partials/app-breadcrumb.phtml');
?>
<div class="app-list-titlebar">
  <h1><?php e(t('Mail logs')); ?></h1>
  <div class="app-list-titlebar-actions">
    <button
      class="outline secondary"
      type="button"
      data-toolbar-toggle
      data-toolbar-target="#mail-log-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="mail-log-toolbar">
  <label class="app-field">
    <span><?php e(t('Search')); ?></span>
    <input type="search" id="mail-log-search" placeholder="<?php e(t('Search...')); ?>">
  </label>
  <label class="app-field">
    <span><?php e(t('Status')); ?></span>
    <select id="mail-log-status-filter">
      <option value=""><?php e(t('All statuses')); ?></option>
      <option value="sent"><?php e(t('Sent')); ?></option>
      <option value="queued"><?php e(t('Queued')); ?></option>
      <option value="failed"><?php e(t('Failed')); ?></option>
    </select>
  </label>
  <label class="app-field">
    <span><?php e(t('Created from')); ?></span>
    <input type="date" id="mail-log-created-from">
  </label>
  <label class="app-field">
    <span><?php e(t('Created to')); ?></span>
    <input type="date" id="mail-log-created-to">
  </label>
</div>
<div class="app-list-table">
  <div id="mail-log-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 initMailLogGrid = () => {
    const gridConfig = createServerGrid({
      gridjs: window.gridjs,
      container: '#mail-log-grid',
      dataUrl: 'admin/mail-log/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('');
            }
            const variant = cell.variant || 'neutral';
            const label = cell.label || '';
            return gridjs.html(`<span class="badge" data-variant="${variant}">${label}</span>`);
          }
        },
        {
          name: "<?php e(t('Recipient')); ?>",
          sort: true,
          formatter: (cell) => {
            if (!cell || typeof cell !== 'object') {
              return gridjs.html(String(cell ?? ''));
            }
            return gridjs.html(String(cell ?? ''));
          }
        },
        {
          name: "<?php e(t('Subject')); ?>",
          sort: true
        },
        {
          name: "<?php e(t('Template')); ?>",
          sort: false
        },
        {
          name: "ID",
          hidden: true
        }
      ],
      sortColumns: ['created_at', 'status', 'to_email', 'subject', null, 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_label
        },
        row.to_email,
        row.subject,
        row.template || '-',
        row.id
      ]),
      actions: {
        enabled: false
      },
      search: {
        input: '#mail-log-search',
        param: 'search',
        debounce: 250
      },
      filters: [
        {
          input: '#mail-log-status-filter',
          param: 'status'
        },
        {
          input: '#mail-log-created-from',
          param: 'created_from',
          normalize: (value) => (value ? value : '')
        },
        {
          input: '#mail-log-created-to',
          param: 'created_to',
          normalize: (value) => (value ? value : '')
        }
      ],
      urlSync: true,
      rowDblClick: {
        getUrl: (rowData) => {
          const id = rowData?.cells?.[5]?.data;
          return id ? new URL(`admin/mail-log/view/${id}`, appBase).toString() : '';
        }
      }
    });

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

    return gridConfig;
  };

  initMailLogGrid();
</script>
