<?php

use MintyPHP\Session;

$canPurge = can('settings.update');
?>
<?php
$breadcrumbs = [
  ['label' => t('Home'), 'path' => 'admin'],
  ['label' => t('Scheduled jobs')],
];
require templatePath('partials/app-breadcrumb.phtml');
?>
<div class="app-list-titlebar">
  <h1><?php e(t('Scheduled jobs')); ?></h1>
  <div class="app-list-titlebar-actions">
    <?php if ($canPurge): ?>
      <form id="scheduled-jobs-purge-form" method="post" action="admin/scheduled-jobs/purge-runs">
        <?php Session::getCsrfInput(); ?>
      </form>
      <button
        type="submit"
        form="scheduled-jobs-purge-form"
        class="outline secondary"
        onclick="return confirm('<?php e(t('Purge run logs older than 90 days?')); ?>');"
      >
        <i class="bi bi-trash"></i> <?php e(t('Purge scheduler logs')); ?>
      </button>
    <?php endif; ?>
    <button
      class="outline secondary"
      type="button"
      data-toolbar-toggle
      data-toolbar-target="#scheduled-jobs-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="scheduled-jobs-toolbar">
  <label class="app-field">
    <span><?php e(t('Search')); ?></span>
    <input type="search" id="scheduled-jobs-search" placeholder="<?php e(t('Search...')); ?>">
  </label>
  <label class="app-field">
    <span><?php e(t('Enabled')); ?></span>
    <select id="scheduled-jobs-enabled-filter">
      <option value=""><?php e(t('All')); ?></option>
      <option value="1"><?php e(t('Enabled')); ?></option>
      <option value="0"><?php e(t('Disabled')); ?></option>
    </select>
  </label>
  <label class="app-field">
    <span><?php e(t('Status')); ?></span>
    <select id="scheduled-jobs-status-filter">
      <option value=""><?php e(t('All statuses')); ?></option>
      <option value="running"><?php e(t('Running')); ?></option>
      <option value="success"><?php e(t('Success')); ?></option>
      <option value="failed"><?php e(t('Failed')); ?></option>
      <option value="skipped"><?php e(t('Skipped')); ?></option>
    </select>
  </label>
</div>

<div class="app-list-table">
  <div id="scheduled-jobs-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 statusLabel = (value) => {
    const key = String(value || '').toLowerCase();
    if (key === 'running') {return "<?php e(t('Running')); ?>";}
    if (key === 'success') {return "<?php e(t('Success')); ?>";}
    if (key === 'failed') {return "<?php e(t('Failed')); ?>";}
    if (key === 'skipped') {return "<?php e(t('Skipped')); ?>";}
    return key || '-';
  };

  createServerGrid({
    gridjs: window.gridjs,
    container: '#scheduled-jobs-grid',
    dataUrl: 'admin/scheduled-jobs/data',
    appBase,
    columns: [
      {
        name: "<?php e(t('Job')); ?>",
        sort: true,
        formatter: (cell) => {
          if (!cell || typeof cell !== 'object') {
            return gridjs.html('-');
          }
          const fallbackLabel = String(cell.job_key || '')
            .toLowerCase()
            .replace(/_/g, ' ')
            .replace(/^./, (char) => char.toUpperCase());
          return gridjs.html(cell.label || fallbackLabel || '-');
        }
      },
      {
        name: "<?php e(t('Enabled')); ?>",
        sort: true,
        formatter: (cell) => {
          const enabled = Number(cell) === 1;
          const variant = enabled ? 'success' : 'neutral';
          const label = enabled ? "<?php e(t('Enabled')); ?>" : "<?php e(t('Disabled')); ?>";
          return gridjs.html(`<span class="badge" data-variant="${variant}">${label}</span>`);
        }
      },
      {name: "<?php e(t('Next run')); ?>", sort: true},
      {name: "<?php e(t('Schedule')); ?>", sort: false},
      {name: "<?php e(t('Last run')); ?>", 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'}">${statusLabel(cell.label || '')}</span>`);
        }
      },
      {name: "<?php e(t('Last error')); ?>", sort: false},
      {name: 'ID', hidden: true}
    ],
    sortColumns: ['job_key', 'enabled', 'next_run_at', null, 'last_run_finished_at', 'last_run_status', null, null],
    paginationLimit: 10,
    language: <?php MintyPHP\Buffer::get('grid_lang'); ?>,
    mapData: (data) => data.data.map((row) => [
      {id: row.id, label: row.label || row.job_key, job_key: row.job_key},
      row.enabled,
      row.next_run_at || '-',
      row.schedule_summary || '-',
      row.last_run_finished_at || '-',
      {variant: row.last_run_status_badge, label: row.last_run_status || ''},
      row.last_error || '-',
      row.id
    ]),
    actions: {enabled: false},
    search: {
      input: '#scheduled-jobs-search',
      param: 'search',
      debounce: 250
    },
    filters: [
      {input: '#scheduled-jobs-enabled-filter', param: 'enabled'},
      {input: '#scheduled-jobs-status-filter', param: 'status'}
    ],
    urlSync: true,
    rowDblClick: {
      getUrl: (rowData) => {
        const id = rowData?.cells?.[7]?.data;
        return id ? new URL(`admin/scheduled-jobs/edit/${id}`, appBase).toString() : '';
      }
    }
  });
</script>
