<?php

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

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

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

$campaigns = $pdo->query('SELECT id, name FROM campaigns WHERE status = "active" ORDER BY name ASC')->fetchAll();
$products = $pdo->query('SELECT id, name FROM products ORDER BY 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 empty form.
$presetProductId = (int) ($_GET['product_id'] ?? 0);
$presetPlatform = $_GET['platform'] ?? '';

$result = null;
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::requireValid();

    $campaignId = !empty($_POST['campaign_id']) ? (int) $_POST['campaign_id'] : null;
    $productId = (int) ($_POST['product_id'] ?? 0);
    $platform = $_POST['platform'] ?? '';
    $pool = ($_POST['pool'] ?? '') === 'active' ? 'active' : 'inactive';
    $pastedKeys = $_POST['keys_text'] ?? '';

    if (!$productId) {
        $errors[] = I18n::t('keys_import.error_select_product');
    }
    if (!Platform::exists($platform)) {
        $errors[] = I18n::t('keys_import.error_select_platform');
    }

    $fileError = $_FILES['keys_file']['error'] ?? UPLOAD_ERR_NO_FILE;

    $lines = [];
    if ($fileError === UPLOAD_ERR_OK) {
        $content = file_get_contents($_FILES['keys_file']['tmp_name']);
        $lines = preg_split('/\r\n|\r|\n/', $content);
    } elseif ($fileError !== UPLOAD_ERR_NO_FILE) {
        $errors[] = in_array($fileError, [UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE], true)
            ? I18n::t('keys_import.error_file_too_large')
            : I18n::t('keys_import.error_file_upload_generic');
    } elseif (trim($pastedKeys) !== '') {
        $lines = preg_split('/\r\n|\r|\n/', $pastedKeys);
    } else {
        $errors[] = I18n::t('keys_import.error_no_keys_provided');
    }

    if (empty($errors)) {
        $result = KeyImporter::import($productId, $campaignId, $platform, $lines, $pool);
        AuditLog::log(
            $admin['id'],
            'keys_imported',
            "product={$productId} platform={$platform} imported={$result['imported']} duplicates={$result['skipped_duplicate']}"
        );
    }
}

$pageTitle = I18n::t('keys_import.page_title');
$activeNav = 'keys';
$extraAdminCss = 'admin-product-editor';
require __DIR__ . '/includes/layout_header.php';

// Built here (not inline below) since the third clause is conditional and
// the sentence needs to stay in one piece per language for correct grammar.
if ($result) {
    $resultSummary = sprintf(I18n::t('keys_import.result_summary_base'), $result['skipped_duplicate'], $result['skipped_blank']);
    if ($result['skipped_invalid_format'] > 0) {
        $resultSummary .= sprintf(I18n::t('keys_import.result_summary_invalid_format_suffix'), $result['skipped_invalid_format']);
    }
    $resultSummary .= '.';

    $platformsLink = '<a href="platforms.php" style="color:var(--signal);">' . Helpers::e(I18n::t('nav.platforms')) . '</a>';
    $invalidFormatHint = sprintf(I18n::t('keys_import.invalid_format_hint'), $platformsLink);
}
?>
<div class="topbar"><h1><?= Helpers::e(I18n::t('keys_import.heading')) ?></h1></div>

<?php if (!empty($errors)): ?>
  <div class="form-section" style="border-color:var(--danger); margin-bottom:16px;">
    <?php foreach ($errors as $err): ?><p style="color:var(--danger); font-size:13px; margin:0;"><?= Helpers::e($err) ?></p><?php endforeach; ?>
  </div>
<?php endif; ?>

<?php if ($result): ?>
  <div class="form-section" style="border-color:var(--signal-dim); margin-bottom:16px;">
    <p style="color:var(--signal); font-size:14px; font-weight:600; margin:0 0 6px;"><?= Helpers::e(sprintf(I18n::t('keys_import.result_imported'), $result['imported'])) ?></p>
    <p style="color:var(--text-muted); font-size:12.5px; margin:0;">
      <?= Helpers::e($resultSummary) ?>
    </p>
    <?php if (!empty($result['duplicate_values'])): ?>
    <details style="margin-top:8px;">
      <summary style="color:var(--text-muted); font-size:12.5px; cursor:pointer;"><?= Helpers::e(I18n::t('keys_import.show_duplicate_keys')) ?></summary>
      <div style="margin-top:6px; max-height:180px; overflow-y:auto; background:var(--bg-void); border:1px solid var(--line); border-radius:8px; padding:8px 12px; font-family:var(--font-mono); font-size:12px; color:var(--text-muted);">
        <?php foreach ($result['duplicate_values'] as $dup): ?>
          <div><?= Helpers::e($dup) ?></div>
        <?php endforeach; ?>
      </div>
    </details>
    <?php endif; ?>
    <?php if (!empty($result['invalid_format_values'])): ?>
    <details style="margin-top:8px;">
      <summary style="color:var(--text-muted); font-size:12.5px; cursor:pointer;"><?= Helpers::e(I18n::t('keys_import.show_invalid_format_keys')) ?></summary>
      <div style="margin-top:6px; max-height:180px; overflow-y:auto; background:var(--bg-void); border:1px solid var(--line); border-radius:8px; padding:8px 12px; font-family:var(--font-mono); font-size:12px; color:var(--text-muted);">
        <?php foreach ($result['invalid_format_values'] as $inv): ?>
          <div><?= Helpers::e($inv) ?></div>
        <?php endforeach; ?>
      </div>
      <p style="color:var(--text-faint); font-size:11.5px; margin:6px 0 0;"><?= $invalidFormatHint ?></p>
    </details>
    <?php endif; ?>
  </div>
<?php endif; ?>

<?php if (empty($products)): ?>
  <div class="panel">
    <p style="color:var(--text-muted); font-size:13px;">
      <?= Helpers::e(I18n::t('keys_import.need_product_hint')) ?>
      <a href="product_form.php" style="color:var(--signal);"><?= Helpers::e(I18n::t('keys_import.create_product_link')) ?></a>
    </p>
  </div>
<?php else: ?>
<form method="post" enctype="multipart/form-data">
  <?= Csrf::field() ?>
  <div class="form-section">
    <p class="form-section-title"><?= Helpers::e(I18n::t('keys_import.destination_title')) ?></p>
    <div class="field-row">
      <div class="field">
        <label><?= Helpers::e(I18n::t('keys_import.field_campaign_optional')) ?></label>
        <select name="campaign_id">
          <option value=""><?= Helpers::e(I18n::t('keys_import.no_campaign')) ?></option>
          <?php foreach ($campaigns 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_import.field_product')) ?></label>
        <select name="product_id" required>
          <option value=""><?= Helpers::e(I18n::t('keys_import.select_product_option')) ?></option>
          <?php foreach ($products as $p): ?>
            <option value="<?= (int) $p['id'] ?>" <?= $presetProductId === (int) $p['id'] ? 'selected' : '' ?>><?= Helpers::e($p['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
    </div>
    <div class="field-row">
      <div class="field">
        <label><?= Helpers::e(I18n::t('keys_import.field_platform')) ?></label>
        <select name="platform" required onchange="
          var pattern = this.options[this.selectedIndex].dataset.format;
          document.getElementById('platform-format-hint').textContent = pattern ? <?= json_encode(I18n::t('keys_import.format_hint_prefix'), JSON_HEX_APOS | JSON_HEX_QUOT) ?> + pattern : '';
        ">
          <option value=""><?= Helpers::e(I18n::t('keys_import.select_platform_option')) ?></option>
          <?php foreach (Platform::all() as $p): ?>
            <option value="<?= Helpers::e($p['slug']) ?>" data-format="<?= Helpers::e($p['key_format_pattern'] ?? '') ?>" <?= $presetPlatform === $p['slug'] ? 'selected' : '' ?>><?= Helpers::e($p['label']) ?></option>
          <?php endforeach; ?>
        </select>
        <p id="platform-format-hint" style="color:var(--text-faint); font-size:11.5px; margin:6px 0 0; font-family:var(--font-mono);"></p>
      </div>
      <div class="field">
        <label><?= Helpers::e(I18n::t('keys_import.field_release')) ?></label>
        <select name="pool">
          <option value="inactive" selected><?= Helpers::e(I18n::t('keys_import.release_held_back')) ?></option>
          <option value="active"><?= Helpers::e(I18n::t('keys_import.release_released')) ?></option>
        </select>
      </div>
    </div>
  </div>

  <div class="form-section">
    <p class="form-section-title"><?= Helpers::e(I18n::t('keys_import.keys_section_title')) ?></p>
    <p class="form-section-hint"><?= Helpers::e(I18n::t('keys_import.keys_section_hint')) ?></p>
    <div class="field">
      <label><?= Helpers::e(I18n::t('keys_import.field_paste_keys')) ?></label>
      <textarea name="keys_text" rows="8" style="width:100%; background:var(--bg-void); border:1px solid var(--line); color:var(--text-primary); font-family:var(--font-mono); font-size:12.5px; padding:10px 12px; border-radius:8px;" placeholder="STEAM-AAAA-BBBB-CCCC&#10;STEAM-DDDD-EEEE-FFFF"></textarea>
    </div>
    <div class="field">
      <label><?= Helpers::e(I18n::t('keys_import.field_upload_file')) ?></label>
      <label class="btn btn-ghost file-choose-label" style="cursor:pointer; display:inline-flex; align-items:center; gap:8px;">
        <span><?= Helpers::e(I18n::t('keys_import.choose_file_button')) ?></span>
        <span id="keys-file-name" style="color:var(--text-faint); font-weight:400;"><?= Helpers::e(I18n::t('keys_import.no_file_chosen')) ?></span>
        <input type="file" name="keys_file" accept=".csv,.txt,text/csv,text/plain" style="display:none;" onchange="document.getElementById('keys-file-name').textContent = this.files[0]?.name || <?= json_encode(I18n::t('keys_import.no_file_chosen'), JSON_HEX_APOS | JSON_HEX_QUOT) ?>;">
      </label>
    </div>
  </div>

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

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