<?php
include('../config/db.php');
include('../includes/auth.php');
require_admin_role();
require_once '../includes/csrf.php';
require_once '../includes/voucher_helpers.php'; // parse_voucher_mode() lives here

$isAdmin = is_admin_role();
$flash = ''; $flashType = 'success';

// Handle POST actions — must run before HTML output (may set $flash)
require_once 'handlers/manage_vouchers_handler.php';

// HTML starts here
include('partials/header.php');

$today   = date('Y-m-d');
$tab     = $_GET['tab'] ?? 'all';

$whereExtra = match($tab) {
    'published' => "AND v.is_public = 1",
    'hidden'    => "AND v.is_public = 0",
    'private'   => "AND (v.type LIKE 'private:%' OR v.type = 'private')",
    'public'    => "AND (v.type NOT LIKE 'private:%' AND v.type != 'private')",
    default     => '',
};

$vouchers = $conn->query("
    SELECT v.*,
           COUNT(DISTINCT vc.id)       AS total_claims,
           SUM(vc.status='redeemed')   AS total_redeemed,
           CASE
             WHEN v.end_date IS NOT NULL AND v.end_date != '0000-00-00' AND v.end_date < '{$today}' THEN 'expired'
             WHEN v.start_date IS NOT NULL AND v.start_date != '0000-00-00' AND v.start_date > '{$today}' THEN 'upcoming'
             ELSE 'active'
           END AS date_status
    FROM vouchers v
    LEFT JOIN vouchers ch ON ch.parent_voucher_id = v.id
    LEFT JOIN voucher_claims vc ON vc.voucher_id = ch.id
    WHERE v.parent_voucher_id IS NULL
    {$whereExtra}
    GROUP BY v.id
    ORDER BY v.created_at DESC
");

$countAll       = (int)$conn->query("SELECT COUNT(*) c FROM vouchers WHERE parent_voucher_id IS NULL")->fetch_assoc()['c'];
$countPublished = (int)$conn->query("SELECT COUNT(*) c FROM vouchers WHERE parent_voucher_id IS NULL AND is_public=1")->fetch_assoc()['c'];
$countHidden    = (int)$conn->query("SELECT COUNT(*) c FROM vouchers WHERE parent_voucher_id IS NULL AND is_public=0")->fetch_assoc()['c'];
$countPrivate   = (int)$conn->query("SELECT COUNT(*) c FROM vouchers WHERE parent_voucher_id IS NULL AND (type LIKE 'private:%' OR type='private')")->fetch_assoc()['c'];
$countPublicM   = $countAll - $countPrivate;
?>
<!-- styles loaded from assets/admin.css -->

<?php if ($flash): ?>
<div style="border-radius:8px;font-size:13px;padding:12px 16px;margin-bottom:16px;display:flex;align-items:center;gap:8px;
  background:<?= $flashType==='error'?'rgba(224,82,82,.12)':'rgba(45,189,135,.12)' ?>;
  border:1px solid <?= $flashType==='error'?'rgba(224,82,82,.3)':'rgba(45,189,135,.3)' ?>;
  color:<?= $flashType==='error'?'#e05252':'#2dbd87' ?>">
  <i class="bi bi-<?= $flashType==='error'?'x-circle-fill':'check-circle-fill' ?>"></i>
  <?= htmlspecialchars($flash) ?>
</div>
<?php endif; ?>

<div class="pg-title">Voucher Management</div>
<div class="pg-sub">Create, edit and control visibility of your vouchers</div>

<!-- Info banner -->
<div class="info-box" style="margin-top:14px">
  <i class="bi bi-eye-slash-fill" style="color:var(--accent);font-size:16px;flex-shrink:0;margin-top:1px"></i>
  <div><strong style="color:var(--accent)">All new vouchers start Hidden.</strong>
  Toggle them Live when ready. <strong>Public</strong> vouchers are claimable by anyone. <strong>Private</strong> vouchers are exclusive — only users you manually release them to can claim them.</div>
</div>

<!-- New Voucher button -->
<div style="margin-top:16px;margin-bottom:0">
  <button class="btn-success" onclick="toggleCreate()" id="create-btn" style="display:inline-flex;align-items:center;gap:8px;padding:9px 18px">
    <i class="bi bi-plus-circle-fill"></i> New Voucher
  </button>
</div>

<!-- Create form -->
<div class="create-panel" id="create-panel">
  <div style="font-size:15px;font-weight:700;margin-bottom:18px;display:flex;align-items:center;gap:8px;flex-wrap:wrap">
    <i class="bi bi-plus-circle" style="color:var(--accent)"></i> Create New Voucher
    <span style="font-size:11px;font-weight:600;color:var(--muted);background:var(--surface2);padding:3px 9px;border-radius:20px;border:1px solid var(--border)">
      <i class="bi bi-eye-slash"></i> Hidden until published
    </span>
  </div>
  <form method="POST" id="create-form">
    <?php csrf_field(); ?>
    <input type="hidden" name="action" value="create_voucher">
    <input type="hidden" name="voucher_mode" id="voucher_mode_input" value="public">

    <!-- Mode selector -->
    <div class="mb-3">
      <label class="frm-label">Voucher Type <span style="color:#e05252">*</span></label>
      <div class="mode-cards">
        <div class="mode-card selected" id="mode-public" onclick="selectMode('public')">
          <div class="mode-card-icon">🌐</div>
          <div>
            <div class="mode-card-title">Public</div>
            <div class="mode-card-desc">Anyone who has the link or visits your page can claim this voucher once it's published.</div>
          </div>
        </div>
        <div class="mode-card" id="mode-private" onclick="selectMode('private')">
          <div class="mode-card-icon">⭐</div>
          <div>
            <div class="mode-card-title">Private</div>
            <div class="mode-card-desc">Exclusive. Only users you manually release this voucher to will be able to claim it.</div>
          </div>
        </div>
      </div>
    </div>

    <div class="create-grid">
      <div>
        <label class="frm-label">Voucher Name <span style="color:#e05252">*</span></label>
        <input type="text" name="event_name" class="frm-ctrl" placeholder="e.g. Buy 1 Free 1 Ice Cream" required maxlength="100">
      </div>
      <div>
        <label class="frm-label">Category / Type</label>
        <input type="text" name="type" class="frm-ctrl" placeholder="e.g. Hokkaido Ice Cream" maxlength="100">
      </div>
      <div>
        <label class="frm-label"><i class="bi bi-calendar3" style="color:var(--accent)"></i> Valid From</label>
        <div class="date-wrap">
          <i class="bi bi-calendar3"></i>
          <input type="date" name="start_date" class="frm-ctrl" required>
        </div>
      </div>
      <div>
        <label class="frm-label"><i class="bi bi-calendar3" style="color:var(--accent)"></i> Valid Until</label>
        <div class="date-wrap">
          <i class="bi bi-calendar3"></i>
          <input type="date" name="end_date" class="frm-ctrl" required>
        </div>
      </div>
      <div>
        <label class="frm-label">Max Uses per User</label>
        <input type="number" name="max_per_user" class="frm-ctrl" value="1" min="1" max="99" placeholder="1">
      </div>
      <div>
        <label class="frm-label">Voucher Code</label>
        <div class="frm-ctrl" style="background:var(--surface2);color:var(--muted);font-family:var(--mono);font-size:12px;cursor:default;display:flex;align-items:center;gap:6px">
          <i class="bi bi-upc-scan"></i> ICE-XXXXXXXX (auto)
        </div>
      </div>
      <div style="grid-column:1/-1">
        <label class="frm-label">Description</label>
        <textarea name="details" class="frm-ctrl" rows="3" placeholder="What does the customer get? Any terms or exclusions to note…" maxlength="2000" style="resize:vertical"></textarea>
        <div style="font-size:11px;color:var(--muted);margin-top:4px"><i class="bi bi-info-circle"></i> Shown on the voucher card the customer sees.</div>
      </div>
    </div>
    <div style="display:flex;gap:10px;margin-top:16px;flex-wrap:wrap">
      <button type="submit" class="btn-success" style="padding:9px 20px">
        <i class="bi bi-save"></i> Create Voucher
      </button>
      <button type="button" class="btn-ghost" onclick="toggleCreate()" style="padding:9px 16px">Cancel</button>
    </div>
  </form>
</div>

<!-- Bulk delete toolbar (hidden until checkboxes selected) -->
<div id="bulk-del-bar" style="display:none;background:rgba(224,82,82,.08);border:1px solid rgba(224,82,82,.25);border-radius:10px;padding:12px 16px;margin-top:16px;display:none;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap">
  <span style="font-size:13px;font-weight:600;color:#e05252" id="bulk-del-count">0 selected</span>
  <div style="display:flex;gap:8px;align-items:center">
    <button onclick="clearVoucherSel()" class="btn-ghost" style="padding:6px 14px;font-size:12px">Clear</button>
    <button onclick="submitBulkDelete()" class="btn-danger" style="padding:6px 14px;font-size:12px;display:inline-flex;align-items:center;gap:6px">
      <i class="bi bi-trash3-fill"></i> Delete selected
    </button>
  </div>
</div>
<form method="POST" id="bulk-del-form" style="display:none">
  <?php csrf_field(); ?>
  <input type="hidden" name="action" value="bulk_delete_vouchers">
  <div id="bulk-del-ids"></div>
</form>

<!-- Tabs -->
<nav class="mv-tabs">
  <a href="?tab=all"       class="mv-tab <?= $tab==='all'?'active':'' ?>"><i class="bi bi-grid-fill"></i> All <span class="tab-cnt"><?= $countAll ?></span></a>
  <a href="?tab=published" class="mv-tab <?= $tab==='published'?'active':'' ?>"><i class="bi bi-eye-fill"></i> Live <span class="tab-cnt"><?= $countPublished ?></span></a>
  <a href="?tab=hidden"    class="mv-tab <?= $tab==='hidden'?'active':'' ?>"><i class="bi bi-eye-slash-fill"></i> Hidden <span class="tab-cnt"><?= $countHidden ?></span></a>
  <a href="?tab=public"    class="mv-tab <?= $tab==='public'?'active':'' ?>"><i class="bi bi-globe2"></i> Public <span class="tab-cnt"><?= $countPublicM ?></span></a>
  <a href="?tab=private"   class="mv-tab <?= $tab==='private'?'active':'' ?>"><i class="bi bi-star-fill"></i> Private <span class="tab-cnt"><?= $countPrivate ?></span></a>
</nav>

<!-- Voucher list -->
<div class="adm-card" style="padding:0;overflow:hidden">
  <!-- Desktop header -->
  <div class="mv-thead">
    <div style="display:flex;align-items:center;gap:10px">
      <input type="checkbox" id="v-sel-all" onchange="toggleAllVouchers(this)"
             style="width:15px;height:15px;accent-color:var(--accent);cursor:pointer;flex-shrink:0">
      <span>Voucher</span>
    </div>
    <div>Visibility</div>
    <div>Type</div>
    <div>Dates</div>
    <div>Claims</div>
    <div>Actions</div>
  </div>

  <?php if ($vouchers->num_rows === 0): ?>
  <div style="padding:48px 20px;text-align:center;color:var(--muted)">
    <i class="bi bi-ticket-perforated" style="font-size:36px;display:block;margin-bottom:10px;opacity:.3"></i>
    <div style="font-size:14px;font-weight:600;margin-bottom:6px">No vouchers found</div>
    <div style="font-size:12px">Click <strong>New Voucher</strong> above to get started.</div>
  </div>
  <?php else: while ($v = $vouchers->fetch_assoc()):
    $isPublic  = (int)$v['is_public'];
    $isExpired = $v['date_status'] === 'expired';
    $parsed    = parse_voucher_mode($v['type'] ?? '');
    $mode      = $parsed['mode'];
    $typeLabel = $parsed['label'];
    $sDate = ($v['start_date'] && $v['start_date'] !== '0000-00-00') ? date('d M Y', strtotime($v['start_date'])) : null;
    $eDate = ($v['end_date']   && $v['end_date']   !== '0000-00-00') ? date('d M Y', strtotime($v['end_date']))   : null;
    $editData = json_encode([
      'id'         => $v['id'],
      'event_name' => $v['event_name'],
      'details'    => $v['details'] ?? '',
      'start_date' => ($v['start_date'] !== '0000-00-00' ? $v['start_date'] : ''),
      'end_date'   => ($v['end_date']   !== '0000-00-00' ? $v['end_date']   : ''),
      'mode'       => $mode,
      'type_label' => $typeLabel,
    ], JSON_HEX_QUOT|JSON_HEX_APOS);
  ?>
  <div class="mv-card" data-vid="<?= $v['id'] ?>">

    <!-- Name column (always visible) -->
    <div style="display:flex;align-items:flex-start;gap:10px">
      <input type="checkbox" class="v-sel" data-id="<?= $v['id'] ?>"
             onchange="updateVoucherBulkBar()"
             style="width:15px;height:15px;accent-color:var(--accent);cursor:pointer;flex-shrink:0;margin-top:3px">
      <div style="min-width:0">
        <div class="mv-name"><?= htmlspecialchars($v['event_name']) ?></div>
        <?php if ($typeLabel): ?>
        <div class="mv-type"><i class="bi bi-tag-fill" style="color:var(--accent);font-size:10px"></i><?= htmlspecialchars($typeLabel) ?></div>
        <?php endif; ?>
        <?php if ($v['details']): ?>
        <div class="mv-desc"><?= htmlspecialchars($v['details']) ?></div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Visibility (desktop column, mobile pill) -->
    <div class="mv-col-vis">
      <?php if ($isExpired): ?>
        <span class="pill pill-expired"><i class="bi bi-clock"></i> Expired</span>
      <?php elseif ($mode === 'private'): ?>
        <!-- Private vouchers have no Live/Hidden state — they're release-controlled -->
        <span class="pill pill-private"><i class="bi bi-star-fill"></i> Exclusive</span>
      <?php elseif ($isPublic): ?>
        <span class="pill pill-live" id="pill-<?= $v['id'] ?>"><i class="bi bi-eye-fill"></i> Live</span>
      <?php else: ?>
        <span class="pill pill-hidden" id="pill-<?= $v['id'] ?>"><i class="bi bi-eye-slash-fill"></i> Hidden</span>
      <?php endif; ?>
    </div>

    <!-- Mode (desktop column, mobile pill) -->
    <div class="mv-col-uses">
      <?php if ($mode === 'private'): ?>
        <span class="pill pill-private"><i class="bi bi-star-fill"></i> Private</span>
      <?php else: ?>
        <span class="pill pill-public-mode"><i class="bi bi-globe2"></i> Public</span>
      <?php endif; ?>
    </div>

    <!-- Dates (desktop) -->
    <div class="mv-col-dates" style="font-size:11.5px;color:var(--muted);line-height:1.6">
      <?= $sDate ? '<i class="bi bi-play-fill" style="color:var(--accent);font-size:10px"></i> '.$sDate : '<span style="opacity:.4">No start</span>' ?>
      <br><?= $eDate ? '<i class="bi bi-stop-fill" style="color:#e05252;font-size:10px"></i> '.$eDate  : '<span style="opacity:.4">No end</span>' ?>
    </div>

    <!-- Claims (desktop) -->
    <div class="mv-col-claims">
      <div style="font-size:14px;font-weight:700;font-family:var(--mono);color:var(--accent)"><?= (int)$v['total_claims'] ?></div>
      <div style="font-size:10.5px;color:var(--muted)"><?= (int)$v['total_redeemed'] ?> used</div>
    </div>

    <!-- Mobile meta pills row -->
    <div class="mv-mobile-meta">
      <!-- Checkbox for mobile -->
      <label style="display:flex;align-items:center;gap:6px;font-size:12px;color:var(--muted);cursor:pointer;width:100%;margin-bottom:4px">
        <input type="checkbox" class="v-sel" data-id="<?= $v['id'] ?>"
               onchange="updateVoucherBulkBar()"
               style="width:15px;height:15px;accent-color:var(--accent);cursor:pointer">
        Select
      </label>
      <!-- Visibility pill -->
      <?php if ($isExpired): ?>
        <span class="pill pill-expired"><i class="bi bi-clock"></i> Expired</span>
      <?php elseif ($mode === 'private'): ?>
        <span class="pill pill-private"><i class="bi bi-star-fill"></i> Exclusive</span>
      <?php elseif ($isPublic): ?>
        <span class="pill pill-live" id="pill-m-<?= $v['id'] ?>"><i class="bi bi-eye-fill"></i> Live</span>
      <?php else: ?>
        <span class="pill pill-hidden" id="pill-m-<?= $v['id'] ?>"><i class="bi bi-eye-slash-fill"></i> Hidden</span>
      <?php endif; ?>
      <!-- Mode pill (only show for public so we don't double-up on private) -->
      <?php if ($mode !== 'private'): ?>
        <span class="pill pill-public-mode"><i class="bi bi-globe2"></i> Public</span>
      <?php endif; ?>
      <!-- Claims count on mobile -->
      <span class="pill" style="background:var(--surface2);border:1px solid var(--border);color:var(--text)">
        <i class="bi bi-ticket-perforated" style="color:var(--accent)"></i>
        <?= (int)$v['total_claims'] ?> claimed · <?= (int)$v['total_redeemed'] ?> used
      </span>
      <!-- Dates on mobile -->
      <?php if ($sDate || $eDate): ?>
      <span class="pill" style="background:var(--surface2);border:1px solid var(--border);color:var(--muted)">
        <i class="bi bi-calendar3" style="color:var(--accent)"></i>
        <?= $sDate ?? '?' ?> → <?= $eDate ?? '∞' ?>
      </span>
      <?php endif; ?>
    </div>

    <!-- Actions -->
    <div class="mv-actions">
      <?php if ($mode === 'private'): ?>
        <!-- Private: no toggle — controlled via Release to Users -->
        <span style="font-size:11px;color:var(--muted);display:flex;align-items:center;gap:5px;white-space:nowrap">
          <i class="bi bi-people-fill" style="color:var(--accent)"></i>
          <span class="d-none d-sm-inline">Release only</span>
        </span>
      <?php else: ?>
        <!-- Public: show publish/hide toggle -->
        <label class="tog-sw" title="<?= $isPublic ? 'Click to Hide' : 'Click to Publish' ?>">
          <input type="checkbox"
                 <?= $isPublic ? 'checked' : '' ?>
                 <?= $isExpired ? 'disabled' : '' ?>
                 onchange="doToggle(<?= $v['id'] ?>, this.checked, this)">
          <span class="sl"></span>
        </label>
        <span style="font-size:11px;color:var(--muted);min-width:36px" id="tog-lbl-<?= $v['id'] ?>"><?= $isPublic ? 'Live' : 'Hidden' ?></span>
      <?php endif; ?>
      <!-- Edit (always shown) -->
      <button class="btn-sm-edit" onclick="openEdit(<?= htmlspecialchars($editData, ENT_QUOTES) ?>)">
        <i class="bi bi-pencil-fill"></i> <span class="d-none d-sm-inline">Edit</span>
      </button>
    </div>
  </div>
  <?php endwhile; endif; ?>
</div>

<!-- Edit Drawer -->
<div class="overlay" id="drawer-overlay" onclick="closeEdit()"></div>
<div class="edit-drawer" id="edit-drawer">
  <div class="edit-drawer-head">
    <div style="font-size:15px;font-weight:700;display:flex;align-items:center;gap:8px">
      <i class="bi bi-pencil-fill" style="color:var(--accent)"></i> Edit Voucher
    </div>
    <button onclick="closeEdit()" style="background:none;border:none;color:var(--muted);font-size:22px;cursor:pointer;line-height:1;padding:4px"><i class="bi bi-x"></i></button>
  </div>
  <div class="edit-drawer-body">
    <div class="info-box" style="margin-bottom:18px">
      <i class="bi bi-info-circle-fill" style="color:var(--accent);flex-shrink:0"></i>
      Changes update this voucher and all copies already claimed by users.
    </div>
    <div id="edit-form-wrap"></div>
  </div>
  <div class="edit-drawer-foot">
    <button class="btn-success" onclick="submitEdit()" style="flex:1;justify-content:center;padding:10px;display:flex;align-items:center;gap:6px">
      <i class="bi bi-save"></i> Save Changes
    </button>
    <button onclick="closeEdit()" class="btn-ghost" style="padding:10px 16px">Cancel</button>
  </div>
</div>

<script>
let _eid = null;

function selectMode(m) {
  document.getElementById('voucher_mode_input').value = m;
  document.getElementById('mode-public').classList.toggle('selected', m === 'public');
  document.getElementById('mode-private').classList.toggle('selected', m === 'private');
}

function toggleCreate() {
  const p = document.getElementById('create-panel');
  const b = document.getElementById('create-btn');
  const open = p.classList.toggle('open');
  b.innerHTML = open
    ? '<i class="bi bi-x-circle"></i> Cancel'
    : '<i class="bi bi-plus-circle-fill"></i> New Voucher';
  if (open) p.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}

async function doToggle(id, newVal, checkbox) {
  const lbl  = document.getElementById('tog-lbl-' + id);
  const pill  = document.getElementById('pill-' + id);
  const pillM = document.getElementById('pill-m-' + id);
  checkbox.disabled = true;
  try {
    const res = await fetch('toggle.php', {
      method: 'POST',
      headers: { 'X-CSRF-Token': CSRF },
      body: new URLSearchParams({ id, val: newVal ? 1 : 0 })
    });
    const data = await res.json();
    if (data.success) {
      const liveHtml   = '<i class="bi bi-eye-fill"></i> Live';
      const hiddenHtml = '<i class="bi bi-eye-slash-fill"></i> Hidden';
      if (lbl)  lbl.textContent = newVal ? 'Live' : 'Hidden';
      [pill, pillM].forEach(el => {
        if (!el) return;
        el.className = newVal ? 'pill pill-live' : 'pill pill-hidden';
        el.innerHTML = newVal ? liveHtml : hiddenHtml;
      });
      showToast(newVal
        ? 'Voucher is now Live — visible to users.'
        : 'Voucher hidden — no longer visible to users.', 'success');
    } else {
      checkbox.checked = !newVal;
      showToast(data.error || 'Toggle failed.', 'error');
    }
  } catch(e) {
    checkbox.checked = !newVal;
    showToast('Network error.', 'error');
  } finally {
    checkbox.disabled = false;
  }
}

function openEdit(v) {
  _eid = v.id;
  document.getElementById('edit-form-wrap').innerHTML = `
    <div class="mb-3">
      <label class="frm-label">Voucher Name <span style="color:#e05252">*</span></label>
      <input type="text" id="ef-name" class="frm-ctrl" value="${esc(v.event_name)}" maxlength="100">
    </div>
    <div class="mb-3">
      <label class="frm-label">Category / Type</label>
      <input type="text" id="ef-type" class="frm-ctrl" value="${esc(v.type_label)}" maxlength="100" placeholder="e.g. Hokkaido Ice Cream">
    </div>
    <div class="mb-3">
      <label class="frm-label"><i class="bi bi-calendar3" style="color:var(--accent)"></i> Valid From</label>
      <div class="date-wrap"><i class="bi bi-calendar3"></i>
        <input type="date" id="ef-start" class="frm-ctrl" value="${esc(v.start_date)}">
      </div>
    </div>
    <div class="mb-3">
      <label class="frm-label"><i class="bi bi-calendar3" style="color:var(--accent)"></i> Valid Until</label>
      <div class="date-wrap"><i class="bi bi-calendar3"></i>
        <input type="date" id="ef-end" class="frm-ctrl" value="${esc(v.end_date)}">
      </div>
    </div>
    <div class="mb-3">
      <label class="frm-label">Voucher Mode</label>
      <div style="display:flex;gap:8px">
        <label style="display:flex;align-items:center;gap:6px;cursor:pointer;font-size:13px;padding:8px 12px;border:1px solid var(--border);border-radius:8px;flex:1;transition:.15s" id="em-pub">
          <input type="radio" name="ef-mode" value="public" ${v.mode !== 'private' ? 'checked' : ''} onchange="updateEditMode()" style="accent-color:var(--accent)">
          🌐 Public
        </label>
        <label style="display:flex;align-items:center;gap:6px;cursor:pointer;font-size:13px;padding:8px 12px;border:1px solid var(--border);border-radius:8px;flex:1;transition:.15s" id="em-priv">
          <input type="radio" name="ef-mode" value="private" ${v.mode === 'private' ? 'checked' : ''} onchange="updateEditMode()" style="accent-color:var(--accent)">
          ⭐ Private
        </label>
      </div>
    </div>
    <div class="mb-3">
      <label class="frm-label">Description</label>
      <textarea id="ef-details" class="frm-ctrl" rows="5" maxlength="2000" style="resize:vertical"
        placeholder="What does the customer get? Any terms…">${esc(v.details)}</textarea>
      <div style="font-size:11px;color:var(--muted);margin-top:4px"><i class="bi bi-info-circle"></i> Shown on the voucher card.</div>
    </div>
  `;
  document.getElementById('edit-drawer').classList.add('open');
  document.getElementById('drawer-overlay').classList.add('show');
  document.getElementById('ef-name').focus();
}

function updateEditMode() {/* visual feedback only */}

function closeEdit() {
  document.getElementById('edit-drawer').classList.remove('open');
  document.getElementById('drawer-overlay').classList.remove('show');
  _eid = null;
}

async function submitEdit() {
  if (!_eid) return;
  const name    = document.getElementById('ef-name').value.trim();
  const typeL   = document.getElementById('ef-type').value.trim();
  const details = document.getElementById('ef-details').value.trim();
  const start   = document.getElementById('ef-start').value;
  const end     = document.getElementById('ef-end').value;
  const mode    = document.querySelector('input[name="ef-mode"]:checked')?.value ?? 'public';
  if (!name)  { showToast('Voucher name is required.', 'error'); return; }
  if (!start) { showToast('Start date is required.', 'error');  return; }
  if (!end)   { showToast('End date is required.', 'error');    return; }
  if (end < start) { showToast('End date cannot be before start date.', 'error'); return; }
  const typeStored = mode + (typeL ? ':' + typeL : '');
  try {
    const res = await fetch('edit_voucher.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRF-Token': CSRF },
      body: new URLSearchParams({ id: _eid, event_name: name, type: typeStored, details, start_date: start, end_date: end })
    });
    const data = await res.json();
    if (data.success) {
      showToast('Voucher updated.', 'success');
      closeEdit();
      setTimeout(() => location.reload(), 800);
    } else {
      showToast(data.error || 'Could not save.', 'error');
    }
  } catch(e) { showToast('Network error.', 'error'); }
}

function esc(s) {
  return (s ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
}

/* ── Bulk delete vouchers ── */
function toggleAllVouchers(cb) {
  document.querySelectorAll('.v-sel').forEach(c => c.checked = cb.checked);
  updateVoucherBulkBar();
}
function updateVoucherBulkBar() {
  const sel   = document.querySelectorAll('.v-sel:checked');
  const bar   = document.getElementById('bulk-del-bar');
  const cnt   = document.getElementById('bulk-del-count');
  const all   = document.getElementById('v-sel-all');
  const total = document.querySelectorAll('.v-sel').length;
  bar.style.display = sel.length > 0 ? 'flex' : 'none';
  cnt.textContent   = sel.length + ' voucher' + (sel.length !== 1 ? 's' : '') + ' selected';
  if (all) {
    all.indeterminate = sel.length > 0 && sel.length < total;
    all.checked = sel.length > 0 && sel.length === total;
  }
}
function clearVoucherSel() {
  document.querySelectorAll('.v-sel').forEach(c => c.checked = false);
  const all = document.getElementById('v-sel-all');
  if (all) { all.checked = false; all.indeterminate = false; }
  document.getElementById('bulk-del-bar').style.display = 'none';
}
function submitBulkDelete() {
  const sel = Array.from(document.querySelectorAll('.v-sel:checked')).map(c => c.dataset.id);
  if (!sel.length) return;
  if (!confirm('Permanently delete ' + sel.length + ' voucher(s)?\n\nThis also removes all claim history for those vouchers. This cannot be undone.')) return;
  const container = document.getElementById('bulk-del-ids');
  container.innerHTML = '';
  sel.forEach(id => {
    const inp = document.createElement('input');
    inp.type = 'hidden'; inp.name = 'voucher_ids[]'; inp.value = id;
    container.appendChild(inp);
  });
  document.getElementById('bulk-del-form').submit();
}
</script>

<?php include('partials/footer.php'); ?>
