let rewardState = {rewards: [], claims: [], tiers: [], sponsors: []};

function publicAsset(path) { if (!path) return ''; if (/^https?:\/\//.test(path)) return path; return (window.PYRK_PUBLIC_BASE || '../') + String(path).replace(/^\/+/, ''); }
function initials(name) { return String(name || 'M').trim().split(/\s+/).slice(0, 2).map(p => p[0] || '').join('').toUpperCase() || 'M'; }
function avatarHtml(person) { return person && person.profile_photo_path ? `<img class="avatar-img" src="${Pyrk.esc(publicAsset(person.profile_photo_path))}" alt="${Pyrk.esc(person.full_name || 'Member')}">` : `<div class="avatar">${Pyrk.esc(initials(person && person.full_name))}</div>`; }
function formatDate(value) { return Pyrk.formatDateTime(value); }
function statusPill(status) { const s = String(status || 'unknown'); const cls = ['active','requested','approved','fulfilled'].includes(s) ? 'pill-green' : (['inactive','rejected','cancelled'].includes(s) ? 'pill-red' : 'pill-muted'); return `<span class="pill ${cls}">${Pyrk.esc(s.replace(/_/g, ' '))}</span>`; }

function claimById(id) {
  return (rewardState.claims || []).find(c => Number(c.id) === Number(id)) || null;
}

function printPrizeClaim(id) {
  const c = claimById(id);
  if (!c) return;
  const claimNo = `PYRK-CLAIM-${String(c.id).padStart(5, '0')}`;
  const printedAt = new Date().toLocaleString();
  const html = `<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>${claimNo}</title>
<style>
  body{font-family:Arial,sans-serif;margin:0;padding:28px;color:#111827;background:#fff}
  .receipt{max-width:760px;margin:0 auto;border:2px solid #111827;border-radius:18px;padding:26px}
  .head{display:flex;justify-content:space-between;gap:16px;border-bottom:1px solid #d1d5db;padding-bottom:16px;margin-bottom:18px}
  .brand{font-size:26px;font-weight:900;letter-spacing:.08em;color:#1c7c54}
  .muted{color:#6b7280;font-size:13px}
  h1{margin:0 0 6px;font-size:22px}
  table{width:100%;border-collapse:collapse;margin:18px 0}
  th,td{text-align:left;border-bottom:1px solid #e5e7eb;padding:11px 6px;vertical-align:top}
  th{width:34%;font-size:12px;text-transform:uppercase;color:#6b7280;letter-spacing:.08em}
  .points{font-size:24px;font-weight:900;color:#b45309}
  .signatures{display:grid;grid-template-columns:1fr 1fr;gap:18px;margin-top:34px}
  .line{border-top:1px solid #111827;padding-top:8px;font-weight:700}
  .note{border:1px dashed #9ca3af;border-radius:12px;padding:12px;margin-top:16px;background:#f9fafb}
  @media print{button{display:none}.receipt{border-radius:0}}
</style>
</head>
<body>
  <div class="receipt">
    <div class="head">
      <div><div class="brand">PYRK</div><div class="muted">Prize claim accounting receipt</div></div>
      <div><h1>${Pyrk.esc(claimNo)}</h1><div class="muted">Printed: ${Pyrk.esc(printedAt)}</div></div>
    </div>
    <table>
      <tr><th>Member</th><td><strong>${Pyrk.esc(c.full_name || '')}</strong><br>${Pyrk.esc(c.mobile || c.email || '')}</td></tr>
      <tr><th>Prize</th><td><strong>${Pyrk.esc(c.reward_name || '')}</strong><br>${Pyrk.esc(c.description || c.reward_type || '')}</td></tr>
      <tr><th>Claim status</th><td>${Pyrk.esc(String(c.status || '').replace(/_/g, ' '))}</td></tr>
      <tr><th>Points used</th><td class="points">${Number(c.points_spent || c.points_cost || 0)} pts</td></tr>
      <tr><th>Requested date</th><td>${Pyrk.esc(formatDate(c.requested_at || c.created_at))}</td></tr>
      <tr><th>Claim ID</th><td>#${Number(c.id || 0)}</td></tr>
    </table>
    <div class="note"><strong>Cashier/accounting note:</strong> Keep this receipt with the cashier settlement or prize handover record.</div>
    <div class="signatures">
      <div class="line">Cashier signature</div>
      <div class="line">Member signature</div>
    </div>
  </div>
  <script>window.onload=()=>{window.print(); setTimeout(()=>window.close(), 300);};<\/script>
</body>
</html>`;
  const w = window.open('', '_blank', 'width=900,height=720');
  if (!w) {
    alert('Popup blocked. Please allow popups for this site, then print again.');
    return;
  }
  w.document.open();
  w.document.write(html);
  w.document.close();
}



function tierIdsForReward(r) { return Array.isArray(r.tier_ids) ? r.tier_ids.map(Number).filter(Boolean) : String(r.tier_ids_csv || '').split(',').map(Number).filter(Boolean); }
function sponsorName(id) { const s = (rewardState.sponsors || []).find(x => Number(x.id) === Number(id)); return s ? s.sponsor_name : ''; }
function tierLabelList(ids) {
  const list = (ids || []).map(Number).filter(Boolean);
  if (!list.length) return '<span class="pill pill-green">All tiers</span>';
  return list.map(id => {
    const t = (rewardState.tiers || []).find(x => Number(x.id) === id);
    return `<span class="pill pill-muted">${Pyrk.esc(t ? (t.icon || '') + ' ' + t.tier_name : '#' + id)}</span>`;
  }).join('');
}
function fillRewardEnterpriseSelects() {
  const sponsor = document.getElementById('rewardSponsor');
  if (sponsor) sponsor.innerHTML = '<option value="">No sponsor</option>' + (rewardState.sponsors || []).filter(s => s.status !== 'inactive').map(s => `<option value="${Number(s.id)}">${Pyrk.esc(s.sponsor_name)}</option>`).join('');
  const tiers = document.getElementById('rewardTiers');
  if (tiers) tiers.innerHTML = (rewardState.tiers || []).filter(t => t.status !== 'inactive').map(t => `<option value="${Number(t.id)}">${Pyrk.esc(t.icon || '🏅')} ${Pyrk.esc(t.tier_name)}</option>`).join('');
}
function selectRewardTiers(ids) {
  const selected = (ids || []).map(Number).filter(Boolean);
  Array.from(document.getElementById('rewardTiers')?.options || []).forEach(o => o.selected = selected.includes(Number(o.value)));
}

function resetRewardForm() {
  const form = document.getElementById('rewardForm');
  if (!form) return;
  form.reset();
  document.getElementById('rewardId').value = '';
  document.getElementById('rewardFormTitle').textContent = 'Create prize';
  document.getElementById('rewardStatus').value = 'active';
  document.getElementById('rewardType').value = 'gift';
  if (document.getElementById('rewardSponsor')) document.getElementById('rewardSponsor').value = '';
  if (document.getElementById('rewardAvailableFrom')) document.getElementById('rewardAvailableFrom').value = '';
  if (document.getElementById('rewardAvailableUntil')) document.getElementById('rewardAvailableUntil').value = '';
  selectRewardTiers([]);
  Pyrk.toast('rewardMsg', {ok:true, message:''});
  document.getElementById('rewardName')?.focus();
}

function filteredRewards() {
  const q = (document.getElementById('rewardSearch')?.value || '').toLowerCase().trim();
  const status = document.getElementById('rewardStatusFilter')?.value || '';
  return (rewardState.rewards || []).filter(r => {
    const hay = `${r.reward_name || ''} ${r.description || ''} ${r.reward_type || ''} ${r.sponsor_name || ''}`.toLowerCase();
    return (!q || hay.includes(q)) && (!status || r.status === status);
  });
}

function filteredClaims() {
  const q = (document.getElementById('claimSearch')?.value || '').toLowerCase().trim();
  const status = document.getElementById('claimStatusFilter')?.value || '';
  return (rewardState.claims || []).filter(c => {
    const hay = `${c.full_name || ''} ${c.mobile || ''} ${c.email || ''} ${c.reward_name || ''} ${c.status || ''}`.toLowerCase();
    return (!q || hay.includes(q)) && (!status || c.status === status);
  });
}

function renderStats() {
  const rewards = rewardState.rewards || [];
  const claims = rewardState.claims || [];
  document.getElementById('rewardTotal').textContent = rewards.length;
  document.getElementById('rewardActive').textContent = rewards.filter(r => r.status === 'active').length;
  document.getElementById('claimOpen').textContent = claims.filter(c => ['requested','approved'].includes(c.status)).length;
  document.getElementById('claimFulfilled').textContent = claims.filter(c => c.status === 'fulfilled').length;
}

function renderRewards() {
  renderStats();
  const canManage = !!window.PYRK_CAN_MANAGE_LOYALTY;
  const grid = document.getElementById('rewardGrid');
  if (!grid) return;
  const rows = filteredRewards();
  grid.innerHTML = rows.map(r => `<article class="reward-rule-card enterprise-card pro-library-card">
    <div class="reward-card-icon">🎁</div>
    <div class="reward-card-body">
      <div class="inline-controls tiny-controls">${statusPill(r.status)}<span class="pill pill-muted">${Number(r.points_cost || 0)} pts</span><span class="pill pill-muted">Stock ${r.stock_quantity === null || r.stock_quantity === undefined ? '∞' : Number(r.stock_quantity)}</span>${r.sponsor_name ? `<span class="pill pill-muted">🤝 ${Pyrk.esc(r.sponsor_name)}</span>` : ''}</div>
      <strong>${Pyrk.esc(r.reward_name)}</strong>
      <p>${Pyrk.esc(r.description || 'No description')}</p><div class="inline-controls tiny-controls">${tierLabelList(tierIdsForReward(r))}</div>${(r.available_from || r.available_until) ? `<small class="muted">Available ${Pyrk.esc(r.available_from || 'now')} → ${Pyrk.esc(r.available_until || 'open')}</small>` : ''}
    </div>
    ${canManage ? `<button class="btn btn-light btn-small" type="button" onclick="editReward(${r.id})">Edit</button>` : ''}
  </article>`).join('') || '<div class="empty-state"><strong>No prizes found</strong><span>Change search/filter or create your first prize.</span></div>';
}

function renderClaims() {
  const body = document.getElementById('rewardClaimsBody');
  if (!body) return;
  const canManage = !!window.PYRK_CAN_MANAGE_LOYALTY;
  const rows = filteredClaims();
  body.innerHTML = rows.map(c => `<tr>
    <td><a class="identity-cell" href="members.php?open=${c.user_id}">${avatarHtml(c)}<div><strong>${Pyrk.esc(c.full_name)}</strong><small>${Pyrk.esc(c.mobile || c.email || '')}</small></div></a></td>
    <td><strong>${Pyrk.esc(c.reward_name)}</strong><small>${Pyrk.esc(c.reward_type || '')}</small></td>
    <td>${statusPill(c.status)}</td>
    <td><strong>${Number(c.points_spent || c.points_cost || 0)}</strong></td>
    <td>${formatDate(c.requested_at || c.created_at)}</td>
    <td><div class="inline-controls tiny-controls"><button class="btn btn-light btn-small" onclick="printPrizeClaim(${c.id})">Print claim</button>${canManage && ['requested','approved'].includes(c.status) ? `<button class="btn btn-light btn-small" onclick="updateClaim(${c.id},'approved')">Approve</button><button class="btn btn-small" onclick="updateClaim(${c.id},'fulfilled')">Fulfil</button><button class="btn btn-danger btn-small" onclick="updateClaim(${c.id},'rejected')">Reject/refund</button>` : '<span class="muted small">Closed</span>'}</div></td>
  </tr>`).join('') || '<tr><td colspan="6" class="muted">No prize claims found.</td></tr>';
}

window.editReward = function editReward(id) {
  const r = (rewardState.rewards || []).find(x => Number(x.id) === Number(id));
  if (!r) return;
  document.getElementById('rewardFormTitle').textContent = 'Edit prize';
  document.getElementById('rewardId').value = r.id;
  document.getElementById('rewardName').value = r.reward_name || '';
  document.getElementById('rewardType').value = r.reward_type || 'gift';
  document.getElementById('rewardPointsCost').value = r.points_cost || 0;
  document.getElementById('rewardStock').value = r.stock_quantity ?? '';
  document.getElementById('rewardStatus').value = r.status || 'active';
  document.getElementById('rewardDescription').value = r.description || '';
  document.getElementById('rewardInstructions').value = r.redemption_instructions || '';
  if (document.getElementById('rewardSponsor')) document.getElementById('rewardSponsor').value = r.sponsor_id || '';
  if (document.getElementById('rewardAvailableFrom')) document.getElementById('rewardAvailableFrom').value = r.available_from || '';
  if (document.getElementById('rewardAvailableUntil')) document.getElementById('rewardAvailableUntil').value = r.available_until || '';
  selectRewardTiers(tierIdsForReward(r));
  document.getElementById('rewardMsg').textContent = '';
  document.querySelector('.rewards-side-panel')?.scrollIntoView({behavior:'smooth', block:'start'});
};

window.updateClaim = async function updateClaim(id, status) {
  const label = status === 'fulfilled' ? 'mark this claim as fulfilled' : status;
  if (!confirm(`Are you sure you want to ${label}?`)) return;
  const notes = (status === 'fulfilled' || status === 'rejected') ? (prompt('Optional notes for this claim:', '') || '') : '';
  const res = await Pyrk.post('rewards.php', {action:'update_claim', claim_id:id, status, fulfilment_notes: notes});
  alert(res.message || (res.ok ? 'Updated.' : 'Failed.'));
  if (res.ok) await loadRewardsAdmin();
};

async function loadRewardsAdmin() {
  const res = await Pyrk.get('rewards.php', {action:'admin'});
  if (!res.ok) {
    document.getElementById('rewardGrid').innerHTML = `<div class="notice bad">${Pyrk.esc(res.message)}</div>`;
    return;
  }
  rewardState = res.data || {rewards: [], claims: [], tiers: [], sponsors: []};
  fillRewardEnterpriseSelects();
  renderRewards();
  renderClaims();
}

document.getElementById('rewardForm')?.addEventListener('submit', async e => {
  e.preventDefault();
  const fd = new FormData(e.currentTarget);
  fd.append('action', 'save_reward');
  fd.delete('tier_ids[]');
  Array.from(document.getElementById('rewardTiers')?.selectedOptions || []).forEach(o => fd.append('tier_ids[]', o.value));
  const res = await Pyrk.postForm('rewards.php', fd);
  Pyrk.toast('rewardMsg', res);
  if (res.ok) { resetRewardForm(); await loadRewardsAdmin(); }
});

document.getElementById('newPrizeBtn')?.addEventListener('click', resetRewardForm);
document.getElementById('resetRewardForm')?.addEventListener('click', resetRewardForm);
document.getElementById('rewardSearch')?.addEventListener('input', renderRewards);
document.getElementById('rewardStatusFilter')?.addEventListener('change', renderRewards);
document.getElementById('claimSearch')?.addEventListener('input', renderClaims);
document.getElementById('claimStatusFilter')?.addEventListener('change', renderClaims);

loadRewardsAdmin();
