let paymentMethods = [];

const pmEsc = value => Pyrk.esc(value ?? '');

function paymentMethodToast(res) {
  Pyrk.toast('paymentMethodMsg', res);
}

function methodCodeFromName(value) {
  return String(value || '').toLowerCase().trim().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 50);
}

function renderMethods() {
  const body = document.getElementById('paymentMethodsRows');
  if (!body) return;

  body.innerHTML = paymentMethods.map(m => `
    <tr>
      <td><strong>${pmEsc(m.name)}</strong></td>
      <td><code>${pmEsc(m.code)}</code></td>
      <td><span class="pill ${m.status === 'active' ? 'pill-green' : 'pill-muted'}">${pmEsc(m.status)}</span></td>
      <td>${Number(m.sort_order || 0)}</td>
      <td>${Number(m.usage_count || 0)}</td>
      <td class="table-actions">
        <button class="btn btn-light btn-small" type="button" data-edit-method="${Number(m.id)}">Edit</button>
        <button class="btn btn-danger btn-small" type="button" data-delete-method="${Number(m.id)}">${Number(m.usage_count || 0) > 0 ? 'Deactivate' : 'Delete'}</button>
      </td>
    </tr>
  `).join('') || '<tr><td colspan="6" class="muted">No payment methods found. Run the SQL migration first.</td></tr>';
}

async function loadMethods() {
  const res = await Pyrk.get('payment_methods.php', {action:'list'});
  if (!res.ok) {
    paymentMethodToast(res);
    document.getElementById('paymentMethodsRows').innerHTML = `<tr><td colspan="6" class="notice bad">${pmEsc(res.message)}</td></tr>`;
    return;
  }

  paymentMethods = res.data.methods || [];
  renderMethods();
}

function openMethodModal(method = null) {
  document.getElementById('methodId').value = method?.id || '';
  document.getElementById('methodName').value = method?.name || '';
  document.getElementById('methodCode').value = method?.code || '';
  document.getElementById('methodStatus').value = method?.status || 'active';
  document.getElementById('methodSort').value = method?.sort_order || 100;
  document.getElementById('methodModalTitle').textContent = method ? 'Edit method' : 'New method';
  Pyrk.openModal('paymentMethodModal');
}

document.getElementById('newMethodBtn')?.addEventListener('click', () => openMethodModal());
document.getElementById('refreshMethodsBtn')?.addEventListener('click', loadMethods);

document.getElementById('methodName')?.addEventListener('input', e => {
  const code = document.getElementById('methodCode');
  if (code && !code.dataset.touched) code.value = methodCodeFromName(e.target.value);
});
document.getElementById('methodCode')?.addEventListener('input', e => {
  e.target.dataset.touched = '1';
  e.target.value = methodCodeFromName(e.target.value);
});

document.getElementById('paymentMethodsRows')?.addEventListener('click', async e => {
  const edit = e.target.closest('[data-edit-method]');
  const del = e.target.closest('[data-delete-method]');

  if (edit) {
    const id = Number(edit.dataset.editMethod || 0);
    const method = paymentMethods.find(m => Number(m.id) === id);
    if (method) openMethodModal(method);
    return;
  }

  if (del) {
    const id = Number(del.dataset.deleteMethod || 0);
    const method = paymentMethods.find(m => Number(m.id) === id);
    if (!method) return;
    const msg = Number(method.usage_count || 0) > 0
      ? `Deactivate ${method.name}? It is already used by receipts, so it will not be deleted.`
      : `Delete ${method.name}?`;
    if (!confirm(msg)) return;

    const res = await Pyrk.post('payment_methods.php', {action:'delete', id});
    paymentMethodToast(res);
    if (res.ok) loadMethods();
  }
});

document.getElementById('paymentMethodForm')?.addEventListener('submit', async e => {
  e.preventDefault();
  const payload = {
    action: 'save',
    id: document.getElementById('methodId').value,
    name: document.getElementById('methodName').value,
    code: document.getElementById('methodCode').value,
    status: document.getElementById('methodStatus').value,
    sort_order: document.getElementById('methodSort').value
  };
  const res = await Pyrk.post('payment_methods.php', payload);
  paymentMethodToast(res);
  if (res.ok) {
    Pyrk.closeModal('paymentMethodModal');
    loadMethods();
  }
});

document.querySelectorAll('[data-close-modal]').forEach(btn => btn.addEventListener('click', () => Pyrk.closeModal(btn.dataset.closeModal)));
document.querySelectorAll('.modal-backdrop').forEach(modal => modal.addEventListener('click', e => {
  if (e.target === modal) Pyrk.closeModal(modal.id);
}));

loadMethods();
