<?php
$lastKeys = flash('generated_keys');
$filters = is_array($filters ?? null) ? $filters : [];
$gameCatalog = is_array($game_catalog ?? null) ? $game_catalog : [];
$batchSummaries = is_array($batch_summaries ?? null) ? $batch_summaries : [];
$generatedBatch = is_array($generated_batch ?? null) ? $generated_batch : [];
$exportAllUrl = (string)($export_all_url ?? base_url('keys/export-all'));
$keys = is_array($keys ?? null) ? $keys : [];
$canManageKeys = !empty($can_manage_keys);
?>

<div class="row">
  <div class="col-md-12">
    <?php if (!empty($lastKeys) && is_array($lastKeys)): ?>
      <div class="alert alert-info">
        <strong><?= e(app_zh('本次生成的卡密：')) ?></strong>
        <?php if (!empty($generatedBatch['code'])): ?>
          <div style="margin:8px 0 10px;">
            <span class="label label-primary"><?= e(app_zh('批次号：')) ?><?= e((string)$generatedBatch['code']) ?></span>
            <?php if (!empty($generatedBatch['name'])): ?>
              <span class="label label-default"><?= e(app_zh('批次名：')) ?><?= e((string)$generatedBatch['name']) ?></span>
            <?php endif; ?>
            <?php if (!empty($generatedBatch['game_name'])): ?>
              <span class="label label-success"><?= e(app_zh('游戏：')) ?><?= e((string)$generatedBatch['game_name']) ?></span>
            <?php endif; ?>
          </div>
        <?php endif; ?>
        <textarea class="form-control" rows="5" readonly id="last-keys"><?= e(implode("\n", $lastKeys)) ?></textarea>
        <div style="margin-top:10px;">
          <button class="btn btn-xs btn-default" type="button" id="copy-last-keys"><?= e(app_zh('一键复制')) ?></button>
          <a class="btn btn-xs btn-success" href="<?= e_url(base_url('keys/download-last')) ?>"><?= e(app_zh('下载本次卡密')) ?></a>
          <?php if (!empty($generatedBatch['code'])): ?>
            <a class="btn btn-xs btn-primary" href="<?= e_url(app_url_with_query(base_url('keys/export-all'), ['batch' => $generatedBatch['code']])) ?>"><?= e(app_zh('导出本批次')) ?></a>
          <?php endif; ?>
        </div>
      </div>
    <?php endif; ?>

    <div class="card">
      <div class="card-header"><h4><?= e(app_zh('筛选与批次')) ?></h4></div>
      <div class="card-body">
        <form method="get" action="<?= e_url(base_url('keys')) ?>">
          <div class="row">
            <div class="col-md-3">
              <div class="form-group">
                <label><?= e(app_zh('游戏/项目')) ?></label>
                <select class="form-control" name="game">
                  <option value=""><?= e(app_zh('全部游戏')) ?></option>
                  <?php foreach ($gameCatalog as $code => $game): ?>
                    <option value="<?= e((string)$code) ?>" <?= (($filters['game'] ?? '') === (string)$code) ? 'selected' : '' ?>>
                      <?= e((string)($game['name'] ?? $code)) ?>
                    </option>
                  <?php endforeach; ?>
                </select>
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label><?= e(app_zh('批次筛选')) ?></label>
                <input class="form-control" name="batch" value="<?= e((string)($filters['batch'] ?? '')) ?>" placeholder="<?= e(app_zh('批次号或批次名称')) ?>">
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label><?= e(app_zh('关键字')) ?></label>
                <input class="form-control" name="keyword" value="<?= e((string)($filters['keyword'] ?? '')) ?>" placeholder="<?= e(app_zh('卡密 / 批次关键字')) ?>">
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label><?= e(app_zh('状态')) ?></label>
                <select class="form-control" name="status">
                  <option value=""><?= e(app_zh('全部状态')) ?></option>
                  <option value="active" <?= (($filters['status'] ?? '') === 'active') ? 'selected' : '' ?>><?= e(app_zh('正常')) ?></option>
                  <option value="inactive" <?= (($filters['status'] ?? '') === 'inactive') ? 'selected' : '' ?>><?= e(app_zh('禁用')) ?></option>
                </select>
              </div>
            </div>
          </div>

          <div style="display:flex;gap:10px;flex-wrap:wrap;">
            <button class="btn btn-primary" type="submit"><?= e(app_zh('应用筛选')) ?></button>
            <a class="btn btn-default" href="<?= e_url(base_url('keys')) ?>"><?= e(app_zh('重置')) ?></a>
            <a class="btn btn-success" href="<?= e_url($exportAllUrl) ?>"><?= e(app_zh('导出当前结果')) ?></a>
          </div>
        </form>

        <?php if (!empty($batchSummaries)): ?>
          <hr>
          <div class="table-responsive">
            <table class="table table-bordered table-hover">
              <thead>
                <tr>
                  <th><?= e(app_zh('批次号')) ?></th>
                  <th><?= e(app_zh('批次名')) ?></th>
                  <th><?= e(app_zh('游戏')) ?></th>
                  <th><?= e(app_zh('卡密数量')) ?></th>
                  <th><?= e(app_zh('最近生成时间')) ?></th>
                  <th><?= e(app_zh('操作')) ?></th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($batchSummaries as $batch): ?>
                  <?php $batchGameCode = (string)($batch['game'] ?? ''); ?>
                  <tr>
                    <td><?= e((string)($batch['batch_code'] ?? '')) ?></td>
                    <td><?= !empty($batch['batch_name']) ? e((string)$batch['batch_name']) : '-' ?></td>
                    <td><?= e((string)($gameCatalog[$batchGameCode]['name'] ?? $batchGameCode)) ?></td>
                    <td><?= e((string)($batch['keys_total'] ?? 0)) ?></td>
                    <td><?= e((string)($batch['last_created_at'] ?? '')) ?></td>
                    <td>
                      <a class="btn btn-xs btn-info" href="<?= e_url(app_url_with_query(base_url('keys'), ['batch' => (string)($batch['batch_code'] ?? '')])) ?>"><?= e(app_zh('查看本批次')) ?></a>
                      <a class="btn btn-xs btn-success" href="<?= e_url(app_url_with_query(base_url('keys/export-all'), ['batch' => (string)($batch['batch_code'] ?? '')])) ?>"><?= e(app_zh('导出本批次')) ?></a>
                    </td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <div class="card">
      <div class="card-header"><h4><?= e(app_zh('卡密明细')) ?></h4></div>
      <div class="card-body">
        <form method="post" id="keys-bulk-form">
          <?= csrf_field() ?>
          <input type="hidden" name="batch_action" id="keys-batch-action" value="">

          <?php if ($canManageKeys): ?>
            <div style="display:flex;gap:10px;flex-wrap:wrap;align-items:flex-end;margin-bottom:12px;">
              <button class="btn btn-danger" type="submit" formaction="<?= e_url(base_url('keys/delete-batch')) ?>" onclick="return keysSubmitBatch('delete');"><?= e(app_zh('删除已选')) ?></button>
              <button class="btn btn-warning" type="submit" formaction="<?= e_url(base_url('keys/batch-update')) ?>" onclick="return keysSubmitBatch('reset_devices');"><?= e(app_zh('清空已选设备')) ?></button>
              <button class="btn btn-danger" type="submit" formaction="<?= e_url(base_url('keys/batch-update')) ?>" onclick="return keysSubmitBatch('status_inactive');"><?= e(app_zh('封禁已选')) ?></button>
              <button class="btn btn-success" type="submit" formaction="<?= e_url(base_url('keys/batch-update')) ?>" onclick="return keysSubmitBatch('status_active');"><?= e(app_zh('解封已选')) ?></button>
              <div style="display:flex;gap:8px;align-items:flex-end;flex-wrap:wrap;">
                <div>
                  <label for="batch-extend-hours" style="display:block;margin:0 0 4px;"><?= e(app_zh('批量加时（小时）')) ?></label>
                  <input class="form-control" style="width:140px;" type="number" min="1" max="8760" step="1" id="batch-extend-hours" name="batch_extend_hours" value="24" placeholder="<?= e(app_zh('例如 24')) ?>">
                </div>
                <button class="btn btn-primary" type="submit" formaction="<?= e_url(base_url('keys/batch-update')) ?>" onclick="return keysSubmitBatch('extend_hours');"><?= e(app_zh('为已选加时')) ?></button>
              </div>
              <span class="text-muted" id="keys-selected-count"><?= e(app_zh('已选 0 项')) ?></span>
            </div>
          <?php else: ?>
            <div style="margin-bottom:12px;color:#64748b;">
              <?= e(app_zh('代理可查看、复制和导出卡密，但不可对卡密进行修改、封禁、删除、加时或清理设备操作')) ?>
            </div>
          <?php endif; ?>

          <div class="table-responsive">
            <table class="table table-bordered table-hover">
              <thead>
                <tr>
                  <?php if ($canManageKeys): ?>
                    <th style="width:46px;">
                      <label style="margin:0;">
                        <input type="checkbox" id="keys-check-all">
                      </label>
                    </th>
                  <?php endif; ?>
                  <th>ID</th>
                  <th><?= e(app_zh('游戏')) ?></th>
                  <th><?= e(app_zh('卡密')) ?></th>
                  <th><?= e(app_zh('生成者')) ?></th>
                  <th><?= e(app_zh('生成时间')) ?></th>
                  <th><?= e(app_zh('状态')) ?></th>
                  <th><?= e(app_zh('激活状态')) ?></th>
                  <th><?= e(app_zh('设备')) ?></th>
                  <th><?= e(app_zh('到期时间')) ?></th>
                  <th><?= e(app_zh('操作')) ?></th>
                </tr>
              </thead>
              <tbody>
                <?php if (empty($keys)): ?>
                  <tr>
                    <td colspan="<?= $canManageKeys ? '11' : '10' ?>"><?= e(app_zh('暂无卡密记录')) ?></td>
                  </tr>
                <?php else: ?>
                  <?php foreach ($keys as $row): ?>
                    <?php
                    $gameCode = (string)($row['game'] ?? '');
                    $gameName = (string)($gameCatalog[$gameCode]['name'] ?? $gameCode);
                    $devices = array_values(array_filter(array_map('trim', explode(',', (string)($row['devices'] ?? '')))));
                    $activated = !empty($row['activated_at']) || !empty($row['expired_at']);
                    $status = (string)($row['status'] ?? '');
                    $rowId = (int)($row['id'] ?? 0);
                    ?>
                    <tr>
                      <?php if ($canManageKeys): ?>
                        <td>
                          <input type="checkbox" class="key-row-check" name="ids[]" value="<?= e((string)$rowId) ?>">
                        </td>
                      <?php endif; ?>
                      <td><?= e((string)$rowId) ?></td>
                      <td><?= e($gameName) ?></td>
                      <td><code><?= e((string)($row['user_key'] ?? '')) ?></code></td>
                      <td><?= e((string)($row['registrator_name'] ?? '-')) ?></td>
                      <td><?= e((string)($row['created_at'] ?? '')) ?></td>
                      <td>
                        <?php if ($status === 'active'): ?>
                          <span class="badge-status badge-ok"><?= e(app_zh('正常')) ?></span>
                        <?php else: ?>
                          <span class="badge-status badge-danger"><?= e(app_zh('已封禁')) ?></span>
                        <?php endif; ?>
                      </td>
                      <td>
                        <?php if ($activated): ?>
                          <span class="badge-status badge-ok"><?= e(app_zh('已激活')) ?></span>
                        <?php else: ?>
                          <span class="badge-status badge-danger"><?= e(app_zh('未激活')) ?></span>
                        <?php endif; ?>
                      </td>
                      <td>
                        <div><?= e((string)count($devices)) ?> / <?= e((string)($row['max_devices'] ?? 0)) ?></div>
                        <?php if (!empty($devices)): ?>
                          <div style="margin-top:6px;max-width:260px;">
                            <?php foreach ($devices as $device): ?>
                              <div><code style="white-space:normal;word-break:break-all;"><?= e((string)$device) ?></code></div>
                            <?php endforeach; ?>
                          </div>
                        <?php else: ?>
                          <div class="text-muted" style="margin-top:6px;"><?= e(app_zh('暂无设备记录')) ?></div>
                        <?php endif; ?>
                      </td>
                      <td><?= !empty($row['expired_at']) ? e((string)$row['expired_at']) : '-' ?></td>
                      <td style="white-space:nowrap;">
                        <button class="btn btn-xs btn-default key-copy-btn" type="button" data-key="<?= e((string)($row['user_key'] ?? '')) ?>"><?= e(app_zh('复制')) ?></button>
                        <?php if ($canManageKeys): ?>
                          <a class="btn btn-xs btn-info" href="<?= e_url(base_url('keys/edit/' . $rowId)) ?>"><?= e(app_zh('编辑')) ?></a>
                          <?php if (!empty($devices)): ?>
                            <button class="btn btn-xs btn-warning" type="submit" formaction="<?= e_url(base_url('keys/reset-devices')) ?>" name="id" value="<?= e((string)$rowId) ?>" onclick="return confirm('<?= e(app_zh('确定清空该卡密已绑定设备？')) ?>');"><?= e(app_zh('清空设备')) ?></button>
                          <?php endif; ?>
                          <button class="btn btn-xs btn-danger" type="submit" formaction="<?= e_url(base_url('keys/delete')) ?>" name="id" value="<?= e((string)$rowId) ?>" onclick="return confirm('<?= e(app_zh('确定删除该卡密？')) ?>');"><?= e(app_zh('删除')) ?></button>
                        <?php endif; ?>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<script>
(function () {
  var bulkForm = document.getElementById('keys-bulk-form');
  var batchActionInput = document.getElementById('keys-batch-action');
  var checkAll = document.getElementById('keys-check-all');
  var rowChecks = Array.prototype.slice.call(document.querySelectorAll('.key-row-check'));
  var selectedCount = document.getElementById('keys-selected-count');

  function selectedRows() {
    return rowChecks.filter(function (input) {
      return input.checked;
    });
  }

  function updateSelectedCount() {
    if (!selectedCount) {
      return;
    }
    selectedCount.textContent = '<?= e(app_zh('已选')) ?> ' + selectedRows().length + ' <?= e(app_zh('项')) ?>';
  }

  if (checkAll) {
    checkAll.addEventListener('change', function () {
      rowChecks.forEach(function (input) {
        input.checked = !!checkAll.checked;
      });
      updateSelectedCount();
    });
  }

  rowChecks.forEach(function (input) {
    input.addEventListener('change', function () {
      if (!checkAll) {
        updateSelectedCount();
        return;
      }
      checkAll.checked = rowChecks.length > 0 && rowChecks.every(function (row) { return row.checked; });
      updateSelectedCount();
    });
  });

  window.keysSubmitBatch = function (action) {
    if (!bulkForm) {
      return false;
    }
    if (selectedRows().length === 0) {
      alert('<?= e(app_zh('请先勾选卡密')) ?>');
      return false;
    }
    if (batchActionInput) {
      batchActionInput.value = action;
    }
    if (action === 'delete') {
      return confirm('<?= e(app_zh('确定删除已选卡密？')) ?>');
    }
    if (action === 'reset_devices') {
      return confirm('<?= e(app_zh('确定清空已选卡密的绑定设备？')) ?>');
    }
    if (action === 'status_inactive') {
      return confirm('<?= e(app_zh('确定封禁已选卡密？')) ?>');
    }
    if (action === 'status_active') {
      return confirm('<?= e(app_zh('确定解封已选卡密？')) ?>');
    }
    if (action === 'extend_hours') {
      var extendInput = document.getElementById('batch-extend-hours');
      var hours = extendInput ? parseInt(extendInput.value || '0', 10) : 0;
      if (!hours || hours < 1 || hours > 8760) {
        alert('<?= e(app_zh('请输入 1 到 8760 之间的加时小时数')) ?>');
        if (extendInput) {
          extendInput.focus();
        }
        return false;
      }
      return confirm('<?= e(app_zh('确定为已选卡密批量加时？')) ?>');
    }
    return true;
  };

  var copyBtn = document.getElementById('copy-last-keys');
  var area = document.getElementById('last-keys');
  if (copyBtn && area) {
    copyBtn.addEventListener('click', function () {
      area.select();
      document.execCommand('copy');
    });
  }

  document.querySelectorAll('.key-copy-btn').forEach(function (btn) {
    btn.addEventListener('click', function () {
      var value = btn.getAttribute('data-key') || '';
      if (!value) {
        return;
      }

      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(value);
        return;
      }

      var input = document.createElement('input');
      input.value = value;
      document.body.appendChild(input);
      input.select();
      document.execCommand('copy');
      document.body.removeChild(input);
    });
  });

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