<?php
// admin/tickets_download.php — batched ticket ZIP downloads (shared-hosting friendly)
require_once __DIR__ . '/../config.php';
adminGuard();
require_once __DIR__ . '/_layout.php';

$db      = db();
$adminId = (int)$_SESSION['admin_id'];
$eventId = (int)($_GET['event_id'] ?? 0);

$ev = $db->prepare('SELECT * FROM events WHERE id=? AND admin_id=?');
$ev->execute([$eventId, $adminId]);
$event = $ev->fetch();
if (!$event) { header('Location: ' . BASE_URL . '/admin/events.php'); exit; }

// Batch size — keep each request small enough for shared hosting limits
$allowed = [50, 100, 200, 500];
$per     = (int)($_GET['per'] ?? 200);
if (!in_array($per, $allowed, true)) $per = 200;

// Counts
$c = $db->prepare('SELECT COUNT(*) FROM guests WHERE event_id=? AND invite_path IS NOT NULL AND invite_path != ""');
$c->execute([$eventId]);
$withTickets = (int)$c->fetchColumn();

$c2 = $db->prepare('SELECT COUNT(*) FROM guests WHERE event_id=?');
$c2->execute([$eventId]);
$totalGuests = (int)$c2->fetchColumn();
$missing     = $totalGuests - $withTickets;

$partCount = $withTickets > 0 ? (int)ceil($withTickets / $per) : 0;

layout_start('Download Tickets — ' . $event['title'], 'ticket');
event_tabs($eventId, 'tickets', $event['title']);
?>

<div class="page-header">
  <div>
    <div class="page-header-sub">Ticket Management</div>
    <h1>Download Tickets</h1>
  </div>
  <a href="<?= BASE_URL ?>/admin/ticket_designer.php?event_id=<?= $eventId ?>" class="btn btn-outline btn-sm">← Designer</a>
</div>

<div class="stats-grid">
  <div class="stat-card success">
    <div class="stat-value"><?= $withTickets ?></div>
    <div class="stat-label">Tickets Ready</div>
  </div>
  <div class="stat-card <?= $missing > 0 ? 'danger' : '' ?>">
    <div class="stat-value"><?= $missing ?></div>
    <div class="stat-label">Guests Without a Ticket</div>
  </div>
  <div class="stat-card info">
    <div class="stat-value"><?= $partCount ?></div>
    <div class="stat-label">Download Part<?= $partCount === 1 ? '' : 's' ?></div>
  </div>
</div>

<?php if ($missing > 0): ?>
  <div class="alert alert-info" style="margin-bottom:20px">
    <?= $missing ?> guest<?= $missing === 1 ? ' has' : 's have' ?> no ticket yet — they won't be in the download.
    <a href="<?= BASE_URL ?>/admin/ticket_designer.php?event_id=<?= $eventId ?>" style="color:var(--gold)">Generate tickets first</a>.
  </div>
<?php endif; ?>

<?php if ($withTickets === 0): ?>

  <div class="card" style="text-align:center;padding:48px 28px">
    <h2 style="font-family:var(--font-display);font-size:1.5rem;margin-bottom:10px">No tickets to download yet</h2>
    <p class="text-muted" style="max-width:420px;margin:0 auto 22px">
      Generate tickets for your guests first, then come back to download them.
    </p>
    <a href="<?= BASE_URL ?>/admin/ticket_designer.php?event_id=<?= $eventId ?>" class="btn btn-gold">Go to Ticket Designer</a>
  </div>

<?php else: ?>

  <!-- Batch size -->
  <div class="card card-sm mb-3" style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap">
    <div>
      <div class="label-ui mb-1">Tickets per file</div>
      <div class="text-muted text-sm">Smaller batches are safer on shared hosting. Each part downloads separately.</div>
    </div>
    <form method="GET" style="display:flex;gap:8px;align-items:center" data-no-loader>
      <input type="hidden" name="event_id" value="<?= $eventId ?>">
      <select name="per" class="form-control" style="width:auto;padding:8px 12px;font-size:.82rem" onchange="this.form.submit()">
        <?php foreach ($allowed as $n): ?>
          <option value="<?= $n ?>" <?= $per === $n ? 'selected' : '' ?>><?= $n ?> per file</option>
        <?php endforeach; ?>
      </select>
    </form>
  </div>

  <div class="card">
    <div class="card-header">
      <span class="card-title">
        <?= $partCount ?> file<?= $partCount === 1 ? '' : 's' ?>
        <span class="badge badge-muted" style="margin-left:8px"><?= $withTickets ?> tickets</span>
      </span>
      <?php if ($partCount > 1): ?>
        <button class="btn btn-outline btn-sm" type="button" onclick="downloadAllParts()" data-no-loader>
          ⬇ Download all parts
        </button>
      <?php endif; ?>
    </div>

    <?php if ($partCount > 1): ?>
      <p class="text-muted text-sm" style="margin-bottom:16px">
        Download each part one at a time. "Download all parts" queues them a few seconds apart so the
        server isn't asked to build every archive at once — keep this tab open until they finish.
      </p>
    <?php endif; ?>

    <div style="display:flex;flex-direction:column;gap:8px">
      <?php for ($p = 0; $p < $partCount; $p++):
        $offset = $p * $per;
        $from   = $offset + 1;
        $to     = min($offset + $per, $withTickets);
        $url    = BASE_URL . '/api/tickets_zip.php?event_id=' . $eventId . '&offset=' . $offset . '&limit=' . $per;
      ?>
        <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;
                    padding:12px 14px;background:var(--surface-2);border:1px solid var(--border);
                    border-radius:var(--radius);flex-wrap:wrap">
          <div>
            <div style="font-weight:500">Part <?= $p + 1 ?> of <?= $partCount ?></div>
            <div class="text-muted text-sm">Tickets <?= $from ?>–<?= $to ?> (<?= $to - $from + 1 ?> files)</div>
          </div>
          <a class="btn btn-gold btn-sm part-link" data-no-loader href="<?= htmlspecialchars($url) ?>">⬇ Download</a>
        </div>
      <?php endfor; ?>
    </div>
  </div>

  <script>
  // Queue each part a few seconds apart — one archive is built at a time.
  function downloadAllParts() {
    const links = Array.from(document.querySelectorAll('.part-link'));
    if (!links.length) return;
    showToast('Queuing ' + links.length + ' downloads — keep this tab open.', 'info', 5000);
    links.forEach((a, i) => {
      setTimeout(() => {
        const f = document.createElement('iframe');
        f.style.display = 'none';
        f.src = a.href;
        document.body.appendChild(f);
        setTimeout(() => f.remove(), 120000);
        if (i === links.length - 1) showToast('All parts requested.', 'success');
      }, i * 6000); // 6s apart
    });
  }
  </script>

<?php endif; ?>

<?php layout_end(); ?>
