<?php

require __DIR__ . '/../bootstrap.php';

use KeyLair\Auth;
use KeyLair\Database;
use KeyLair\Deployer;
use KeyLair\DemoMask;
use KeyLair\Helpers;
use KeyLair\I18n;
use KeyLair\Platform;
use KeyLair\Settings;

Auth::requireLogin();
$pdo = Database::connection();

$channelLabels = [
    'stable' => I18n::t('dashboard.channel.stable'),
    'beta' => I18n::t('dashboard.channel.beta'),
    'alpha' => I18n::t('dashboard.channel.alpha'),
    'dev' => I18n::t('dashboard.channel.dev'),
];
$updateChannel = Settings::updateChannel();

$updateAvailable = false;
$remoteVersion = null;
if (Auth::isMasterAdmin() && class_exists('ZipArchive')) {
    $remoteVersion = Deployer::remoteVersion();
    // Only a genuine forward update -- a plain !== also fired when the
    // checked channel's latest happens to be numerically *behind* what's
    // already installed (e.g. switched from Development back to Stable,
    // which hasn't caught up to a pre-release build yet), which read as
    // an "update available" prompt for what was actually a downgrade.
    $updateAvailable = $remoteVersion !== null
        && version_compare($remoteVersion, (string) Deployer::currentVersion(), '>');
}

$totalKeys = (int) $pdo->query('SELECT COUNT(*) FROM `keys`')->fetchColumn();
$redeemedKeys = (int) $pdo->query("SELECT COUNT(*) FROM `keys` WHERE status='redeemed'")->fetchColumn();
// Not just "total - redeemed" -- an exported key isn't redeemed, but it's
// also not actually remaining/claimable anymore either (see
// admin/keys_export.php), so it has to be excluded from both sides.
$remainingKeys = (int) $pdo->query("SELECT COUNT(*) FROM `keys` WHERE status='available'")->fetchColumn();
$rate = $totalKeys > 0 ? round($redeemedKeys / $totalKeys * 100, 1) : 0;

$platformStmt = $pdo->query(
    'SELECT p.id AS product_id, p.name AS product_name, k.platform, COUNT(*) AS total
     FROM `keys` k
     JOIN products p ON p.id = k.product_id
     GROUP BY p.id, k.platform
     ORDER BY p.name ASC, k.platform ASC'
);
$productPlatformTotals = [];
$maxPlatformTotal = 1;
foreach ($platformStmt->fetchAll() as $row) {
    $productPlatformTotals[$row['product_id']]['name'] = $row['product_name'];
    $productPlatformTotals[$row['product_id']]['platforms'][$row['platform']] = (int) $row['total'];
    $maxPlatformTotal = max($maxPlatformTotal, (int) $row['total']);
}

$recent = $pdo->query(
    "SELECT r.redeemed_at, r.platform, u.name AS user_name, cl.user_id, c.name AS campaign_name
     FROM redemptions r
     JOIN claim_links cl ON cl.id = r.claim_link_id
     LEFT JOIN users u ON u.id = cl.user_id
     LEFT JOIN campaigns c ON c.id = cl.campaign_id
     ORDER BY r.redeemed_at DESC
     LIMIT 8"
)->fetchAll();

$pageTitle = I18n::t('dashboard.page_title');
$activeNav = 'dashboard';
require __DIR__ . '/includes/layout_header.php';
?>
<div class="topbar">
  <h1><?= Helpers::e(I18n::t('dashboard.page_title')) ?></h1>
</div>

<?php if ($updateAvailable): ?>
<div class="panel" style="border-color:var(--key-gold); margin-bottom:16px; display:flex; align-items:center; justify-content:space-between; gap:16px; flex-wrap:wrap;">
  <div>
    <p style="color:var(--key-gold); font-size:13px; font-weight:600; margin:0 0 2px;">
      <?= Helpers::e(I18n::t('dashboard.update_available')) ?><?php if ($updateChannel !== 'stable'): ?> &middot; <?= Helpers::e($channelLabels[$updateChannel]) ?><?php endif; ?>
    </p>
    <p style="color:var(--text-muted); font-size:12.5px; margin:0;"><?= sprintf(I18n::t('dashboard.update_version_ready'), Helpers::e($remoteVersion)) ?></p>
  </div>
  <a href="deploy.php" class="btn btn-primary" style="text-decoration:none;"><?= Helpers::e(I18n::t('dashboard.open_updates')) ?></a>
</div>
<?php endif; ?>

<div class="stat-grid">
  <div class="stat-card">
    <div class="stat-label"><?= Helpers::e(I18n::t('dashboard.stat.total_keys')) ?></div>
    <div class="stat-value"><?= number_format($totalKeys) ?></div>
  </div>
  <div class="stat-card">
    <div class="stat-label"><?= Helpers::e(I18n::t('dashboard.stat.remaining')) ?></div>
    <div class="stat-value signal"><?= number_format($remainingKeys) ?></div>
  </div>
  <div class="stat-card">
    <div class="stat-label"><?= Helpers::e(I18n::t('dashboard.stat.redeemed')) ?></div>
    <div class="stat-value gold"><?= number_format($redeemedKeys) ?></div>
  </div>
  <div class="stat-card">
    <div class="stat-label"><?= Helpers::e(I18n::t('dashboard.stat.redemption_rate')) ?></div>
    <div class="stat-value"><?= $rate ?>%</div>
  </div>
</div>

<div class="row-2 row-2-even">
  <div class="panel">
    <p class="panel-title"><?= Helpers::e(I18n::t('dashboard.keys_by_platform_title')) ?></p>
    <?php if (empty($productPlatformTotals)): ?>
      <p style="color:var(--text-faint); font-size:13px;"><?= Helpers::e(I18n::t('dashboard.no_keys_yet')) ?></p>
    <?php else: ?>
      <?php $firstProduct = array_key_first($productPlatformTotals); ?>
      <?php foreach ($productPlatformTotals as $productId => $data): ?>
        <p style="font-weight:600; font-size:12.5px; color:var(--text-primary); margin:<?= $productId === $firstProduct ? '0' : '16px' ?> 0 8px; <?= $productId === $firstProduct ? '' : 'padding-top:12px; border-top:1px solid var(--line);' ?>"><?= Helpers::e($data['name']) ?></p>
        <div class="bar-list">
        <?php foreach ($data['platforms'] as $platform => $count):
            $width = $count > 0 ? max(4, round($count / $maxPlatformTotal * 100)) : 0;
        ?>
          <div class="bar-row">
            <span class="bar-plat"><?= Helpers::e(Platform::label($platform)) ?></span>
            <div class="bar-track"><div class="bar-fill" style="width:<?= $width ?>%"></div></div>
            <span class="bar-num"><?= sprintf(I18n::t('dashboard.platform_count_total'), number_format($count)) ?></span>
          </div>
        <?php endforeach; ?>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>

  <div class="panel">
    <p class="panel-title"><?= Helpers::e(I18n::t('dashboard.recent_redemptions_title')) ?></p>
    <?php if (empty($recent)): ?>
      <p style="color:var(--text-faint); font-size:13px;"><?= Helpers::e(I18n::t('dashboard.no_redemptions_yet')) ?></p>
    <?php else: ?>
    <table>
      <thead><tr><th><?= Helpers::e(I18n::t('dashboard.table.creator')) ?></th><th><?= Helpers::e(I18n::t('dashboard.table.platform')) ?></th><th><?= Helpers::e(I18n::t('dashboard.table.campaign')) ?></th><th><?= Helpers::e(I18n::t('dashboard.table.time')) ?></th></tr></thead>
      <tbody>
        <?php foreach ($recent as $r): ?>
        <tr>
          <td class="creator" data-label="<?= Helpers::e(I18n::t('dashboard.table.creator')) ?>"><?= Helpers::e($r['user_name'] !== null ? DemoMask::name($r['user_name']) : sprintf(I18n::t('dashboard.user_number'), (int) $r['user_id'])) ?></td>
          <td data-label="<?= Helpers::e(I18n::t('dashboard.table.platform')) ?>"><span class="plat-tag"><?= Helpers::e(Platform::label($r['platform'])) ?></span></td>
          <td data-label="<?= Helpers::e(I18n::t('dashboard.table.campaign')) ?>"><?= $r['campaign_name'] !== null ? Helpers::e($r['campaign_name']) : '<span style="color:var(--text-faint);">—</span>' ?></td>
          <td class="time-cell" data-label="<?= Helpers::e(I18n::t('dashboard.table.time')) ?>"><?= date('H:i', strtotime($r['redeemed_at'])) ?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    <?php endif; ?>
  </div>
</div>

<?php require __DIR__ . '/includes/layout_footer.php'; ?>
