<div class="page-actions" style="margin-bottom:20px">
  <button class="btn btn-primary" onclick="document.getElementById('newPromoModal').style.display='flex'"><i class="bi bi-plus-circle-fill"></i> New Promo Code</button>
</div>

<div class="admin-card">
  <table class="admin-table">
    <thead><tr><th>Code</th><th>Type</th><th>Value</th><th>Uses</th><th>Valid Until</th><th>Status</th><th>Actions</th></tr></thead>
    <tbody>
      <% if (codes && codes.length) { %>
      <% codes.forEach(c => { %>
      <tr>
        <td>
          <code style="font-size:.85rem;background:#f3f4f6;padding:3px 8px;border-radius:5px;font-weight:700"><%= c.code %></code><br>
          <span style="font-size:.72rem;color:#9ca3af"><%= c.description || '' %></span>
        </td>
        <td><span class="badge badge-<%= c.discount_type==='trial_extension'?'info':c.discount_type==='percent'?'warning':'secondary' %>"><%= c.discount_type.replace('_',' ') %></span></td>
        <td style="font-size:.85rem;font-weight:600">
          <% if (c.discount_type === 'percent') { %><%= c.discount_value %>% off
          <% } else if (c.discount_type === 'fixed') { %>$<%= parseFloat(c.discount_value).toFixed(2) %> off
          <% } else if (c.discount_type === 'trial_extension') { %>+<%= c.trial_extension_days %> days trial
          <% } else { %>1 month free<% } %>
        </td>
        <td style="font-size:.8rem"><%= c.redemptions || c.uses_count || 0 %><% if(c.max_uses) { %>/<%= c.max_uses %><% } %></td>
        <td style="font-size:.78rem"><%= c.valid_until ? moment(c.valid_until).format('MMM D, YYYY') : 'No expiry' %></td>
        <td><span class="badge badge-<%= c.is_active ? 'success' : 'secondary' %>"><%= c.is_active ? 'Active' : 'Inactive' %></span></td>
        <td>
          <% if (c.is_active) { %>
          <button class="btn btn-xs btn-danger deactivate-promo" data-id="<%= c.id %>"><i class="bi bi-x-circle"></i> Deactivate</button>
          <% } %>
        </td>
      </tr>
      <% }) %>
      <% } else { %>
      <tr><td colspan="7" style="text-align:center;padding:40px;color:#9ca3af">No promo codes yet.</td></tr>
      <% } %>
    </tbody>
  </table>
</div>

<!-- New Promo Modal -->
<div class="modal" id="newPromoModal" style="display:none">
  <div class="modal-backdrop" onclick="document.getElementById('newPromoModal').style.display='none'"></div>
  <div class="modal-content modal-md">
    <div class="modal-header"><h3>Create Promo Code</h3><button onclick="document.getElementById('newPromoModal').style.display='none'" class="modal-close"><i class="bi bi-x-lg"></i></button></div>
    <div class="modal-body">
      <div class="form-group"><label>Code *</label><input type="text" id="promoCode" placeholder="e.g., SUMMER25" style="text-transform:uppercase"></div>
      <div class="form-group"><label>Description</label><input type="text" id="promoDesc" placeholder="Internal description..."></div>
      <div class="form-row">
        <div class="form-group"><label>Type *</label>
          <select id="promoType" onchange="updatePromoType()">
            <option value="percent">Percent Discount</option>
            <option value="fixed">Fixed Amount Off</option>
            <option value="trial_extension">Trial Extension</option>
            <option value="free_month">Free Month</option>
          </select>
        </div>
        <div class="form-group" id="promoValueGroup"><label>Discount Value *</label><input type="number" id="promoValue" placeholder="e.g., 25 for 25%"></div>
        <div class="form-group" id="promoTrialGroup" style="display:none"><label>Extension Days *</label><input type="number" id="promoTrialDays" placeholder="e.g., 30" min="1"></div>
      </div>
      <div class="form-row">
        <div class="form-group"><label>Max Uses</label><input type="number" id="promoMaxUses" placeholder="Leave blank for unlimited"></div>
        <div class="form-group"><label>Valid From</label><input type="date" id="promoValidFrom"></div>
        <div class="form-group"><label>Valid Until</label><input type="date" id="promoValidUntil"></div>
      </div>
      <div class="modal-actions" style="margin-top:20px">
        <button class="btn btn-primary" onclick="createPromo()"><i class="bi bi-check-lg"></i> Create Code</button>
        <button class="btn btn-ghost" onclick="document.getElementById('newPromoModal').style.display='none'">Cancel</button>
      </div>
    </div>
  </div>
</div>

<script>
function updatePromoType() {
  const t = document.getElementById('promoType').value;
  document.getElementById('promoValueGroup').style.display = t === 'trial_extension' || t === 'free_month' ? 'none' : 'block';
  document.getElementById('promoTrialGroup').style.display = t === 'trial_extension' ? 'block' : 'none';
}

async function createPromo() {
  const body = {
    code: document.getElementById('promoCode').value.toUpperCase(),
    description: document.getElementById('promoDesc').value,
    discount_type: document.getElementById('promoType').value,
    discount_value: document.getElementById('promoValue').value || 0,
    trial_extension_days: document.getElementById('promoTrialDays').value || 0,
    max_uses: document.getElementById('promoMaxUses').value || null,
    valid_from: document.getElementById('promoValidFrom').value || null,
    valid_until: document.getElementById('promoValidUntil').value || null
  };
  const res  = await fetch('/admin/promo-codes', {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});
  const data = await res.json();
  if (data.success) { document.getElementById('newPromoModal').style.display='none'; location.reload(); }
  else alert(data.error || 'Failed to create promo code.');
}

document.querySelectorAll('.deactivate-promo').forEach(btn => {
  btn.addEventListener('click', async () => {
    if (!confirm('Deactivate this promo code?')) return;
    const res = await fetch(`/admin/promo-codes/${btn.dataset.id}`, {method:'DELETE'});
    if((await res.json()).success) location.reload();
  });
});
</script>
