<?php

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

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

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

// Only products/platforms/campaigns that actually have at least one key,
// so the dropdowns don't list options that would always export nothing.
$exportProducts = $pdo->query(
    'SELECT DISTINCT p.id, p.name FROM `keys` k JOIN products p ON p.id = k.product_id ORDER BY p.name ASC'
)->fetchAll();
$exportPlatforms = $pdo->query('SELECT DISTINCT platform FROM `keys` ORDER BY platform ASC')->fetchAll(PDO::FETCH_COLUMN);
$exportCampaigns = $pdo->query(
    'SELECT DISTINCT c.id, c.name FROM `keys` k JOIN campaigns c ON c.id = k.campaign_id ORDER BY c.name ASC'
)->fetchAll();

// Optional preselection when arriving from a specific product/platform's
// key pool page, so that link doesn't dump you back into an unfiltered form.
$presetProductId = (int) ($_GET['product_id'] ?? 0);
$presetPlatform = $_GET['platform'] ?? '';

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

<div id="export-flash"></div>

<form method="post" action="keys_export.php" onsubmit="return kvExportKeys(this);">
  <?= Csrf::field() ?>
  <div class="form-section">
    <p class="form-section-title"><?= Helpers::e(I18n::t('keys_export_form.filters_title')) ?></p>
    <p class="form-section-hint"><?= Helpers::e(I18n::t('keys_export_form.filters_hint')) ?></p>
    <div class="field-row">
      <div class="field">
        <label><?= Helpers::e(I18n::t('keys_export_form.field_product')) ?></label>
        <select name="product_id">
          <option value="0"><?= Helpers::e(I18n::t('keys_export_form.all_products')) ?></option>
          <?php foreach ($exportProducts as $p): ?>
            <option value="<?= (int) $p['id'] ?>" <?= $presetProductId === (int) $p['id'] ? 'selected' : '' ?>><?= Helpers::e($p['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="field">
        <label><?= Helpers::e(I18n::t('keys_export_form.field_platform')) ?></label>
        <select name="platform">
          <option value=""><?= Helpers::e(I18n::t('keys_export_form.all_platforms')) ?></option>
          <?php foreach ($exportPlatforms as $slug): ?>
            <option value="<?= Helpers::e($slug) ?>" <?= $presetPlatform === $slug ? 'selected' : '' ?>><?= Helpers::e(Platform::label($slug)) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
    </div>
    <div class="field-row">
      <div class="field">
        <label><?= Helpers::e(I18n::t('keys_export_form.field_campaign')) ?></label>
        <select name="campaign_id">
          <option value="0"><?= Helpers::e(I18n::t('keys_export_form.all_campaigns')) ?></option>
          <?php foreach ($exportCampaigns as $c): ?>
            <option value="<?= (int) $c['id'] ?>"><?= Helpers::e($c['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="field">
        <label><?= Helpers::e(I18n::t('keys_export_form.field_status')) ?></label>
        <select name="status">
          <option value="available"><?= Helpers::e(I18n::t('keys_export_form.status_unused_only')) ?></option>
          <option value="all"><?= Helpers::e(I18n::t('keys_export_form.status_all_keys')) ?></option>
        </select>
      </div>
    </div>
    <div class="field">
      <label><?= Helpers::e(I18n::t('keys_export_form.field_limit')) ?></label>
      <input type="number" name="limit" min="1" placeholder="<?= Helpers::e(I18n::t('keys_export_form.limit_placeholder')) ?>">
    </div>
  </div>

  <div class="form-actions">
    <a href="keys.php" class="btn btn-ghost" style="text-decoration:none;"><?= Helpers::e(I18n::t('keys_export_form.back_to_keys')) ?></a>
    <button type="submit" class="btn btn-primary"><?= Helpers::e(I18n::t('keys_export_form.export_csv_button')) ?></button>
  </div>
</form>

<script>
  // Same mechanism as keys.php's/keys_pool.php's own export -- the
  // response is both a file download and a mutation (keys_export.php
  // marks the exported keys 'exported'), so fetch() triggers the
  // download and reads back a one-line summary via a response header,
  // shown right here instead of a normal navigation losing it.
  async function kvDoExport(url, formData) {
    const res = await fetch(url, { method: 'POST', body: formData });
    const el = document.getElementById('export-flash');
    if (!res.ok) {
      el.innerHTML = '<div class="panel flash-panel" style="border-color:var(--danger);"><span style="color:var(--danger); font-size:13px;">' + <?= json_encode(I18n::t('keys_export_form.js.export_failed'), JSON_HEX_APOS | JSON_HEX_QUOT) ?> + ' (' + res.status + ').</span></div>';
      return;
    }
    const rawSummary = res.headers.get('X-Export-Summary');
    const summary = rawSummary ? decodeURIComponent(rawSummary) : <?= json_encode(I18n::t('keys_export_form.js.export_complete'), JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
    const blob = await res.blob();
    const disposition = res.headers.get('Content-Disposition') || '';
    const match = disposition.match(/filename="([^"]+)"/);
    const filename = match ? match[1] : 'keys-export.csv';
    const blobUrl = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = blobUrl;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    a.remove();
    URL.revokeObjectURL(blobUrl);
    el.innerHTML = '<div class="panel flash-panel" style="border-color:var(--signal-dim);"><span style="color:var(--signal); font-size:13px;"></span></div>';
    el.querySelector('span').textContent = summary;
  }

  function kvExportKeys(form) {
    kvDoExport(form.action, new FormData(form));
    return false;
  }
</script>

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