let couponState = {coupons: [], redemptions: []};

function money(amount, currency='LBP') {
  const value = Number(amount || 0);
  return `${value.toLocaleString(undefined, {minimumFractionDigits: value % 1 ? 2 : 0, maximumFractionDigits: 2})} ${String(currency || 'LBP').toUpperCase()}`;
}

function statusPill(status) {
  const s = String(status || 'inactive');
  const cls = s === 'active' ? 'pill-green' : 'pill-red';
  return `<span class="pill ${cls}">${Pyrk.esc(s)}</span>`;
}

function couponDiscountText(c) {
  if (c.discount_type === 'fixed') return money(c.discount_value, c.currency);
  return `${Number(c.discount_value || 0)}%`;
}

function datetimeValue(value) {
  if (!value) return '';
  return String(value).replace(' ', 'T').slice(0, 16);
}

function filteredCoupons() {
  const q = (document.getElementById('couponSearch')?.value || '').toLowerCase().trim();
  const status = document.getElementById('couponStatusFilter')?.value || '';
  return (couponState.coupons || []).filter(c => {
    const hay = `${c.code || ''} ${c.description || ''}`.toLowerCase();
    return (!q || hay.includes(q)) && (!status || c.status === status);
  });
}

function renderStats() {
  const coupons = couponState.coupons || [];
  const redemptions = couponState.redemptions || [];
  document.getElementById('couponTotal').textContent = coupons.length;
  document.getElementById('couponActive').textContent = coupons.filter(c => c.status === 'active').length;
  document.getElementById('couponUsed').textContent = redemptions.length;
  const discount = redemptions.reduce((sum, r) => sum + Number(r.discount_amount || 0), 0);
  document.getElementById('couponDiscount').textContent = discount.toLocaleString();
}

function renderCoupons() {
  renderStats();
  const grid = document.getElementById('couponGrid');
  if (!grid) return;
  const rows = filteredCoupons();
  grid.innerHTML = rows.map(c => {
    const used = Number(c.used_count || 0);
    const max = c.max_uses ? Number(c.max_uses) : null;
    const limitText = max ? `${used}/${max} uses` : `${used} uses`;
    return `<article class="coupon-admin-card ${c.status !== 'active' ? 'is-inactive' : ''}">
      <div class="coupon-code-line"><strong>${Pyrk.esc(c.code)}</strong>${statusPill(c.status)}</div>
      <p>${Pyrk.esc(c.description || 'No description')}</p>
      <div class="coupon-meta-grid">
        <span><b>${Pyrk.esc(couponDiscountText(c))}</b><em>Discount</em></span>
        <span><b>${Pyrk.esc(limitText)}</b><em>Usage</em></span>
        <span><b>${c.valid_until ? Pyrk.formatDateTime(c.valid_until) : 'No expiry'}</b><em>Valid until</em></span>
      </div>
      <div class="inline-controls tiny-controls">
        <button class="btn btn-light btn-small" onclick="editCoupon(${c.id})">Edit</button>
        ${c.status === 'active' ? `<button class="btn btn-danger btn-small" onclick="deactivateCoupon(${c.id}, '${Pyrk.esc(c.code).replace(/'/g, '&#39;')}')">Deactivate</button>` : ''}
      </div>
    </article>`;
  }).join('') || '<div class="empty-state"><strong>No coupons found</strong><span>Create your first coupon code.</span></div>';
}

function renderRedemptions() {
  const body = document.getElementById('couponRedemptionsBody');
  if (!body) return;
  body.innerHTML = (couponState.redemptions || []).map(r => `<tr>
    <td>${Pyrk.formatDateTime(r.redeemed_at || r.created_at)}</td>
    <td><strong>${Pyrk.esc(r.code)}</strong></td>
    <td>${Pyrk.esc(r.full_name)}<small>${Pyrk.esc(r.mobile || r.email || '')}</small></td>
    <td>${Pyrk.esc(r.walk_title)}</td>
    <td>${money(r.original_amount, r.currency)}</td>
    <td><span class="ledger-points is-use">-${money(r.discount_amount, r.currency)}</span></td>
    <td><strong>${money(r.final_amount, r.currency)}</strong></td>
  </tr>`).join('') || '<tr><td colspan="7" class="muted">No coupon redemptions yet.</td></tr>';
}

function renderAll() {
  renderCoupons();
  renderRedemptions();
  renderCouponPreview();
}

function resetCouponForm() {
  const form = document.getElementById('couponForm');
  form?.reset();
  document.getElementById('couponId').value = '';
  document.getElementById('couponFormTitle').textContent = 'Create coupon';
  document.getElementById('couponDiscountType').value = 'percent';
  document.getElementById('couponCurrency').value = 'LBP';
  document.getElementById('couponStatus').value = 'active';
  document.getElementById('couponMaxPerUser').value = '1';
  document.getElementById('couponMinAmount').value = '0';
  Pyrk.toast('couponMsg', {ok:true, message:''});
  renderCouponPreview();
}

function renderCouponPreview() {
  const type = document.getElementById('couponDiscountType')?.value || 'percent';
  const value = Number(document.getElementById('couponDiscountValue')?.value || 0);
  const currency = document.getElementById('couponCurrency')?.value || 'LBP';
  const preview = document.getElementById('couponPreview');
  if (!preview) return;
  preview.textContent = type === 'fixed' ? `Preview: fixed discount ${money(value, currency)}` : `Preview: ${value || 0}% discount`;
  preview.classList.toggle('is-fixed', type === 'fixed');
}

window.editCoupon = function editCoupon(id) {
  const c = (couponState.coupons || []).find(x => Number(x.id) === Number(id));
  if (!c) return;
  document.getElementById('couponFormTitle').textContent = 'Edit coupon';
  document.getElementById('couponId').value = c.id;
  document.getElementById('couponCode').value = c.code || '';
  document.getElementById('couponDescription').value = c.description || '';
  document.getElementById('couponDiscountType').value = c.discount_type || 'percent';
  document.getElementById('couponDiscountValue').value = c.discount_value || 0;
  document.getElementById('couponCurrency').value = c.currency || 'LBP';
  document.getElementById('couponStatus').value = c.status || 'active';
  document.getElementById('couponValidFrom').value = datetimeValue(c.valid_from);
  document.getElementById('couponValidUntil').value = datetimeValue(c.valid_until);
  document.getElementById('couponMaxUses').value = c.max_uses ?? '';
  document.getElementById('couponMaxPerUser').value = c.max_uses_per_user || 1;
  document.getElementById('couponMinAmount').value = c.min_walk_amount || 0;
  renderCouponPreview();
  document.querySelector('.enterprise-form-panel')?.scrollIntoView({behavior:'smooth', block:'start'});
};

window.deactivateCoupon = async function deactivateCoupon(id, code) {
  if (!confirm(`Deactivate coupon ${code}?`)) return;
  const res = await Pyrk.post('coupons.php', {action:'deactivate', id});
  alert(res.message || (res.ok ? 'Updated.' : 'Failed.'));
  if (res.ok) await loadCoupons();
};

async function loadCoupons() {
  const res = await Pyrk.get('coupons.php', {action:'admin'});
  if (!res.ok) {
    document.getElementById('couponGrid').innerHTML = `<div class="notice bad">${Pyrk.esc(res.message)}</div>`;
    return;
  }
  couponState = res.data || {coupons: [], redemptions: []};
  renderAll();
}

document.getElementById('couponForm')?.addEventListener('submit', async e => {
  e.preventDefault();
  const fd = new FormData(e.currentTarget);
  fd.append('action', 'save');
  const res = await Pyrk.postForm('coupons.php', fd);
  Pyrk.toast('couponMsg', res);
  if (res.ok) {
    resetCouponForm();
    await loadCoupons();
  }
});

document.getElementById('newCouponBtn')?.addEventListener('click', resetCouponForm);
document.getElementById('resetCouponForm')?.addEventListener('click', resetCouponForm);
document.getElementById('couponSearch')?.addEventListener('input', renderCoupons);
document.getElementById('couponStatusFilter')?.addEventListener('change', renderCoupons);
['couponDiscountType','couponDiscountValue','couponCurrency'].forEach(id => document.getElementById(id)?.addEventListener('input', renderCouponPreview));
['couponDiscountType','couponCurrency'].forEach(id => document.getElementById(id)?.addEventListener('change', renderCouponPreview));

loadCoupons();
