<?php
declare(strict_types=1);

Auth::requireLogin();
require_once __DIR__ . '/_query.php';

[$whereSql, $params, $orderSql] = companies_filter();

$total   = (int) Database::scalar(
    "SELECT COUNT(*) FROM companies c LEFT JOIN watches w ON w.company_id = c.id {$whereSql}",
    $params
);

$page    = max(1, (int) get_int('page', 1));
$perPage = min(PAGE_SIZE_MAX, max(5, (int) get_int('per_page', PAGE_SIZE)));
$offset  = ($page - 1) * $perPage;

$rows = Database::all(
    "SELECT v.*
       FROM v_company_overview v
       JOIN companies c ON c.id = v.id
       LEFT JOIN watches w ON w.company_id = c.id
     {$whereSql}
     {$orderSql}
     LIMIT {$perPage} OFFSET {$offset}",
    $params
);

$tags      = Database::all('SELECT slug, name_en, name_he, is_core_competition FROM tags ORDER BY sort_order');
$countries = Database::all(
    'SELECT co.code, co.name_en, COUNT(c.id) AS n
       FROM countries co JOIN companies c ON c.country_code = co.code
      GROUP BY co.code ORDER BY co.name_en'
);
$analysts = Database::all("SELECT id, full_name FROM users WHERE is_active = 1 ORDER BY full_name");

$selectedTags = get_list('tag');

$PAGE_TITLE    = t('companies_title');
$PAGE_SUBTITLE = t('showing_n_of_m', [
    'from' => number_format(min($total, $offset + 1)),
    'to'   => number_format(min($total, $offset + $perPage)),
    'n'    => number_format($total),
]);

$PAGE_ACTIONS = '';
if (Auth::can('analyst')) {
    $PAGE_ACTIONS .= '<a class="btn btn-primary" href="' . e(url('companies', 'form')) . '">'
                   . e(t('new_company')) . '</a>';
}
$PAGE_ACTIONS .= '<a class="btn" href="' . e(url_with(['a' => 'export', 'page' => null])) . '">'
               . e(t('export_csv')) . '</a>';

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

<section class="panel">
  <div class="panel-body">
    <form method="get" action="<?= e(BASE_URL) ?>/index.php">
      <input type="hidden" name="m" value="companies">
      <input type="hidden" name="a" value="list">

      <div class="filters">
        <div class="field">
          <label class="label" for="f-q"><?= e(t('search')) ?></label>
          <input type="search" id="f-q" name="q" value="<?= e((string) get_param('q', '')) ?>"
                 placeholder="<?= e(t('name')) ?>…">
        </div>

        <div class="field">
          <label class="label" for="f-tag"><?= e(t('keywords')) ?></label>
          <select id="f-tag" name="tag">
            <option value=""><?= e(t('all')) ?></option>
            <?php foreach ($tags as $tag):
                $label = Lang::isRtl() && $tag['name_he'] ? $tag['name_he'] : $tag['name_en']; ?>
              <option value="<?= e($tag['slug']) ?>" <?= in_array($tag['slug'], $selectedTags, true) ? 'selected' : '' ?>>
                <?= e($label) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="field">
          <label class="label" for="f-country"><?= e(t('country')) ?></label>
          <select id="f-country" name="country">
            <option value=""><?= e(t('all')) ?></option>
            <?php foreach ($countries as $c): ?>
              <option value="<?= e($c['code']) ?>" <?= get_param('country') === $c['code'] ? 'selected' : '' ?>>
                <?= e($c['name_en']) ?> (<?= (int) $c['n'] ?>)
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="field">
          <label class="label" for="f-rel"><?= e(t('relationships')) ?></label>
          <select id="f-rel" name="rel_type">
            <option value=""><?= e(t('all')) ?></option>
            <?php foreach (['competitor', 'partner', 'customer', 'distributor', 'supplier', 'watchlist'] as $rel): ?>
              <option value="<?= e($rel) ?>" <?= get_param('rel_type') === $rel ? 'selected' : '' ?>>
                <?= e(ucfirst($rel)) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="field">
          <label class="label" for="f-queue"><?= e(t('last_check')) ?></label>
          <select id="f-queue" name="queue">
            <option value=""><?= e(t('all')) ?></option>
            <option value="overdue"       <?= get_param('queue') === 'overdue' ? 'selected' : '' ?>><?= e(t('queue_overdue')) ?></option>
            <option value="due_soon"      <?= get_param('queue') === 'due_soon' ? 'selected' : '' ?>><?= e(t('queue_due_soon')) ?></option>
            <option value="never_checked" <?= get_param('queue') === 'never_checked' ? 'selected' : '' ?>><?= e(t('queue_never')) ?></option>
            <option value="stale"         <?= get_param('queue') === 'stale' ? 'selected' : '' ?>><?= e(t('thermal_hot')) ?></option>
          </select>
        </div>

        <div class="field">
          <button type="submit" class="btn btn-primary"><?= e(t('apply')) ?></button>
        </div>
      </div>

      <div class="filters-row2">
        <label class="check">
          <input type="checkbox" name="core" value="1" <?= get_param('core') === '1' ? 'checked' : '' ?>>
          <?= e(t('core_only')) ?>
        </label>
        <label class="check">
          <input type="checkbox" name="unrated" value="1" <?= get_param('unrated') === '1' ? 'checked' : '' ?>>
          <?= e(t('unrated_only')) ?>
        </label>
        <label class="check">
          <input type="checkbox" name="tag_mode" value="all" <?= get_param('tag_mode') === 'all' ? 'checked' : '' ?>>
          <?= e(t('match_all_keywords')) ?>
        </label>

        <select name="assigned_to" style="width:auto">
          <option value=""><?= e(t('assigned_to')) ?>: <?= e(t('all')) ?></option>
          <?php foreach ($analysts as $a): ?>
            <option value="<?= (int) $a['id'] ?>" <?= (string) get_param('assigned_to') === (string) $a['id'] ? 'selected' : '' ?>>
              <?= e($a['full_name']) ?>
            </option>
          <?php endforeach; ?>
        </select>

        <a class="btn btn-sm btn-ghost" href="<?= e(url('companies', 'list')) ?>"><?= e(t('clear')) ?></a>
      </div>
    </form>
  </div>
</section>

<section class="panel">
  <div class="panel-head">
    <h2 class="panel-title"><?= e(t('companies_title')) ?></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('no_results')) ?></p>
    <?php else: ?>
    <div class="table-wrap">
      <table class="data">
        <thead>
          <tr>
            <th><?= sort_link('name', t('company')) ?></th>
            <th><?= e(t('keywords')) ?></th>
            <th><?= sort_link('country', t('country')) ?></th>
            <th><?= sort_link('stale', t('last_check')) ?></th>
            <th><?= sort_link('next_due', t('next_due')) ?></th>
            <th class="num"><?= sort_link('threat', t('threat')) ?></th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($rows as $row):
            $rowTags = $row['tags'] ? explode(', ', (string) $row['tags']) : [];
            $rels    = $row['relationships'] ? explode(', ', (string) $row['relationships']) : [];
        ?>
          <tr>
            <td class="cell-name">
              <a href="<?= e(url('companies', 'view', ['id' => $row['id']])) ?>"><?= e($row['name']) ?></a>
              <?php if ($rels): ?>
                <span class="cell-meta">
                  <?php foreach ($rels as $rel): ?><span class="pill pill-<?= e($rel) ?>"><?= e($rel) ?></span> <?php endforeach; ?>
                </span>
              <?php endif; ?>
            </td>
            <td>
              <div class="chips">
                <?php foreach (array_slice($rowTags, 0, 3) as $tagName): ?>
                  <span class="chip"><?= e($tagName) ?></span>
                <?php endforeach; ?>
                <?php if (count($rowTags) > 3): ?>
                  <span class="chip">+<?= count($rowTags) - 3 ?></span>
                <?php endif; ?>
              </div>
            </td>
            <td class="nowrap small"><?= e($row['country_name'] ?: '—') ?></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="num"><?= threat_meter($row['threat_level'] === null ? null : (int) $row['threat_level']) ?></td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?= pager($total, $page, $perPage) ?>
    <?php endif; ?>
  </div>
</section>

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