<?php
$gameCatalog = is_array($game_catalog ?? null) ? $game_catalog : [];
$defaultGameCode = (string)($default_game_code ?? array_key_first($gameCatalog));
$gameCatalogJson = app_json_for_html($gameCatalog);
?>

<div class="row">
  <div class="col-md-8">
    <div class="card">
      <div class="card-header"><h4><?= e(app_zh('生成卡密')) ?></h4></div>
      <div class="card-body">
        <?php if (!$gameCatalog): ?>
          <div class="alert alert-info"><?= e(app_zh('当前没有可用游戏配置，暂时无法生成卡密。')) ?></div>
        <?php else: ?>
          <form method="post" action="<?= e_url(base_url('keys/generate')) ?>">
            <?= csrf_field() ?>

            <div class="form-group">
              <label><?= e(app_zh('游戏/项目')) ?></label>
              <select class="form-control" name="game" id="game-select">
                <?php foreach ($gameCatalog as $code => $game): ?>
                  <option value="<?= e((string)$code) ?>" <?= (string)$code === $defaultGameCode ? 'selected' : '' ?>>
                    <?= e((string)($game['name'] ?? $code)) ?> (<?= e((string)$code) ?>)
                  </option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="form-group">
              <label><?= e(app_zh('时长（小时）')) ?></label>
              <select class="form-control" name="duration" id="duration"></select>
            </div>

            <div class="form-group">
              <label><?= e(app_zh('设备上限')) ?></label>
              <input class="form-control" name="max_devices" id="max_devices" value="1">
            </div>

            <div class="form-group">
              <label><?= e(app_zh('生成数量')) ?></label>
              <input class="form-control" name="quantity" id="quantity" value="1">
            </div>

            <div class="form-group">
              <label><?= e(app_zh('批次号（可选）')) ?></label>
              <input class="form-control" name="batch_code" placeholder="<?= e(app_zh('不填则不创建批次，例如：SPRING_20260404')) ?>">
            </div>

            <div class="form-group">
              <label><?= e(app_zh('批次名称（可选）')) ?></label>
              <input class="form-control" name="batch_name" placeholder="<?= e(app_zh('例如：首发批次 / 活动批次')) ?>">
              <small class="help-block"><?= e(app_zh('只有填写了批次号时，批次名称才会一起生效')) ?></small>
            </div>

            <div class="form-group">
              <label><?= e(app_zh('预估扣费')) ?></label>
              <input class="form-control" id="estimate" value="0.00" readonly>
            </div>

            <div class="form-group">
              <label><?= e(app_zh('自定义前缀（可选）')) ?></label>
              <input class="form-control" name="prefix" placeholder="VIP_">
            </div>

            <div class="form-group">
              <label><?= e(app_zh('自定义完整卡密（可选）')) ?></label>
              <input class="form-control" name="custom_key" placeholder="<?= e(app_zh('仅支持 6-64 位字母、数字、下划线或中划线')) ?>">
            </div>

            <button class="btn btn-primary" type="submit"><?= e(app_zh('立即生成')) ?></button>
          </form>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<script>
(function () {
  var gameCatalog = <?= $gameCatalogJson ?: '{}' ?>;
  var gameSelect = document.getElementById('game-select');
  var durationSelect = document.getElementById('duration');
  var maxDevicesInput = document.getElementById('max_devices');
  var quantityInput = document.getElementById('quantity');
  var estimateInput = document.getElementById('estimate');

  function num(v) {
    var n = parseFloat(v);
    return isNaN(n) ? 0 : n;
  }

  function refreshDurationOptions() {
    if (!gameSelect || !durationSelect) {
      return;
    }

    var code = gameSelect.value;
    var game = gameCatalog[code] || {};
    var prices = game.prices || {};
    var keys = Object.keys(prices).sort(function (a, b) {
      return parseInt(a, 10) - parseInt(b, 10);
    });

    durationSelect.innerHTML = '';
    if (!keys.length) {
      var emptyOpt = document.createElement('option');
      emptyOpt.value = '';
      emptyOpt.textContent = '未配置时长';
      durationSelect.appendChild(emptyOpt);
      refreshEstimate();
      return;
    }

    var selectedHours = keys.indexOf('24') !== -1 ? '24' : keys[0];
    keys.forEach(function (hours) {
      var opt = document.createElement('option');
      opt.value = hours;
      opt.setAttribute('data-price', prices[hours]);
      opt.textContent = hours + ' 小时';
      if (hours === selectedHours) {
        opt.selected = true;
      }
      durationSelect.appendChild(opt);
    });
    refreshEstimate();
  }

  function refreshEstimate() {
    if (!durationSelect || !estimateInput) {
      return;
    }
    var selected = durationSelect.options[durationSelect.selectedIndex];
    var price = selected ? num(selected.getAttribute('data-price')) : 0;
    var maxDevices = Math.max(1, parseInt(maxDevicesInput && maxDevicesInput.value || '1', 10) || 1);
    var quantity = Math.max(1, parseInt(quantityInput && quantityInput.value || '1', 10) || 1);
    estimateInput.value = (price * maxDevices * quantity).toFixed(2);
  }

  if (gameSelect) {
    gameSelect.addEventListener('change', refreshDurationOptions);
  }
  if (durationSelect) {
    durationSelect.addEventListener('change', refreshEstimate);
  }
  if (maxDevicesInput) {
    maxDevicesInput.addEventListener('input', refreshEstimate);
  }
  if (quantityInput) {
    quantityInput.addEventListener('input', refreshEstimate);
  }

  refreshDurationOptions();
})();
</script>
