<?php
declare(strict_types=1);

Auth::requireLogin();

$PAGE_TITLE    = t('coverage_title');
$PAGE_SUBTITLE = t('coverage_subtitle');

/** How many competitors sit against each of our own products. */
$ourProducts = Database::all(
    "SELECT o.id, o.name, o.description,
            COUNT(DISTINCT cm.company_id) AS competitors,
            SUM(cm.overlap = 'direct')   AS direct,
            SUM(cm.overlap = 'partial')  AS partial,
            SUM(cm.overlap = 'adjacent') AS adjacent
       FROM own_products o
       LEFT JOIN competition_map cm ON cm.own_product_id = o.id
      WHERE o.is_active = 1
      GROUP BY o.id
      ORDER BY o.sort_order"
);
$maxCompetitors = 1;
foreach ($ourProducts as $p) {
    $maxCompetitors = max($maxCompetitors, (int) $p['competitors']);
}

/** Keyword coverage crossed with how well watched that group is. */
$byTag = Database::all(
    "SELECT t.slug, t.name_en, t.name_he, t.color, t.is_core_competition,
            COUNT(DISTINCT ct.company_id) AS companies,
            SUM(CASE WHEN w.last_visit_date IS NULL THEN 1 ELSE 0 END) AS never_checked,
            ROUND(AVG(DATEDIFF(CURDATE(), w.last_visit_date))) AS avg_days
       FROM tags t
       JOIN company_tags ct ON ct.tag_id = t.id
       LEFT JOIN watches w ON w.company_id = ct.company_id
      GROUP BY t.id
      ORDER BY t.is_core_competition DESC, companies DESC"
);

/** Where competitors are based. */
$byCountry = Database::all(
    'SELECT co.name_en, COUNT(c.id) AS n
       FROM countries co JOIN companies c ON c.country_code = co.code
      GROUP BY co.code HAVING n > 0 ORDER BY n DESC LIMIT 12'
);
$maxCountry = $byCountry ? (int) $byCountry[0]['n'] : 1;

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

<section class="panel">
  <div class="panel-head">
    <div>
      <h2 class="panel-title"><?= e(t('our_product')) ?></h2>
      <p class="panel-sub"><?= e(t('coverage_subtitle')) ?></p>
    </div>
  </div>
  <div class="panel-body">
    <?php foreach ($ourProducts as $p):
        $n = (int) $p['competitors'];
        $width = (int) round(($n / max(1, $maxCompetitors)) * 100);
        $segments = [
            ['direct',   (int) $p['direct'],   'var(--t-72)'],
            ['partial',  (int) $p['partial'],  'var(--t-50)'],
            ['adjacent', (int) $p['adjacent'], 'var(--ink-3)'],
        ];
    ?>
      <div class="coverage-row">
        <div>
          <div class="coverage-name"><?= e($p['name']) ?></div>
          <div class="coverage-sub"><?= e(t('competitors_n', ['n' => $n])) ?></div>
        </div>
        <div>
          <div class="coverage-bar" style="width:<?= max(4, $width) ?>%">
            <?php foreach ($segments as [$label, $count, $color]):
                if ($count < 1) { continue; }
                $pct = (int) round(($count / max(1, $n)) * 100); ?>
              <span class="coverage-seg" style="width:<?= $pct ?>%;background:<?= e($color) ?>"
                    title="<?= e(t('overlap_' . $label)) ?>: <?= $count ?>">
                <?= $pct > 12 ? $count : '' ?>
              </span>
            <?php endforeach; ?>
          </div>
          <?php if ($p['description']): ?>
            <div class="coverage-sub" style="margin-top:.3rem"><?= e($p['description']) ?></div>
          <?php endif; ?>
        </div>
      </div>
    <?php endforeach; ?>

    <p class="hint" style="margin-top:1rem">
      <span style="display:inline-block;width:9px;height:9px;background:var(--t-72);border-radius:1px"></span>
      <?= e(t('overlap_direct')) ?> ·
      <span style="display:inline-block;width:9px;height:9px;background:var(--t-50);border-radius:1px"></span>
      <?= e(t('overlap_partial')) ?> ·
      <span style="display:inline-block;width:9px;height:9px;background:var(--ink-3);border-radius:1px"></span>
      <?= e(t('overlap_adjacent')) ?>
    </p>
  </div>
</section>

<div class="grid grid-2">

  <section class="panel">
    <div class="panel-head"><h2 class="panel-title"><?= e(t('top_keywords')) ?></h2></div>
    <div class="panel-body is-flush">
      <div class="table-wrap">
        <table class="data">
          <thead>
            <tr>
              <th><?= e(t('keywords')) ?></th>
              <th class="num"><?= e(t('companies_count')) ?></th>
              <th class="num"><?= e(t('queue_never')) ?></th>
              <th class="num"><?= e(t('last_check')) ?></th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($byTag as $tag):
              $label = Lang::isRtl() && $tag['name_he'] ? $tag['name_he'] : $tag['name_en'];
              $avg = $tag['avg_days'] === null ? null : (int) $tag['avg_days'];
              $heat = $avg === null ? 1.0 : max(0.0, min(1.0, $avg / STALE_AFTER_DAYS));
          ?>
            <tr>
              <td>
                <a href="<?= e(url('companies', 'list', ['tag' => $tag['slug']])) ?>"
                   class="<?= $tag['is_core_competition'] ? 'cell-name' : '' ?>"><?= e($label) ?></a>
              </td>
              <td class="num"><?= (int) $tag['companies'] ?></td>
              <td class="num<?= (int) $tag['never_checked'] > 0 ? '' : ' muted' ?>"><?= (int) $tag['never_checked'] ?></td>
              <td class="num">
                <span class="thermal" title="<?= $avg === null ? e(t('never')) : $avg . ' d' ?>">
                  <span class="thermal-fill" style="width:<?= (int) round($heat * 100) ?>%;background:<?= e(thermal_color($heat)) ?>"></span>
                </span>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </section>

  <section class="panel">
    <div class="panel-head"><h2 class="panel-title"><?= e(t('country')) ?></h2></div>
    <div class="panel-body stack">
      <?php foreach ($byCountry as $c): ?>
        <div>
          <div style="display:flex;justify-content:space-between;font-size:13px">
            <span><?= e($c['name_en']) ?></span>
            <span class="mono muted"><?= (int) $c['n'] ?></span>
          </div>
          <div style="height:4px;background:var(--rule-soft);border-radius:1px;margin-top:.25rem">
            <div style="height:100%;border-radius:1px;background:var(--ink-2);width:<?= (int) round(((int) $c['n'] / max(1, $maxCountry)) * 100) ?>%"></div>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  </section>

</div>

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