<?php

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

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

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

$campaignFilter = (int) ($_GET['campaign_id'] ?? 0);
$productFilter = (int) ($_GET['product_id'] ?? 0);

$where = [];
$params = [];
if ($campaignFilter) {
    $where[] = 'cl.campaign_id = :campaign_id';
    $params['campaign_id'] = $campaignFilter;
}
if ($productFilter) {
    $where[] = 'r.product_id = :product_id';
    $params['product_id'] = $productFilter;
}
$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

$stmt = $pdo->prepare(
    "SELECT r.*, u.name AS user_name, u.id AS link_user_id, c.name AS campaign_name, p.name AS product_name,
            k.key_value, clp.max_claims, clp.claims_used
     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
     JOIN products p ON p.id = r.product_id
     JOIN `keys` k ON k.id = r.key_id
     LEFT JOIN claim_link_products clp ON clp.claim_link_id = r.claim_link_id AND clp.product_id = r.product_id
     $whereSql
     ORDER BY r.redeemed_at DESC
     LIMIT 200"
);
$stmt->execute($params);
$redemptions = $stmt->fetchAll();

// Same filters as the table above, just grouped by platform instead of
// listed per event -- "how many of each" is easier to read as one bar
// chart than by counting rows in a 200-row table.
$platformStmt = $pdo->prepare(
    "SELECT r.platform, COUNT(*) AS total
     FROM redemptions r
     JOIN claim_links cl ON cl.id = r.claim_link_id
     $whereSql
     GROUP BY r.platform
     ORDER BY total DESC"
);
$platformStmt->execute($params);
$platformTotals = $platformStmt->fetchAll();
$maxPlatformTotal = max(array_column($platformTotals, 'total') ?: [1]);

$campaigns = $pdo->query('SELECT id, name FROM campaigns ORDER BY name ASC')->fetchAll();
$products = $pdo->query('SELECT id, name FROM products ORDER BY name ASC')->fetchAll();

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

<form method="get" class="filter-row" style="display:flex; gap:10px; margin-bottom:16px; flex-wrap:wrap;">
  <select name="campaign_id" onchange="this.form.submit()" style="background:var(--bg-panel); border:1px solid var(--line); color:var(--text-primary); font-size:13px; padding:8px 12px; border-radius:8px;">
    <option value="0"><?= Helpers::e(I18n::t('redemptions.filter_all_campaigns')) ?></option>
    <?php foreach ($campaigns as $c): ?>
      <option value="<?= (int) $c['id'] ?>" <?= $campaignFilter === (int) $c['id'] ? 'selected' : '' ?>><?= Helpers::e($c['name']) ?></option>
    <?php endforeach; ?>
  </select>
  <select name="product_id" onchange="this.form.submit()" style="background:var(--bg-panel); border:1px solid var(--line); color:var(--text-primary); font-size:13px; padding:8px 12px; border-radius:8px;">
    <option value="0"><?= Helpers::e(I18n::t('redemptions.filter_all_products')) ?></option>
    <?php foreach ($products as $p): ?>
      <option value="<?= (int) $p['id'] ?>" <?= $productFilter === (int) $p['id'] ? 'selected' : '' ?>><?= Helpers::e($p['name']) ?></option>
    <?php endforeach; ?>
  </select>
</form>

<?php if (!empty($platformTotals)): ?>
<div class="panel" style="margin-bottom:16px;">
  <p class="panel-title"><?= Helpers::e(I18n::t('redemptions.by_platform_title')) ?></p>
  <div class="bar-list">
    <?php foreach ($platformTotals as $row):
        $width = $row['total'] > 0 ? max(4, round($row['total'] / $maxPlatformTotal * 100)) : 0;
    ?>
      <div class="bar-row">
        <span class="bar-plat"><?= Helpers::e(Platform::label($row['platform'])) ?></span>
        <div class="bar-track"><div class="bar-fill" style="width:<?= $width ?>%"></div></div>
        <span class="bar-num"><?= number_format($row['total']) ?></span>
      </div>
    <?php endforeach; ?>
  </div>
</div>
<?php endif; ?>

<div class="panel">
  <?php if (empty($redemptions)): ?>
    <p style="color:var(--text-faint); font-size:13px;"><?= Helpers::e(I18n::t('redemptions.empty_state')) ?></p>
  <?php else: ?>
  <?php
    $colCreator = I18n::t('redemptions.col_creator');
    $colProduct = I18n::t('redemptions.col_product');
    $colPlatform = I18n::t('redemptions.col_platform');
    $colKey = I18n::t('redemptions.col_key');
    $colClaimed = I18n::t('redemptions.col_claimed');
    $colCampaign = I18n::t('redemptions.col_campaign');
    $colDate = I18n::t('redemptions.col_date');
  ?>
  <table id="redemptions-table">
    <thead><tr><th><?= Helpers::e($colCreator) ?></th><th><?= Helpers::e($colProduct) ?></th><th><?= Helpers::e($colPlatform) ?></th><th><?= Helpers::e($colKey) ?></th><th><?= Helpers::e($colClaimed) ?></th><th><?= Helpers::e($colCampaign) ?></th><th><?= Helpers::e($colDate) ?></th></tr></thead>
    <tbody>
      <?php foreach ($redemptions as $r): ?>
      <tr>
        <td class="creator" data-label="<?= Helpers::e($colCreator) ?>"><?= Helpers::e($r['user_name'] !== null ? DemoMask::name($r['user_name']) : sprintf(I18n::t('redemptions.user_number'), (int) $r['link_user_id'])) ?></td>
        <td data-label="<?= Helpers::e($colProduct) ?>"><?= Helpers::e($r['product_name']) ?></td>
        <td data-label="<?= Helpers::e($colPlatform) ?>"><span class="plat-tag"><?= Helpers::e(Platform::label($r['platform'])) ?></span></td>
        <td class="time-cell" data-label="<?= Helpers::e($colKey) ?>" style="font-family:var(--font-mono); font-size:12px;"><?= Helpers::e(DemoMask::keyCode($r['key_value'])) ?></td>
        <td class="time-cell" data-label="<?= Helpers::e($colClaimed) ?>"><?= $r['max_claims'] !== null ? ((int) $r['claims_used'] . ' / ' . (int) $r['max_claims']) : '<span style="color:var(--text-faint);">—</span>' ?></td>
        <td data-label="<?= Helpers::e($colCampaign) ?>"><?= $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($colDate) ?>"><?= date('M j, H:i', strtotime($r['redeemed_at'])) ?></td>
      </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
  <div id="redemptions-pagination" style="display:flex; justify-content:center; align-items:center; gap:14px; flex-wrap:wrap; margin-top:16px;">
    <button type="button" class="btn btn-ghost" id="redemptions-prev-btn" onclick="kvRedemptionsChangePage(-1);" style="padding:7px 14px; font-size:12.5px;"><?= Helpers::e(I18n::t('redemptions.prev_button')) ?></button>
    <span id="redemptions-page-info" style="color:var(--text-muted); font-size:13px; white-space:nowrap;"></span>
    <button type="button" class="btn btn-ghost" id="redemptions-next-btn" onclick="kvRedemptionsChangePage(1);" style="padding:7px 14px; font-size:12.5px;"><?= Helpers::e(I18n::t('redemptions.next_button')) ?></button>
    <select id="redemptions-page-size" onchange="kvRedemptionsChangePageSize();" style="background:var(--bg-panel); border:1px solid var(--line); color:var(--text-primary); font-size:12.5px; padding:7px 12px; border-radius:8px;">
      <option value="10"><?= Helpers::e(sprintf(I18n::t('redemptions.page_size_option'), 10)) ?></option>
      <option value="20"><?= Helpers::e(sprintf(I18n::t('redemptions.page_size_option'), 20)) ?></option>
      <option value="50" selected><?= Helpers::e(sprintf(I18n::t('redemptions.page_size_option'), 50)) ?></option>
      <option value="100"><?= Helpers::e(sprintf(I18n::t('redemptions.page_size_option'), 100)) ?></option>
      <option value="200"><?= Helpers::e(sprintf(I18n::t('redemptions.page_size_option'), 200)) ?></option>
      <option value="all"><?= Helpers::e(I18n::t('redemptions.page_size_all')) ?></option>
    </select>
  </div>
  <?php if (count($redemptions) > 20): ?>
  <?php // Same fixed jump-to-first/last-row buttons as Keys/Codes, Users
  // and Claim Links -- the only fast way back to either end once "Show
  // all" is selected on a long list. ?>
  <div style="position:fixed; right:20px; bottom:20px; display:flex; flex-direction:column; gap:8px; z-index:50;">
    <button type="button" class="btn btn-ghost" onclick="kvScrollToRow('first');" title="<?= Helpers::e(I18n::t('redemptions.jump_first')) ?>" style="width:40px; height:40px; padding:0; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:16px; background:var(--bg-panel); box-shadow:0 2px 8px rgba(0,0,0,0.3);">↑</button>
    <button type="button" class="btn btn-ghost" onclick="kvScrollToRow('last');" title="<?= Helpers::e(I18n::t('redemptions.jump_last')) ?>" style="width:40px; height:40px; padding:0; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:16px; background:var(--bg-panel); box-shadow:0 2px 8px rgba(0,0,0,0.3);">↓</button>
  </div>
  <?php endif; ?>
  <?php endif; ?>
</div>

<?php if (!empty($redemptions)): ?>
<script>
function kvScrollToRow(which) {
  const rows = [...document.querySelectorAll('#redemptions-table tbody tr')].filter(tr => tr.style.display !== 'none');
  if (rows.length === 0) return;
  const target = which === 'first' ? rows[0] : rows[rows.length - 1];
  target.scrollIntoView({ behavior: 'smooth', block: 'center' });
}

let kvRedemptionsPage = 1;
let kvRedemptionsPageSize = 50;
const kvRedemptionsPageInfoTemplate = <?= json_encode(I18n::t('redemptions.page_info_template'), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;

function kvRenderRedemptionsPage() {
  const rows = [...document.querySelectorAll('#redemptions-table tbody tr')];
  const total = rows.length;
  const pageSize = kvRedemptionsPageSize === 'all' ? Math.max(total, 1) : kvRedemptionsPageSize;
  const totalPages = Math.max(1, Math.ceil(total / pageSize));
  if (kvRedemptionsPage > totalPages) kvRedemptionsPage = totalPages;
  const start = (kvRedemptionsPage - 1) * pageSize;
  const end = kvRedemptionsPageSize === 'all' ? total : start + pageSize;
  const shown = new Set(rows.slice(start, end));
  rows.forEach(tr => { tr.style.display = shown.has(tr) ? '' : 'none'; });

  document.getElementById('redemptions-page-info').textContent = kvRedemptionsPageInfoTemplate.replace('{page}', kvRedemptionsPage).replace('{total}', totalPages);
  document.getElementById('redemptions-prev-btn').disabled = kvRedemptionsPage <= 1;
  document.getElementById('redemptions-next-btn').disabled = kvRedemptionsPage >= totalPages;
}

function kvRedemptionsChangePage(delta) {
  kvRedemptionsPage += delta;
  kvRenderRedemptionsPage();
}

function kvRedemptionsChangePageSize() {
  const val = document.getElementById('redemptions-page-size').value;
  kvRedemptionsPageSize = val === 'all' ? 'all' : parseInt(val, 10);
  kvRedemptionsPage = 1;
  kvRenderRedemptionsPage();
}

kvRenderRedemptionsPage();
</script>
<?php endif; ?>

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