<?php

declare(strict_types=1);

require_once dirname(__DIR__, 3) . '/system/bootstrap.php';

$currentUser = myronRequireAdministrationAccess();
$settings = myronSiteSettings();
$repo = myronSiteAnalyticsRepository();
$retentionDays = myronAnalyticsRetentionDays();
$repo->purgeExpired($retentionDays);
$days = (int) ($_GET['days'] ?? 30);
if (!in_array($days, [7, 30, 90], true)) {
    $days = 30;
}
$analyticsEnabled = myronAnalyticsEnabled();
$summary = $analyticsEnabled ? $repo->getSummary($days) : ['visits' => 0, 'pageviews' => 0, 'top_country' => '', 'top_device' => '', 'top_page' => '', 'top_referrer' => ''];
$trend = $analyticsEnabled ? $repo->getDailyPageviews($days) : [];
$topPages = $analyticsEnabled ? $repo->getTopPages($days, 10) : [];
$trafficSources = $analyticsEnabled ? $repo->getTrafficSources($days, 10) : [];

myronRenderAdminShellStart($currentUser, [
    'title' => 'Analytics',
    'titleContext' => 'Administration',
    'activeItem' => 'analytics',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Administration', 'href' => myronBuildAdminUrl('identity.users')],
      ['label' => 'System', 'href' => myronBuildAdminUrl('administration.siteSetup')],
      ['label' => 'Analytics'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">Analytics</h1>
  </div>
  <p class="mc-workspace__subtitle">Privacy-first site traffic, stored without cookies, IP addresses, or persistent visitor identifiers.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <?php if (!$analyticsEnabled): ?>
    <section class="sg-section">
      <div class="sg-empty-state">
        <h2>Myron Analytics is off</h2>
        <p>Native pageview collection is disabled. Third-party head scripts can still be managed in Site Settings.</p>
        <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('administration.siteSettings')) ?>">Open Site Settings</a>
      </div>
    </section>
    <?php endif; ?>

    <section class="sg-section">
      <div class="sg-card__actions">
        <?php foreach ([7, 30, 90] as $option): ?>
        <a class="sg-button <?= $days === $option ? 'sg-button--primary' : 'sg-button--secondary' ?>" href="<?= myronEscape(myronBuildAdminUrl('administration.analytics', ['days' => $option])) ?>"><?= $option ?>d</a>
        <?php endforeach; ?>
      </div>
      <div class="mc-page-grid mc-page-grid--cards">
        <?php foreach ([
            'Visits' => (string) $summary['visits'],
            'Pageviews' => (string) $summary['pageviews'],
            'Top Country' => (string) ($summary['top_country'] ?: '—'),
            'Top Device' => (string) ($summary['top_device'] ?: '—'),
        ] as $label => $value): ?>
        <article class="sg-card">
          <span class="mc-page-grid__subtle"><?= myronEscape($label) ?></span>
          <strong><?= myronEscape($value) ?></strong>
        </article>
        <?php endforeach; ?>
      </div>
    </section>

    <section class="sg-section">
      <h2 class="sg-section__title">Daily Pageviews</h2>
      <?php if ($trend === []): ?>
      <p class="sg-inline-note">No pageviews recorded for this range.</p>
      <?php else: ?>
      <table class="sg-table">
        <thead><tr><th>Date</th><th>Pageviews</th></tr></thead>
        <tbody>
          <?php foreach ($trend as $row): ?>
          <tr><td><?= myronEscape((string) $row['date']) ?></td><td><?= (int) $row['pageviews'] ?></td></tr>
          <?php endforeach; ?>
        </tbody>
      </table>
      <?php endif; ?>
    </section>

    <section class="sg-section">
      <h2 class="sg-section__title">Top Pages</h2>
      <?php if ($topPages === []): ?>
      <p class="sg-inline-note">No page traffic yet.</p>
      <?php else: ?>
      <table class="sg-table">
        <thead><tr><th>Path</th><th>Views</th></tr></thead>
        <tbody>
          <?php foreach ($topPages as $row): ?>
          <tr><td><code><?= myronEscape((string) $row['path']) ?></code></td><td><?= (int) $row['views'] ?></td></tr>
          <?php endforeach; ?>
        </tbody>
      </table>
      <?php endif; ?>
    </section>

    <section class="sg-section">
      <h2 class="sg-section__title">Top Referrers</h2>
      <?php if ($trafficSources === []): ?>
      <p class="sg-inline-note">No referrer traffic yet.</p>
      <?php else: ?>
      <table class="sg-table">
        <thead><tr><th>Domain</th><th>Visits</th></tr></thead>
        <tbody>
          <?php foreach ($trafficSources as $row): ?>
          <tr><td><?= myronEscape((string) $row['domain']) ?></td><td><?= (int) $row['visits'] ?></td></tr>
          <?php endforeach; ?>
        </tbody>
      </table>
      <?php endif; ?>
    </section>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
