const API = 'https://api.jb26.co.za/api';
const token = localStorage.getItem('token');

const headers = {
  'Authorization': 'Bearer ' + token,
  'Content-Type': 'application/json'
};

function loadPlans() {
  fetch(`${API}/modules/billing/plans.php`, { headers })
    .then(r => r.json())
    .then(r => {
      const body = document.querySelector('#plans tbody');
      body.innerHTML = '';
      r.data.forEach(p => {
        body.innerHTML += `
          <tr>
            <td>${p.code}</td>
            <td>${p.name}</td>
            <td>R ${p.price}</td>
            <td>${p.billing_cycle}</td>
          </tr>`;
      });
    });
}

function loadSubscriptions() {
  fetch(`${API}/modules/admin/subscriptions.php`, { headers })
    .then(r => r.json())
    .then(r => {
      const body = document.querySelector('#subs tbody');
      body.innerHTML = '';
      r.data.forEach(s => {
        body.innerHTML += `
          <tr>
            <td>${s.company}</td>
            <td>${s.plan_code}</td>
            <td>${s.status}</td>
            <td>${s.expires_at}</td>
            <td>
              <button onclick="cancelSub(${s.id})">Cancel</button>
            </td>
          </tr>`;
      });
    });
}

function loadPayments() {
  fetch(`${API}/modules/admin/payments.php`, { headers })
    .then(r => r.json())
    .then(r => {
      const body = document.querySelector('#payments tbody');
      body.innerHTML = '';
      r.data.forEach(p => {
        body.innerHTML += `
          <tr>
            <td>${p.reference}</td>
            <td>${p.company}</td>
            <td>${p.plan_code}</td>
            <td>R ${p.amount}</td>
            <td>${p.status}</td>
            <td>${p.created_at}</td>
          </tr>`;
      });
    });
}

function cancelSub(id) {
  if (!confirm('Cancel this subscription?')) return;

  fetch(`${API}/modules/admin/subscription_cancel.php`, {
    method: 'POST',
    headers,
    body: JSON.stringify({ id })
  }).then(() => loadSubscriptions());
}

loadPlans();
loadSubscriptions();
loadPayments();
