<?php
declare(strict_types=1);

Auth::requireLogin();

$PAGE_TITLE    = t('dashboard_title');
$PAGE_SUBTITLE = t('dash_subtitle');

$totals = [
    'companies'   => (int) Database::scalar('SELECT COUNT(*) FROM companies'),
    'competitors' => (int) Database::scalar(
        "SELECT COUNT(DISTINCT company_id) FROM company_relationships WHERE rel_type = 'competitor'"),
    'products'    => (int) Database::scalar('SELECT COUNT(*) FROM products'),
    'unrated'     => (int) Database::scalar('SELECT COUNT(*) FROM companies WHERE threat_level IS NULL'),
];

$queue = Database::pairs(
    'SELECT queue_status, COUNT(*) FROM v_watch_queue GROUP BY queue_status'
);

/* The coldest trails among companies that actually compete with us. */
$coldest = Database::all(
    "SELECT c.id, c.name, c.threat_level, w.last_visit_date, 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 AND t.is_core_competition = 1) AS core_tags
       FROM companies c
       JOIN watches w ON w.company_id = c.id AND w.is_paused = 0
       LEFT JOIN users u ON u.id = w.assigned_user_id
      WHERE EXISTS (SELECT 1 FROM company_tags ct JOIN tags t ON t.id = ct.tag_id
                     WHERE ct.company_id = c.id AND t.is_core_competition = 1)
      ORDER BY (w.last_visit_date IS NULL) DESC, w.last_visit_date ASC
      LIMIT 12"
);

$recent = Database::all(
    'SELECT v.visit_date, v.significance, v.findings, c.id AS company_id, c.name AS company,
            u.full_name AS analyst
       FROM visits v
       JOIN companies c ON c.id = v.company_id
       LEFT JOIN users u ON u.id = v.user_id
      ORDER BY v.visit_date DESC, v.id DESC
      LIMIT 8'
);

$byTag = Database::all(
    'SELECT t.slug, t.name_en, t.name_he, t.color, t.is_core_competition,
            COUNT(ct.company_id) AS n
       FROM tags t
       LEFT JOIN company_tags ct ON ct.tag_id = t.id
      GROUP BY t.id
     HAVING n > 0
      ORDER BY n DESC
      LIMIT 14'
);
$maxTag = $byTag ? max(array_map(static fn($r) => (int) $r['n'], $byTag)) : 1;

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

<div class="stats">
  <div class="stat">
    <div class="stat-n"><?= number_format($totals['companies']) ?></div>
    <div class="stat-label"><?= e(t('stat_companies')) ?></div>
  </div>
  <div class="stat">
    <div class="stat-n"><?= number_format($totals['competitors']) ?></div>
    <div class="stat-label"><?= e(t('stat_competitors')) ?></div>
  </div>
  <div class="stat">
    <div class="stat-n"><?= number_format($totals['products']) ?></div>
    <div class="stat-label"><?= e(t('stat_products')) ?></div>
  </div>
  <div class="stat<?= $totals['unrated'] > 0 ? ' is-alert' : '' ?>">
    <div class="stat-n"><?= number_format($totals['unrated']) ?></div>
    <div class="stat-label"><?= e(t('stat_unrated')) ?></div>
  </div>
</div>

<div class="grid grid-main">

  <section class="panel">
    <div class="panel-head">
      <div>
        <h2 class="panel-title"><?= e(t('oldest_checks')) ?></h2>
        <p class="panel-sub"><?= e(t('oldest_checks_sub')) ?></p>
      </div>
      <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 (!$coldest): ?>
        <p class="empty"><?= e(t('no_results')) ?></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('assigned_to')) ?></th>
              <th class="num"><?= e(t('threat')) ?></th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($coldest as $row):
              $heat = staleness($row['last_visit_date']);
              $color = thermal_color($heat);
          ?>
            <tr>
              <td class="cell-name">
                <a href="<?= e(url('companies', 'view', ['id' => $row['id']])) ?>"><?= e($row['name']) ?></a>
                <?php if ($row['core_tags']): ?>
                  <span class="cell-meta"><?= e(excerpt($row['core_tags'], 54)) ?></span>
                <?php endif; ?>
              </td>
              <td class="nowrap">
                <span class="trail<?= $heat > .72 ? ' is-cold-trail' : '' ?>">
                  <span class="thermal" title="<?= e(fmt_date($row['last_visit_date'])) ?>">
                    <span class="thermal-fill" style="width:<?= (int) round($heat * 100) ?>%;background:<?= e($color) ?>"></span>
                  </span>
                  <span class="trail-text"><?= e(fmt_ago($row['last_visit_date'])) ?></span>
                </span>
              </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>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
      <?php endif; ?>
    </div>
  </section>

  <div>
    <section class="panel">
      <div class="panel-head"><h2 class="panel-title"><?= e(t('nav_queue')) ?></h2></div>
      <div class="panel-body stack">
        <?php
        $queueRows = [
            ['overdue',       t('queue_overdue'),   't-72'],
            ['never_checked', t('queue_never'),     't-88'],
            ['due_soon',      t('queue_due_soon'),  't-50'],
            ['ok',            t('queue_ok'),        'ok'],
        ];
        foreach ($queueRows as [$key, $label, $tone]):
            $n = (int) ($queue[$key] ?? 0);
        ?>
          <div style="display:flex;align-items:center;justify-content:space-between;gap:.75rem">
            <a href="<?= e(url('companies', 'list', ['queue' => $key])) ?>"><?= e($label) ?></a>
            <span class="mono" style="color:var(--<?= e($tone) ?>);font-weight:500"><?= $n ?></span>
          </div>
        <?php endforeach; ?>
        <div class="divider"></div>
        <a class="btn btn-sm" href="<?= e(url('visits', 'queue')) ?>"><?= e(t('nav_queue')) ?></a>
      </div>
    </section>

    <section class="panel">
      <div class="panel-head"><h2 class="panel-title"><?= e(t('top_keywords')) ?></h2></div>
      <div class="panel-body stack">
        <?php foreach ($byTag as $tag):
            $label = Lang::isRtl() && $tag['name_he'] ? $tag['name_he'] : $tag['name_en'];
            $pct = (int) round(((int) $tag['n'] / max(1, $maxTag)) * 100);
        ?>
          <div>
            <div style="display:flex;justify-content:space-between;gap:.5rem;font-size:12.5px">
              <a href="<?= e(url('companies', 'list', ['tag' => $tag['slug']])) ?>"><?= e($label) ?></a>
              <span class="mono muted"><?= (int) $tag['n'] ?></span>
            </div>
            <div style="height:4px;background:var(--rule-soft);border-radius:1px;margin-top:.25rem">
              <div style="height:100%;width:<?= $pct ?>%;border-radius:1px;background:<?= e($tag['is_core_competition'] ? 'var(--accent)' : 'var(--ink-3)') ?>"></div>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
    </section>
  </div>
</div>

<section class="panel">
  <div class="panel-head"><h2 class="panel-title"><?= e(t('recent_activity')) ?></h2></div>
  <div class="panel-body">
    <?php if (!$recent): ?>
      <p class="empty"><?= e(t('no_recent_checks')) ?></p>
    <?php else: ?>
      <ul class="timeline">
        <?php foreach ($recent as $v): ?>
          <li>
            <span class="timeline-date"><?= e(fmt_date($v['visit_date'])) ?></span>
            <div>
              <div class="timeline-body">
                <span class="sig sig-<?= e($v['significance']) ?>" aria-hidden="true"></span>
                <a href="<?= e(url('companies', 'view', ['id' => $v['company_id']])) ?>"><?= e($v['company']) ?></a>
                <?php if ($v['findings']): ?>
                  — <?= e(excerpt($v['findings'], 140)) ?>
                <?php endif; ?>
              </div>
              <div class="timeline-meta"><?= e($v['analyst'] ?: '—') ?></div>
            </div>
          </li>
        <?php endforeach; ?>
      </ul>
    <?php endif; ?>
  </div>
</section>

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