<?php
declare(strict_types=1);

Auth::requireLogin();

$mine = get_param('mine') === '1';
$params = [];
$extra = '';

if ($mine) {
    $extra = ' AND w.assigned_user_id = :me';
    $params['me'] = Auth::id();
}

/**
 * Ordered by how cold the trail is: never-checked first, then oldest check.
 * That is the working order, not alphabetical.
 */
$rows = Database::all(
    "SELECT c.id, c.name, c.threat_level, c.website,
            w.last_visit_date, w.next_due_date, w.frequency_days, w.is_paused,
            u.full_name AS assigned_to,
            (SELECT GROUP_CONCAT(t.name_en ORDER BY t.sort_order SEPARATOR ' · ')
               FROM company_tags ct JOIN tags t ON t.id = ct.tag_id
              WHERE ct.company_id = c.id) AS tags
       FROM companies c
       JOIN watches w ON w.company_id = c.id
       LEFT JOIN users u ON u.id = w.assigned_user_id
      WHERE w.is_paused = 0
        AND (w.last_visit_date IS NULL OR w.next_due_date IS NULL OR w.next_due_date <= CURDATE())
        {$extra}
      ORDER BY (w.last_visit_date IS NULL) DESC, w.last_visit_date ASC, c.name ASC
      LIMIT 200",
    $params
);

$PAGE_TITLE    = t('queue_title');
$PAGE_SUBTITLE = t('queue_subtitle');

$PAGE_ACTIONS = $mine
    ? '<a class="btn" href="' . e(url('visits', 'queue')) . '">' . e(t('all')) . '</a>'
    : '<a class="btn" href="' . e(url('visits', 'queue', ['mine' => 1])) . '">' . e(t('assigned_to')) . ': '
      . e(Auth::user()['full_name']) . '</a>';

require BASE_DIR . '/includes/layout/header.php';
?>

<section class="panel">
  <div class="panel-head">
    <h2 class="panel-title"><?= e(t('queue_title')) ?> · <?= count($rows) ?></h2>
    <div class="thermal-legend" title="<?= e(t('thermal_legend')) ?>">
      <span><?= e(t('thermal_cold')) ?></span>
      <span class="thermal-scale" aria-hidden="true"></span>
      <span><?= e(t('thermal_hot')) ?></span>
    </div>
  </div>

  <div class="panel-body is-flush">
    <?php if (!$rows): ?>
      <p class="empty"><?= e(t('queue_empty')) ?></p>
    <?php else: ?>
    <div class="table-wrap">
      <table class="data">
        <thead>
          <tr>
            <th><?= e(t('company')) ?></th>
            <th><?= e(t('last_check')) ?></th>
            <th><?= e(t('next_due')) ?></th>
            <th><?= e(t('assigned_to')) ?></th>
            <th class="num"><?= e(t('threat')) ?></th>
            <?php if (Auth::can('analyst')): ?><th class="num"></th><?php endif; ?>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($rows as $row): ?>
          <tr>
            <td class="cell-name">
              <a href="<?= e(url('companies', 'view', ['id' => $row['id']])) ?>"><?= e($row['name']) ?></a>
              <?php if ($row['tags']): ?>
                <span class="cell-meta"><?= e(excerpt($row['tags'], 60)) ?></span>
              <?php endif; ?>
            </td>
            <td class="nowrap"><?= thermal_cell($row['last_visit_date']) ?></td>
            <td class="nowrap mono muted"><?= e(fmt_date($row['next_due_date'])) ?></td>
            <td class="small"><?= e($row['assigned_to'] ?: t('unassigned')) ?></td>
            <td class="num"><?= threat_meter($row['threat_level'] === null ? null : (int) $row['threat_level']) ?></td>
            <?php if (Auth::can('analyst')): ?>
            <td class="num nowrap">
              <?php if ($row['website']): ?>
                <a class="btn btn-sm btn-ghost" href="<?= e($row['website']) ?>"
                   target="_blank" rel="noopener noreferrer"><?= e(t('website')) ?></a>
              <?php endif; ?>
              <form method="post" action="<?= e(url('visits', 'quick')) ?>" style="display:inline">
                <?= Csrf::field() ?>
                <input type="hidden" name="company_id" value="<?= (int) $row['id'] ?>">
                <button class="btn btn-sm" type="submit"><?= e(t('mark_checked')) ?></button>
              </form>
            </td>
            <?php endif; ?>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php endif; ?>
  </div>
</section>

<?php require BASE_DIR . '/includes/layout/footer.php'; ?>
