<?php
declare(strict_types=1);

/**
 * The crawler's output: pages that moved, waiting for someone to look.
 * This is the screen that turns "check 79 sites" into "look at the 4 that changed".
 */

Auth::requireLogin();

$status = in_array(get_param('status'), ['new', 'reviewed', 'ignored'], true)
    ? (string) get_param('status') : 'new';

$where  = ['ch.status = :status'];
$params = ['status' => $status];

if (($cid = get_int('company')) !== null) {
    $where[] = 'ch.company_id = :cid';
    $params['cid'] = $cid;
}
if (get_param('core') === '1') {
    $where[] = 'EXISTS (SELECT 1 FROM company_tags ct JOIN tags t ON t.id = ct.tag_id
                         WHERE ct.company_id = ch.company_id AND t.is_core_competition = 1)';
}

$whereSql = 'WHERE ' . implode(' AND ', $where);

$page    = max(1, (int) get_int('page', 1));
$perPage = 20;
$offset  = ($page - 1) * $perPage;

$total = (int) Database::scalar("SELECT COUNT(*) FROM link_changes ch {$whereSql}", $params);

$changes = Database::all(
    "SELECT ch.*, c.name AS company_name, c.threat_level, l.url, l.link_type,
            u.full_name AS reviewer
       FROM link_changes ch
       JOIN companies c ON c.id = ch.company_id
       JOIN links l     ON l.id = ch.link_id
       LEFT JOIN users u ON u.id = ch.reviewed_by
     {$whereSql}
     ORDER BY ch.change_ratio DESC, ch.detected_at DESC
     LIMIT {$perPage} OFFSET {$offset}",
    $params
);

$counts = Database::pairs('SELECT status, COUNT(*) FROM link_changes GROUP BY status');

$feed = Database::all(
    "SELECT f.id, f.title, f.url, f.summary, f.published_at,
            c.id AS company_id, c.name AS company_name
       FROM feed_items f
       JOIN companies c ON c.id = f.company_id
      WHERE f.status = 'new'
      ORDER BY f.published_at DESC, f.id DESC
      LIMIT 12"
);

$lastRun = Database::one('SELECT * FROM fetch_runs ORDER BY started_at DESC LIMIT 1');
$dueNow  = Crawler::dueCount();

$PAGE_TITLE    = t('signals_title');
$PAGE_SUBTITLE = t('signals_subtitle');

$PAGE_ACTIONS = '';
if (Auth::can('analyst')) {
    $PAGE_ACTIONS =
        '<form method="post" action="' . e(url('signals', 'run')) . '" data-no-lock="0">'
      . Csrf::field()
      . '<button type="submit" class="btn btn-primary" data-busy="' . e(t('crawl_running')) . '">'
      . e($dueNow > 0 ? t('crawl_run_now_n', ['n' => min(12, $dueNow)]) : t('crawl_run_now'))
      . '</button></form>';
}

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

<?php if ($lastRun === null): ?>
  <div class="flash flash-warn">
    <?= e(t('signals_never_run')) ?>
    <code class="login-code">php tools/fetch_links.php --verbose</code>
  </div>
<?php elseif ($lastRun['finished_at'] === null): ?>
  <div class="flash flash-warn"><?= e(t('signals_run_incomplete')) ?></div>
<?php endif; ?>

<section class="panel">
  <div class="panel-body">
    <div style="display:flex;gap:.4rem;flex-wrap:wrap;align-items:center">
      <?php foreach (['new', 'reviewed', 'ignored'] as $s): ?>
        <a class="btn btn-sm<?= $status === $s ? ' btn-primary' : '' ?>"
           href="<?= e(url('signals', 'index', ['status' => $s])) ?>">
          <?= e(t('signal_status_' . $s)) ?> · <?= (int) ($counts[$s] ?? 0) ?>
        </a>
      <?php endforeach; ?>

      <a class="btn btn-sm<?= get_param('core') === '1' ? ' btn-primary' : '' ?>"
         href="<?= e(url_with(['core' => get_param('core') === '1' ? null : '1', 'page' => null])) ?>">
        <?= e(t('core_only')) ?>
      </a>

      <span style="margin-inline-start:auto" class="mono muted small">
        <?php if ($lastRun): ?>
          <?= e(t('last_run')) ?>: <?= e(fmt_ago(substr((string) $lastRun['started_at'], 0, 10))) ?>
          · <?= (int) $lastRun['links_checked'] ?> <?= e(t('checked')) ?>
          · <?= (int) $lastRun['errors'] ?> <?= e(t('errors')) ?>
          · <?= (int) $dueNow ?> <?= e(t('due_now')) ?>
        <?php endif; ?>
      </span>
    </div>
  </div>
</section>

<?php if (!$changes): ?>
  <section class="panel">
    <p class="empty"><?= e($status === 'new' ? t('signals_none_new') : t('no_results')) ?></p>
  </section>
<?php else: ?>

  <?php foreach ($changes as $ch):
      $ratioPct = (float) $ch['change_ratio'] * 100;
      // How much moved drives the same thermal ramp used everywhere else.
      $heat = min(1.0, (float) $ch['change_ratio'] * 8);
  ?>
    <section class="panel signal">
      <div class="panel-head">
        <div>
          <h2 class="panel-title" style="text-transform:none;letter-spacing:0;font-size:14px">
            <a href="<?= e(url('companies', 'view', ['id' => $ch['company_id']])) ?>">
              <?= e($ch['company_name']) ?>
            </a>
            <span class="muted" style="font-weight:400">
              — <?= e(t('change_kind_' . $ch['change_kind'])) ?>
            </span>
          </h2>
          <p class="panel-sub">
            <a href="<?= e($ch['url']) ?>" target="_blank" rel="noopener noreferrer">
              <?= e(excerpt($ch['url'], 70)) ?>
            </a>
            · <?= e(fmt_ago(substr((string) $ch['detected_at'], 0, 10))) ?>
          </p>
        </div>

        <div style="text-align:end">
          <span class="thermal" title="<?= e(number_format($ratioPct, 1)) ?>%">
            <span class="thermal-fill" style="width:<?= (int) round($heat * 100) ?>%;background:<?= e(thermal_color($heat)) ?>"></span>
          </span>
          <div class="mono muted" style="font-size:11.5px;margin-top:.2rem">
            +<?= (int) $ch['words_added'] ?> / &minus;<?= (int) $ch['words_removed'] ?>
          </div>
        </div>
      </div>

      <div class="panel-body">
        <?php if ($ch['added_excerpt']): ?>
          <div class="diff diff-added">
            <div class="diff-label"><?= e(t('added')) ?></div>
            <?= nl2br(e(excerpt($ch['added_excerpt'], 700))) ?>
          </div>
        <?php endif; ?>

        <?php if ($ch['removed_excerpt']): ?>
          <div class="diff diff-removed">
            <div class="diff-label"><?= e(t('removed')) ?></div>
            <?= nl2br(e(excerpt($ch['removed_excerpt'], 400))) ?>
          </div>
        <?php endif; ?>

        <?php if ($ch['status'] === 'new' && Auth::can('analyst')): ?>
          <form method="post" action="<?= e(url('signals', 'review')) ?>" class="signal-actions">
            <?= Csrf::field() ?>
            <input type="hidden" name="id" value="<?= (int) $ch['id'] ?>">
            <input type="hidden" name="return" value="<?= e($status) ?>">

            <input type="text" name="findings" class="signal-note"
                   placeholder="<?= e(t('signal_note_placeholder')) ?>">

            <button class="btn btn-sm btn-primary" type="submit" name="action" value="log">
              <?= e(t('signal_log_check')) ?>
            </button>
            <button class="btn btn-sm" type="submit" name="action" value="reviewed">
              <?= e(t('signal_mark_reviewed')) ?>
            </button>
            <button class="btn btn-sm btn-ghost" type="submit" name="action" value="ignored">
              <?= e(t('signal_ignore')) ?>
            </button>
          </form>
        <?php elseif ($ch['reviewer']): ?>
          <p class="small muted" style="margin:.6rem 0 0">
            <?= e(t('signal_status_' . $ch['status'])) ?> · <?= e($ch['reviewer']) ?>
            · <?= e(fmt_date(substr((string) $ch['reviewed_at'], 0, 10))) ?>
          </p>
        <?php endif; ?>
      </div>
    </section>
  <?php endforeach; ?>

  <?= pager($total, $page, $perPage) ?>
<?php endif; ?>

<?php if ($feed): ?>
<section class="panel">
  <div class="panel-head"><h2 class="panel-title"><?= e(t('feed_items')) ?></h2></div>
  <div class="panel-body">
    <ul class="timeline">
      <?php foreach ($feed as $item): ?>
        <li>
          <span class="timeline-date"><?= e(fmt_date(substr((string) $item['published_at'], 0, 10))) ?></span>
          <div>
            <div class="timeline-body">
              <a href="<?= e(url('companies', 'view', ['id' => $item['company_id']])) ?>"><?= e($item['company_name']) ?></a>
              &mdash;
              <?php if ($item['url']): ?>
                <a href="<?= e($item['url']) ?>" target="_blank" rel="noopener noreferrer"><?= e($item['title']) ?></a>
              <?php else: ?>
                <?= e($item['title']) ?>
              <?php endif; ?>
            </div>
            <?php if ($item['summary']): ?>
              <div class="timeline-meta"><?= e(excerpt($item['summary'], 160)) ?></div>
            <?php endif; ?>
          </div>
        </li>
      <?php endforeach; ?>
    </ul>
  </div>
</section>
<?php endif; ?>

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