/* ============================================================
   AI Auto Reply Marketing — Admin Panel App Logic
   ============================================================ */

let currentAdmin = null;
let usersPage = 1, txnPage = 1, callLogsPage = 1, auditPage = 1;
let charts = {};

// ---------------------------------------------------------
// Toast helper
// ---------------------------------------------------------
function toast(message, type = 'success') {
  const el = document.createElement('div');
  el.className = `alert alert-${type === 'error' ? 'danger' : 'success'} shadow-sm mb-2`;
  el.style.borderRadius = '10px';
  el.innerText = message;
  document.getElementById('toastFloat').appendChild(el);
  setTimeout(() => el.remove(), 3500);
}

function fmtDate(str) {
  if (!str) return '-';
  const d = new Date(str.replace(' ', 'T'));
  return d.toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' }) +
    ' ' + d.toLocaleTimeString('en-IN', { hour: '2-digit', minute: '2-digit' });
}
function fmtMoney(n) { return '₹' + Number(n || 0).toLocaleString('en-IN', { minimumFractionDigits: 0 }); }
function initials(name) { return (name || 'A').trim().split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase(); }

// ---------------------------------------------------------
// Auth
// ---------------------------------------------------------
document.getElementById('togglePwd').addEventListener('click', () => {
  const inp = document.getElementById('loginPassword');
  const icon = document.getElementById('togglePwd');
  if (inp.type === 'password') { inp.type = 'text'; icon.className = 'bi bi-eye-slash position-absolute'; }
  else { inp.type = 'password'; icon.className = 'bi bi-eye position-absolute'; }
});

document.getElementById('loginForm').addEventListener('submit', async (e) => {
  e.preventDefault();
  const errBox = document.getElementById('loginError');
  const btn = document.getElementById('loginSubmitBtn');
  const spinner = document.getElementById('loginSpinner');
  errBox.classList.add('d-none');
  btn.disabled = true;
  spinner.classList.remove('d-none');

  try {
    const data = await API.post('/login.php', {
      email: document.getElementById('loginEmail').value,
      password: document.getElementById('loginPassword').value,
    });
    API.setToken(data.token);
    currentAdmin = data.admin;
    bootAdminApp();
  } catch (err) {
    errBox.innerText = err.message;
    errBox.classList.remove('d-none');
  } finally {
    btn.disabled = false;
    spinner.classList.add('d-none');
  }
});

document.getElementById('logoutBtn').addEventListener('click', async () => {
  try { await API.post('/logout.php'); } catch (e) {}
  API.setToken(null);
  window.location.reload();
});

async function checkExistingSession() {
  if (!API.getToken()) return;
  try {
    const data = await API.get('/me.php');
    currentAdmin = data.admin;
    bootAdminApp();
  } catch (err) {
    API.setToken(null);
  }
}

function bootAdminApp() {
  document.getElementById('loginScreen').classList.add('d-none');
  document.getElementById('adminApp').classList.remove('d-none');
  document.getElementById('adminNameLabel').innerText = currentAdmin.full_name || currentAdmin.email;
  document.getElementById('adminRoleLabel').innerText = currentAdmin.role;
  document.getElementById('adminAvatar').innerText = initials(currentAdmin.full_name);
  if (currentAdmin.role !== 'SUPER_ADMIN') {
    document.querySelector('[data-section="payments"]').style.display = 'none';
    document.querySelector('[data-section="smtp"]').style.display = 'none';
  }
  loadSection('dashboard');
}

// ---------------------------------------------------------
// Section navigation
// ---------------------------------------------------------
const sectionTitles = {
  dashboard: ['Dashboard', 'Live overview of your business'],
  users: ['Users', 'Manage customer accounts, licenses & devices'],
  templates: ['Templates', 'Auto-reply message presets'],
  banners: ['Banners', 'Dashboard slider promotions'],
  plans: ['Plans', 'Subscription pricing plans'],
  payments: ['Payment gateways', 'Razorpay, PhonePe & manual UPI configuration'],
  transactions: ['Transactions', 'Payment history & UTR approvals'],
  reports: ['Call reports', 'Auto-reply activity across all users'],
  audit: ['Audit logs', 'Every admin action, tracked'],
  smtp: ['SMTP', 'Outgoing email configuration'],
  settings: ['App settings', 'Legal pages, support info & branding'],
};

document.querySelectorAll('.nav-item[data-section]').forEach(btn => {
  btn.addEventListener('click', () => loadSection(btn.dataset.section));
});

function loadSection(name) {
  document.querySelectorAll('.nav-item[data-section]').forEach(b => b.classList.toggle('active', b.dataset.section === name));
  document.querySelectorAll('.admin-section').forEach(s => s.classList.remove('active'));
  document.getElementById('section-' + name).classList.add('active');
  document.getElementById('pageTitle').innerText = sectionTitles[name][0];
  document.getElementById('pageSubtitle').innerText = sectionTitles[name][1];
  document.getElementById('sidebar').classList.remove('open');

  const loaders = {
    dashboard: loadDashboard, users: () => loadUsers(1), templates: loadTemplates,
    banners: loadBanners, plans: loadPlans, payments: loadGateways,
    transactions: () => loadTransactions(1), reports: () => loadCallReports(1),
    audit: () => loadAuditLogs(1), smtp: loadSmtp, settings: loadAppSettings,
  };
  if (loaders[name]) loaders[name]();
}

document.getElementById('mobileToggle').addEventListener('click', () => {
  document.getElementById('sidebar').classList.toggle('open');
});

// ============================================================
// DASHBOARD
// ============================================================
async function loadDashboard() {
  try {
    const d = await API.get('/dashboard_stats.php');
    const cards = [
      ['Total users', d.users.total, 'bi-people', '#6C5CE7'],
      ['Active', d.users.active, 'bi-check-circle', '#17B26A'],
      ['Expired', d.users.expired, 'bi-clock-history', '#F79009'],
      ['Blocked', d.users.blocked, 'bi-slash-circle', '#F04438'],
      ['Trial users', d.users.trial, 'bi-hourglass-split', '#00D9C0'],
      ['Paid users', d.users.paid, 'bi-gem', '#6C5CE7'],
      ['Total revenue', fmtMoney(d.payments.total_revenue), 'bi-cash-stack', '#17B26A'],
      ['Pending payments', d.payments.pending_payments, 'bi-hourglass', '#F79009'],
      ['Total calls', d.calls.total, 'bi-telephone', '#6C5CE7'],
      ['Active banners', d.active_banners, 'bi-images', '#00D9C0'],
    ];
    document.getElementById('statsRow').innerHTML = cards.map(([label, value, icon, color]) => `
      <div class="col-6 col-lg-3">
        <div class="stat-card d-flex justify-content-between align-items-start">
          <div><div class="stat-label">${label}</div><div class="stat-value">${value}</div></div>
          <div class="stat-icon" style="background:${color}"><i class="bi ${icon}"></i></div>
        </div>
      </div>`).join('');

    renderChart('chartGrowth', d.charts.user_growth, '#6C5CE7', 'New users');
    renderChart('chartRevenue', d.charts.revenue, '#17B26A', 'Revenue', true);
    renderChart('chartCalls', d.charts.call_activity, '#00D9C0', 'Calls');
  } catch (err) { toast(err.message, 'error'); }
}

function renderChart(canvasId, rows, color, label, isMoney = false) {
  const ctx = document.getElementById(canvasId);
  if (charts[canvasId]) charts[canvasId].destroy();
  const labels = rows.map(r => new Date(r.d).toLocaleDateString('en-IN', { day: '2-digit', month: 'short' }));
  const values = rows.map(r => isMoney ? Number(r.total) : Number(r.c));
  charts[canvasId] = new Chart(ctx, {
    type: 'line',
    data: { labels, datasets: [{ label, data: values, borderColor: color, backgroundColor: color + '22', fill: true, tension: 0.35, pointRadius: 2 }] },
    options: { plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true } } },
  });
}

// ============================================================
// USERS
// ============================================================
let userSearchTimer = null;
document.getElementById('userSearch').addEventListener('input', () => {
  clearTimeout(userSearchTimer);
  userSearchTimer = setTimeout(() => loadUsers(1), 400);
});
document.getElementById('userStatusFilter').addEventListener('change', () => loadUsers(1));

async function loadUsers(page) {
  usersPage = page;
  const search = document.getElementById('userSearch').value;
  const status = document.getElementById('userStatusFilter').value;
  try {
    const data = await API.get(`/users.php?page=${page}&search=${encodeURIComponent(search)}&status=${status}`);
    renderUsersTable(data.users);
    renderPagination('usersPagination', data.pagination, loadUsers);
  } catch (err) { toast(err.message, 'error'); }
}

function renderUsersTable(users) {
  const body = document.getElementById('usersTableBody');
  if (!users.length) { body.innerHTML = `<tr><td colspan="7" class="empty-state">No users found.</td></tr>`; return; }

  body.innerHTML = users.map(u => {
    const expiry = new Date(u.activated_at); expiry.setDate(expiry.getDate() + Number(u.validity_days));
    const isExpired = expiry < new Date();
    const statusBadge = u.is_blocked == 1 ? `<span class="badge-soft badge-danger">Blocked</span>`
      : isExpired ? `<span class="badge-soft badge-warning">Expired</span>`
      : `<span class="badge-soft badge-success">Active</span>`;

    return `<tr>
      <td><div class="fw-semibold">${u.full_name || '-'}</div><div class="text-muted" style="font-size:11.5px;">${u.business_name || ''}</div></td>
      <td><div>${u.email}</div><div class="text-muted" style="font-size:11.5px;">${u.phone_number || '-'}</div></td>
      <td><span class="badge-soft badge-info">${u.license_key}</span></td>
      <td>${u.validity_days} days<div class="text-muted" style="font-size:11px;">till ${expiry.toLocaleDateString('en-IN')}</div></td>
      <td>${statusBadge}</td>
      <td>${u.active_device_id ? '<i class="bi bi-phone-fill text-success"></i> Locked' : '<i class="bi bi-phone text-muted"></i> None'}</td>
      <td>
        <div class="dropdown">
          <button class="btn btn-sm btn-soft" data-bs-toggle="dropdown"><i class="bi bi-three-dots"></i></button>
          <ul class="dropdown-menu dropdown-menu-end">
            <li><a class="dropdown-item" href="#" onclick="viewUser(${u.id});return false;">View details</a></li>
            <li><a class="dropdown-item" href="#" onclick="toggleUserBlock(${u.id}, ${u.is_blocked == 1 ? 0 : 1});return false;">${u.is_blocked == 1 ? 'Unblock' : 'Block'}</a></li>
            <li><a class="dropdown-item" href="#" onclick="resetUserPassword(${u.id});return false;">Reset password</a></li>
            <li><a class="dropdown-item" href="#" onclick="resetUserDevice(${u.id});return false;">Reset device lock</a></li>
            <li><a class="dropdown-item text-danger" href="#" onclick="deleteUser(${u.id});return false;">Delete</a></li>
          </ul>
        </div>
      </td>
    </tr>`;
  }).join('');
}

function renderPagination(containerId, p, loaderFn) {
  const el = document.getElementById(containerId);
  el.innerHTML = `
    <div class="text-muted small">Page ${p.page} of ${p.total_pages || 1} — ${p.total} total</div>
    <div class="d-flex gap-8">
      <button class="btn btn-sm btn-soft" ${p.page <= 1 ? 'disabled' : ''} onclick="(${loaderFn.name})(${p.page - 1})">Previous</button>
      <button class="btn btn-sm btn-soft" ${p.page >= p.total_pages ? 'disabled' : ''} onclick="(${loaderFn.name})(${p.page + 1})">Next</button>
    </div>`;
}

async function viewUser(id) {
  const modal = new bootstrap.Modal(document.getElementById('userDetailModal'));
  document.getElementById('userDetailBody').innerHTML = '<div class="text-center py-4"><span class="spinner-border spinner-brand"></span></div>';
  modal.show();
  try {
    const data = await API.get('/users.php?id=' + id);
    const u = data.user;
    document.getElementById('userDetailBody').innerHTML = `
      <div class="row g-3">
        <div class="col-md-6">
          <h6 class="fw-bold">Profile</h6>
          <table class="table-modern"><tbody>
            <tr><td class="text-muted">Name</td><td>${u.full_name || '-'}</td></tr>
            <tr><td class="text-muted">Email</td><td>${u.email}</td></tr>
            <tr><td class="text-muted">Phone</td><td>${u.phone_number || '-'}</td></tr>
            <tr><td class="text-muted">Business</td><td>${u.business_name || '-'}</td></tr>
            <tr><td class="text-muted">License</td><td>${u.license_key}</td></tr>
            <tr><td class="text-muted">Validity</td><td>${u.validity_days} days</td></tr>
            <tr><td class="text-muted">Joined</td><td>${fmtDate(u.created_at)}</td></tr>
            <tr><td class="text-muted">Last login</td><td>${fmtDate(u.last_login)}</td></tr>
          </tbody></table>
          <div class="d-flex gap-8 mt-2">
            <input type="number" id="extendDaysInput" class="form-control form-control-sm" style="width:100px;" placeholder="Days">
            <button class="btn btn-sm btn-brand" onclick="extendUserPlan(${u.id})">Extend / change validity</button>
          </div>
        </div>
        <div class="col-md-6">
          <h6 class="fw-bold">Recent calls</h6>
          <div style="max-height:160px;overflow:auto;">
            ${data.recent_calls.length ? data.recent_calls.map(c => `<div class="small border-bottom py-1">${c.phone_number} — <span class="badge-soft badge-neutral">${c.status}</span></div>`).join('') : '<div class="text-muted small">No calls yet.</div>'}
          </div>
          <h6 class="fw-bold mt-3">Recent payments</h6>
          <div style="max-height:160px;overflow:auto;">
            ${data.recent_payments.length ? data.recent_payments.map(p => `<div class="small border-bottom py-1">${p.plan_name} — ${fmtMoney(p.amount)} <span class="badge-soft badge-neutral">${p.status}</span></div>`).join('') : '<div class="text-muted small">No payments yet.</div>'}
          </div>
        </div>
      </div>`;
  } catch (err) { toast(err.message, 'error'); }
}

async function extendUserPlan(id) {
  const days = document.getElementById('extendDaysInput').value;
  if (!days) return toast('Enter number of days first.', 'error');
  try {
    await API.patch(`/users.php?id=${id}&action=plan`, { validity_days: Number(days) });
    toast('Plan updated.');
    bootstrap.Modal.getInstance(document.getElementById('userDetailModal')).hide();
    loadUsers(usersPage);
  } catch (err) { toast(err.message, 'error'); }
}

async function toggleUserBlock(id, blocked) {
  try {
    await API.patch(`/users.php?id=${id}&action=status`, { is_blocked: blocked });
    toast(blocked ? 'User blocked.' : 'User unblocked.');
    loadUsers(usersPage);
  } catch (err) { toast(err.message, 'error'); }
}

async function resetUserPassword(id) {
  if (!confirm('Generate a new password for this user?')) return;
  try {
    const data = await API.post('/users.php?action=reset-password', { id });
    alert('New password: ' + data.new_password + '\n\nShare this with the user securely.');
  } catch (err) { toast(err.message, 'error'); }
}

async function resetUserDevice(id) {
  if (!confirm('Reset device lock? User will be able to log in on a new device.')) return;
  try {
    await API.post('/users.php?action=reset-device', { id });
    toast('Device lock reset.');
    loadUsers(usersPage);
  } catch (err) { toast(err.message, 'error'); }
}

async function deleteUser(id) {
  if (!confirm('Permanently delete this user? This cannot be undone.')) return;
  try {
    await API.del('/users.php?id=' + id);
    toast('User deleted.');
    loadUsers(usersPage);
  } catch (err) { toast(err.message, 'error'); }
}

document.getElementById('userCreateSubmitBtn').addEventListener('click', async () => {
  const payload = {
    full_name: document.getElementById('ucFullName').value,
    email: document.getElementById('ucEmail').value,
    phone_number: document.getElementById('ucPhone').value,
    business_name: document.getElementById('ucBusiness').value,
    plan_id: document.getElementById('ucPlan').value,
  };
  if (!payload.full_name || !payload.email || !payload.plan_id) return toast('Fill all required fields.', 'error');
  try {
    const data = await API.post('/users.php', payload);
    alert(`User created!\n\nEmail: ${data.email}\nTemp password: ${data.temp_password}\nLicense: ${data.license_key}\n\nShare securely with the user.`);
    bootstrap.Modal.getInstance(document.getElementById('userCreateModal')).hide();
    document.getElementById('userCreateForm').reset();
    loadUsers(1);
  } catch (err) { toast(err.message, 'error'); }
});

async function populatePlanDropdown(selectId) {
  try {
    const data = await API.get('/plans.php');
    document.getElementById(selectId).innerHTML = data.plans.filter(p => p.is_active == 1)
      .map(p => `<option value="${p.id}">${p.plan_name} — ${fmtMoney(p.price)} / ${p.validity_days}d</option>`).join('');
  } catch (err) {}
}
document.getElementById('userCreateModal').addEventListener('show.bs.modal', () => populatePlanDropdown('ucPlan'));

// ============================================================
// TEMPLATES
// ============================================================
async function loadTemplates() {
  try {
    const data = await API.get('/templates.php?global_only=1&per_page=100');
    const grid = document.getElementById('templatesGrid');
    if (!data.templates.length) { grid.innerHTML = `<div class="empty-state">No templates yet. Create your first one.</div>`; return; }
    grid.innerHTML = data.templates.map(t => `
      <div class="col-md-6 col-lg-4">
        <div class="card-soft h-100">
          <div class="d-flex justify-content-between align-items-start mb-2">
            <span class="badge-soft badge-info">${t.category}</span>
            <span class="badge-soft ${t.is_active == 1 ? 'badge-success' : 'badge-neutral'}">${t.is_active == 1 ? 'Active' : 'Disabled'}</span>
          </div>
          <div class="fw-bold mb-1">${t.title}</div>
          <div class="text-muted small mb-2" style="min-height:40px;">${(t.message_text || '').slice(0, 90)}...</div>
          <div class="d-flex gap-8 flex-wrap mb-2">
            <span class="badge-soft badge-neutral">${t.event_type}</span>
            <span class="badge-soft badge-neutral">${t.channel}</span>
          </div>
          <div class="d-flex gap-8 mt-auto pt-2">
            <button class="btn btn-sm btn-soft flex-fill" onclick="editTemplate(${t.id})">Edit</button>
            <button class="btn btn-sm btn-soft" onclick="toggleTemplate(${t.id}, ${t.is_active == 1 ? 0 : 1})"><i class="bi bi-toggle2-on"></i></button>
            <button class="btn btn-sm btn-soft text-danger" onclick="deleteTemplate(${t.id})"><i class="bi bi-trash"></i></button>
          </div>
        </div>
      </div>`).join('');
  } catch (err) { toast(err.message, 'error'); }
}

function openTemplateModal() {
  document.getElementById('templateModalTitle').innerText = 'New template';
  document.getElementById('templateForm').reset();
  document.getElementById('tplId').value = '';
}

async function editTemplate(id) {
  try {
    const data = await API.get('/templates.php?id=' + id);
    const t = data.template;
    document.getElementById('templateModalTitle').innerText = 'Edit template';
    document.getElementById('tplId').value = t.id;
    document.getElementById('tplTitle').value = t.title;
    document.getElementById('tplEventType').value = t.event_type;
    document.getElementById('tplChannel').value = t.channel;
    document.getElementById('tplCategory').value = t.category;
    document.getElementById('tplMediaType').value = t.media_type;
    document.getElementById('tplMessage').value = t.message_text;
    document.getElementById('tplWaMessage').value = t.whatsapp_message_text || '';
    document.getElementById('tplLink').value = t.link_url || '';
    new bootstrap.Modal(document.getElementById('templateModal')).show();
  } catch (err) { toast(err.message, 'error'); }
}

document.getElementById('templateSubmitBtn').addEventListener('click', async () => {
  const id = document.getElementById('tplId').value;
  const fileInput = document.getElementById('tplAttachment');
  const hasFile = fileInput.files.length > 0;

  try {
    if (id) {
      await API.put('/templates.php?id=' + id, {
        title: document.getElementById('tplTitle').value,
        message_text: document.getElementById('tplMessage').value,
        whatsapp_message_text: document.getElementById('tplWaMessage').value,
        event_type: document.getElementById('tplEventType').value,
        channel: document.getElementById('tplChannel').value,
        category: document.getElementById('tplCategory').value,
        media_type: document.getElementById('tplMediaType').value,
        link_url: document.getElementById('tplLink').value,
      });
    } else {
      if (hasFile) {
        const fd = new FormData();
        fd.append('title', document.getElementById('tplTitle').value);
        fd.append('message_text', document.getElementById('tplMessage').value);
        fd.append('whatsapp_message_text', document.getElementById('tplWaMessage').value);
        fd.append('event_type', document.getElementById('tplEventType').value);
        fd.append('channel', document.getElementById('tplChannel').value);
        fd.append('category', document.getElementById('tplCategory').value);
        fd.append('media_type', document.getElementById('tplMediaType').value);
        fd.append('link_url', document.getElementById('tplLink').value);
        fd.append('attachment', fileInput.files[0]);
        await API.post('/templates.php', fd, true);
      } else {
        await API.post('/templates.php', {
          title: document.getElementById('tplTitle').value,
          message_text: document.getElementById('tplMessage').value,
          whatsapp_message_text: document.getElementById('tplWaMessage').value,
          event_type: document.getElementById('tplEventType').value,
          channel: document.getElementById('tplChannel').value,
          category: document.getElementById('tplCategory').value,
          media_type: document.getElementById('tplMediaType').value,
          link_url: document.getElementById('tplLink').value,
        });
      }
    }
    toast('Template saved.');
    bootstrap.Modal.getInstance(document.getElementById('templateModal')).hide();
    loadTemplates();
  } catch (err) { toast(err.message, 'error'); }
});

async function toggleTemplate(id, active) {
  try { await API.patch(`/templates.php?id=${id}&action=status`, { is_active: active }); loadTemplates(); }
  catch (err) { toast(err.message, 'error'); }
}
async function deleteTemplate(id) {
  if (!confirm('Delete this template?')) return;
  try { await API.del('/templates.php?id=' + id); toast('Template deleted.'); loadTemplates(); }
  catch (err) { toast(err.message, 'error'); }
}

// ============================================================
// BANNERS
// ============================================================
let bannersOrderCache = [];

async function loadBanners() {
  try {
    const data = await API.get('/banners.php');
    bannersOrderCache = data.banners.map(b => b.id);
    const grid = document.getElementById('bannersGrid');
    if (!data.banners.length) { grid.innerHTML = `<div class="empty-state">No banners yet.</div>`; return; }
    grid.innerHTML = data.banners.map((b, idx) => `
      <div class="col-md-6 col-lg-4">
        <div class="card-soft h-100">
          <img src="${b.image_url}" style="width:100%;height:120px;object-fit:cover;border-radius:10px;" onerror="this.style.display='none'">
          <div class="d-flex justify-content-between align-items-start mt-2">
            <div class="fw-bold">${b.title}</div>
            <span class="badge-soft badge-neutral">#${idx + 1}</span>
          </div>
          <div class="text-muted small mb-2">${(b.description || '').slice(0, 70)}</div>
          <span class="badge-soft ${b.is_active == 1 ? 'badge-success' : 'badge-neutral'}">${b.is_active == 1 ? 'Active' : 'Disabled'}</span>
          <div class="d-flex gap-8 mt-2">
            <button class="btn btn-sm btn-soft" title="Move up" ${idx === 0 ? 'disabled' : ''} onclick="moveBanner(${b.id}, -1)"><i class="bi bi-arrow-up"></i></button>
            <button class="btn btn-sm btn-soft" title="Move down" ${idx === data.banners.length - 1 ? 'disabled' : ''} onclick="moveBanner(${b.id}, 1)"><i class="bi bi-arrow-down"></i></button>
            <button class="btn btn-sm btn-soft flex-fill" onclick="editBanner(${b.id})">Edit</button>
            <button class="btn btn-sm btn-soft" onclick="toggleBanner(${b.id}, ${b.is_active == 1 ? 0 : 1})"><i class="bi bi-toggle2-on"></i></button>
            <button class="btn btn-sm btn-soft text-danger" onclick="deleteBanner(${b.id})"><i class="bi bi-trash"></i></button>
          </div>
        </div>
      </div>`).join('');
  } catch (err) { toast(err.message, 'error'); }
}

async function moveBanner(id, direction) {
  const idx = bannersOrderCache.indexOf(id);
  const swapIdx = idx + direction;
  if (swapIdx < 0 || swapIdx >= bannersOrderCache.length) return;
  [bannersOrderCache[idx], bannersOrderCache[swapIdx]] = [bannersOrderCache[swapIdx], bannersOrderCache[idx]];
  try {
    await API.patch('/banners.php?action=reorder', { order: bannersOrderCache });
    loadBanners();
  } catch (err) { toast(err.message, 'error'); }
}

function openBannerModal() {
  document.getElementById('bannerModalTitle').innerText = 'New banner';
  document.getElementById('bannerForm').reset();
  document.getElementById('bnrId').value = '';
}

async function editBanner(id) {
  const data = await API.get('/banners.php');
  const b = data.banners.find(x => x.id == id);
  if (!b) return;
  document.getElementById('bannerModalTitle').innerText = 'Edit banner';
  document.getElementById('bnrId').value = b.id;
  document.getElementById('bnrTitle').value = b.title;
  document.getElementById('bnrDescription').value = b.description || '';
  document.getElementById('bnrBtnText').value = b.button_text || '';
  document.getElementById('bnrBtnUrl').value = b.button_url || '';
  new bootstrap.Modal(document.getElementById('bannerModal')).show();
}

document.getElementById('bannerSubmitBtn').addEventListener('click', async () => {
  const id = document.getElementById('bnrId').value;
  const fileInput = document.getElementById('bnrImage');
  try {
    if (id) {
      await API.put('/banners.php?id=' + id, {
        title: document.getElementById('bnrTitle').value,
        description: document.getElementById('bnrDescription').value,
        button_text: document.getElementById('bnrBtnText').value,
        button_url: document.getElementById('bnrBtnUrl').value,
      });
    } else {
      const fd = new FormData();
      fd.append('title', document.getElementById('bnrTitle').value);
      fd.append('description', document.getElementById('bnrDescription').value);
      fd.append('button_text', document.getElementById('bnrBtnText').value);
      fd.append('button_url', document.getElementById('bnrBtnUrl').value);
      if (fileInput.files.length) fd.append('image', fileInput.files[0]);
      await API.post('/banners.php', fd, true);
    }
    toast('Banner saved.');
    bootstrap.Modal.getInstance(document.getElementById('bannerModal')).hide();
    loadBanners();
  } catch (err) { toast(err.message, 'error'); }
});

async function toggleBanner(id, active) {
  try { await API.patch(`/banners.php?id=${id}&action=status`, { is_active: active }); loadBanners(); }
  catch (err) { toast(err.message, 'error'); }
}
async function deleteBanner(id) {
  if (!confirm('Delete this banner?')) return;
  try { await API.del('/banners.php?id=' + id); toast('Banner deleted.'); loadBanners(); }
  catch (err) { toast(err.message, 'error'); }
}

// ============================================================
// PLANS
// ============================================================
async function loadPlans() {
  try {
    const data = await API.get('/plans.php');
    const grid = document.getElementById('plansGrid');
    if (!data.plans.length) { grid.innerHTML = `<div class="empty-state">No plans yet.</div>`; return; }
    grid.innerHTML = data.plans.map(p => `
      <div class="col-md-6 col-lg-4">
        <div class="card-soft h-100">
          <div class="d-flex justify-content-between align-items-start mb-2">
            <div class="fw-bold">${p.plan_name}</div>
            <span class="badge-soft ${p.is_active == 1 ? 'badge-success' : 'badge-neutral'}">${p.is_active == 1 ? 'Active' : 'Disabled'}</span>
          </div>
          <div style="font-size:24px;font-weight:700;">${fmtMoney(p.price)}</div>
          <div class="text-muted small mb-2">${p.validity_days} days validity</div>
          <div class="text-muted small mb-2">${p.description || ''}</div>
          <div class="d-flex gap-8 mt-auto pt-2">
            <button class="btn btn-sm btn-soft flex-fill" onclick="editPlan(${p.id})">Edit</button>
            <button class="btn btn-sm btn-soft" onclick="togglePlan(${p.id}, ${p.is_active == 1 ? 0 : 1})"><i class="bi bi-toggle2-on"></i></button>
            <button class="btn btn-sm btn-soft text-danger" onclick="deletePlan(${p.id})"><i class="bi bi-trash"></i></button>
          </div>
        </div>
      </div>`).join('');
  } catch (err) { toast(err.message, 'error'); }
}

function openPlanModal() {
  document.getElementById('planModalTitle').innerText = 'New plan';
  document.getElementById('planForm').reset();
  document.getElementById('planId').value = '';
}

async function editPlan(id) {
  const data = await API.get('/plans.php');
  const p = data.plans.find(x => x.id == id);
  if (!p) return;
  document.getElementById('planModalTitle').innerText = 'Edit plan';
  document.getElementById('planId').value = p.id;
  document.getElementById('planName').value = p.plan_name;
  document.getElementById('planPrice').value = p.price;
  document.getElementById('planValidity').value = p.validity_days;
  document.getElementById('planDescription').value = p.description || '';
  new bootstrap.Modal(document.getElementById('planModal')).show();
}

document.getElementById('planSubmitBtn').addEventListener('click', async () => {
  const id = document.getElementById('planId').value;
  const payload = {
    plan_name: document.getElementById('planName').value,
    price: document.getElementById('planPrice').value,
    validity_days: document.getElementById('planValidity').value,
    description: document.getElementById('planDescription').value,
  };
  try {
    if (id) await API.put('/plans.php?id=' + id, payload);
    else await API.post('/plans.php', payload);
    toast('Plan saved.');
    bootstrap.Modal.getInstance(document.getElementById('planModal')).hide();
    loadPlans();
  } catch (err) { toast(err.message, 'error'); }
});

async function togglePlan(id, active) {
  try { await API.patch(`/plans.php?id=${id}&action=status`, { is_active: active }); loadPlans(); }
  catch (err) { toast(err.message, 'error'); }
}
async function deletePlan(id) {
  if (!confirm('Delete this plan?')) return;
  try { await API.del('/plans.php?id=' + id); toast('Plan deleted.'); loadPlans(); }
  catch (err) { toast(err.message, 'error'); }
}

// ============================================================
// PAYMENT GATEWAYS
// ============================================================
async function loadGateways() {
  try {
    const data = await API.get('/payment_gateways.php');
    const grid = document.getElementById('gatewaysGrid');
    grid.innerHTML = data.gateways.map(g => `
      <div class="col-md-6 col-lg-4">
        <div class="card-soft h-100">
          <div class="d-flex justify-content-between align-items-start mb-2">
            <div class="fw-bold">${g.gateway_name.replace('_', ' ')}</div>
            <span class="badge-soft ${g.is_active == 1 ? 'badge-success' : 'badge-neutral'}">${g.is_active == 1 ? 'Live' : 'Off'}</span>
          </div>
          <div class="text-muted small mb-1">Mode: ${g.mode}</div>
          <div class="text-muted small mb-1">UPI: ${g.upi_id || '-'}</div>
          <div class="d-flex gap-8 mt-2">
            <button class="btn btn-sm btn-soft flex-fill" onclick="editGateway(${g.id}, '${g.gateway_name}')">Configure</button>
            <button class="btn btn-sm btn-soft" onclick="toggleGateway(${g.id}, ${g.is_active == 1 ? 0 : 1})">${g.is_active == 1 ? 'Turn off' : 'Turn on'}</button>
          </div>
        </div>
      </div>`).join('');
  } catch (err) { toast(err.message, 'error'); }
}

let editingGatewayId = null;
async function editGateway(id, name) {
  editingGatewayId = id;
  const data = await API.get('/payment_gateways.php');
  const g = data.gateways.find(x => x.id == id);
  document.getElementById('gatewayModalTitle').innerText = 'Configure ' + name.replace('_', ' ');

  let fields = '';
  if (name === 'RAZORPAY') {
    fields = `
      <div class="mb-2"><label class="form-label">Mode</label><select id="gwMode" class="form-select"><option value="TEST" ${g.mode==='TEST'?'selected':''}>Test</option><option value="LIVE" ${g.mode==='LIVE'?'selected':''}>Live</option></select></div>
      <div class="mb-2"><label class="form-label">Key ID</label><input type="text" id="gwKeyId" class="form-control" value="${g.key_id || ''}"></div>
      <div class="mb-2"><label class="form-label">Key secret</label><input type="text" id="gwKeySecret" class="form-control" value="${g.key_secret || ''}"></div>
      <div class="mb-2"><label class="form-label">Webhook secret</label><input type="text" id="gwWebhookSecret" class="form-control" value="${g.webhook_secret || ''}"></div>`;
  } else if (name === 'PHONEPE') {
    fields = `
      <div class="mb-2"><label class="form-label">Mode</label><select id="gwMode" class="form-select"><option value="TEST" ${g.mode==='TEST'?'selected':''}>Test</option><option value="LIVE" ${g.mode==='LIVE'?'selected':''}>Live</option></select></div>
      <div class="mb-2"><label class="form-label">Merchant ID</label><input type="text" id="gwMerchantId" class="form-control" value="${g.merchant_id || ''}"></div>
      <div class="mb-2"><label class="form-label">Salt key</label><input type="text" id="gwSaltKey" class="form-control" value="${g.salt_key || ''}"></div>
      <div class="mb-2"><label class="form-label">Salt index</label><input type="number" id="gwSaltIndex" class="form-control" value="${g.salt_index || 1}"></div>`;
  } else {
    fields = `
      <div class="mb-2"><label class="form-label">UPI ID</label><input type="text" id="gwUpiId" class="form-control" value="${g.upi_id || ''}"></div>
      <div class="mb-2"><label class="form-label">UPI display name</label><input type="text" id="gwUpiName" class="form-control" value="${g.upi_name || ''}"></div>
      <div class="mb-2"><label class="form-label">QR code image</label><input type="file" id="gwQrImage" class="form-control"></div>
      <div class="mb-2"><label class="form-label">Instructions</label><textarea id="gwInstructions" class="form-control" rows="2">${g.instructions || ''}</textarea></div>`;
  }
  document.getElementById('gatewayModalBody').innerHTML = fields;
  document.getElementById('gatewaySubmitBtn').dataset.gatewayName = name;
  new bootstrap.Modal(document.getElementById('gatewayModal')).show();
}

document.getElementById('gatewaySubmitBtn').addEventListener('click', async () => {
  const name = document.getElementById('gatewaySubmitBtn').dataset.gatewayName;
  try {
    if (name === 'MANUAL_UPI') {
      const fd = new FormData();
      fd.append('upi_id', document.getElementById('gwUpiId').value);
      fd.append('upi_name', document.getElementById('gwUpiName').value);
      fd.append('instructions', document.getElementById('gwInstructions').value);
      const fileInput = document.getElementById('gwQrImage');
      if (fileInput.files.length) fd.append('qr_image', fileInput.files[0]);
      await API.put('/payment_gateways.php?id=' + editingGatewayId, fd, true);
    } else if (name === 'RAZORPAY') {
      await API.put('/payment_gateways.php?id=' + editingGatewayId, {
        mode: document.getElementById('gwMode').value,
        key_id: document.getElementById('gwKeyId').value,
        key_secret: document.getElementById('gwKeySecret').value,
        webhook_secret: document.getElementById('gwWebhookSecret').value,
      });
    } else {
      await API.put('/payment_gateways.php?id=' + editingGatewayId, {
        mode: document.getElementById('gwMode').value,
        merchant_id: document.getElementById('gwMerchantId').value,
        salt_key: document.getElementById('gwSaltKey').value,
        salt_index: document.getElementById('gwSaltIndex').value,
      });
    }
    toast('Gateway configuration saved.');
    bootstrap.Modal.getInstance(document.getElementById('gatewayModal')).hide();
    loadGateways();
  } catch (err) { toast(err.message, 'error'); }
});

async function toggleGateway(id, active) {
  try { await API.patch(`/payment_gateways.php?id=${id}&action=status`, { is_active: active }); loadGateways(); }
  catch (err) { toast(err.message, 'error'); }
}

// ============================================================
// TRANSACTIONS
// ============================================================
document.getElementById('txnStatusFilter').addEventListener('change', () => loadTransactions(1));

async function loadTransactions(page) {
  txnPage = page;
  const status = document.getElementById('txnStatusFilter').value;
  try {
    const data = await API.get(`/transactions.php?page=${page}&status=${status}`);
    const body = document.getElementById('txnTableBody');
    if (!data.transactions.length) { body.innerHTML = `<tr><td colspan="8" class="empty-state">No transactions found.</td></tr>`; return; }
    body.innerHTML = data.transactions.map(t => `
      <tr>
        <td>${t.user_email}</td>
        <td>${t.plan_name}</td>
        <td>${fmtMoney(t.amount)}</td>
        <td>${t.gateway}</td>
        <td>${t.utr_number || t.payment_id || '-'}</td>
        <td><span class="badge-soft ${t.status === 'PENDING' ? 'badge-warning' : (t.status === 'VERIFIED' || t.status === 'SUCCESS') ? 'badge-success' : 'badge-danger'}">${t.status}</span></td>
        <td>${fmtDate(t.created_at)}</td>
        <td>${t.status === 'PENDING' ? `
          <button class="btn btn-sm btn-soft text-success" onclick="updateTxnStatus(${t.id}, 'VERIFIED')">Approve</button>
          <button class="btn btn-sm btn-soft text-danger" onclick="updateTxnStatus(${t.id}, 'REJECTED')">Reject</button>` : ''}
        </td>
      </tr>`).join('');
    renderPagination('txnPagination', data.pagination, loadTransactions);
  } catch (err) { toast(err.message, 'error'); }
}

async function updateTxnStatus(id, status) {
  if (!confirm(`Mark this transaction as ${status}?`)) return;
  try {
    await API.patch(`/transactions.php?id=${id}&action=status`, { status });
    toast('Transaction updated.');
    loadTransactions(txnPage);
  } catch (err) { toast(err.message, 'error'); }
}

// ============================================================
// CALL REPORTS
// ============================================================
let reportFilterTimer = null;
document.getElementById('reportSearch').addEventListener('input', () => {
  clearTimeout(reportFilterTimer);
  reportFilterTimer = setTimeout(() => loadCallReports(1), 400);
});
document.getElementById('reportStatusFilter').addEventListener('change', () => loadCallReports(1));
document.getElementById('reportUserEmail').addEventListener('input', () => {
  clearTimeout(reportFilterTimer);
  reportFilterTimer = setTimeout(() => loadCallReports(1), 400);
});

async function loadCallReports(page) {
  callLogsPage = page;
  const search = document.getElementById('reportSearch').value;
  const status = document.getElementById('reportStatusFilter').value;
  const userEmail = document.getElementById('reportUserEmail').value;
  try {
    const data = await API.get(`/reports_calls.php?page=${page}&search=${encodeURIComponent(search)}&status=${encodeURIComponent(status)}&user_email=${encodeURIComponent(userEmail)}`);
    const summaryRow = document.getElementById('reportsSummaryRow');
    summaryRow.innerHTML = data.summary.by_status.map(s => `
      <div class="col-6 col-lg-3">
        <div class="stat-card"><div class="stat-label">${s.status}</div><div class="stat-value">${s.total}</div></div>
      </div>`).join('');

    const body = document.getElementById('callLogsTableBody');
    if (!data.logs.length) { body.innerHTML = `<tr><td colspan="7" class="empty-state">No call logs yet.</td></tr>`; return; }
    body.innerHTML = data.logs.map(l => `
      <tr>
        <td>${l.phone_number}</td>
        <td>${l.caller_name || '-'}</td>
        <td><span class="badge-soft badge-neutral">${l.call_type}</span></td>
        <td>${l.status}</td>
        <td>${l.channel_used}</td>
        <td>${l.template_title || '-'}</td>
        <td>${fmtDate(l.created_at)}</td>
      </tr>`).join('');
    renderPagination('callLogsPagination', data.pagination, loadCallReports);
  } catch (err) { toast(err.message, 'error'); }
}

// ============================================================
// AUDIT LOGS
// ============================================================
let auditFilterTimer = null;
document.getElementById('auditAdminFilter').addEventListener('input', () => {
  clearTimeout(auditFilterTimer);
  auditFilterTimer = setTimeout(() => loadAuditLogs(1), 400);
});
document.getElementById('auditActionFilter').addEventListener('change', () => loadAuditLogs(1));

async function loadAuditLogs(page) {
  auditPage = page;
  const adminEmail = document.getElementById('auditAdminFilter').value;
  const actionType = document.getElementById('auditActionFilter').value;
  try {
    const data = await API.get(`/reports_audit.php?page=${page}&admin_email=${encodeURIComponent(adminEmail)}&action_type=${encodeURIComponent(actionType)}`);
    const body = document.getElementById('auditTableBody');
    if (!data.logs.length) { body.innerHTML = `<tr><td colspan="6" class="empty-state">No audit logs yet.</td></tr>`; return; }
    body.innerHTML = data.logs.map(l => `
      <tr>
        <td>${l.admin_email}</td>
        <td><span class="badge-soft badge-info">${l.action}</span></td>
        <td>${l.target || '-'}</td>
        <td class="text-muted" style="max-width:260px;">${(l.details || '').slice(0, 80)}</td>
        <td>${l.ip_address}</td>
        <td>${fmtDate(l.created_at)}</td>
      </tr>`).join('');
    renderPagination('auditPagination', data.pagination, loadAuditLogs);
  } catch (err) { toast(err.message, 'error'); }
}

// ============================================================
// SMTP
// ============================================================
async function loadSmtp() {
  try {
    const data = await API.get('/settings_smtp.php');
    const s = data.smtp;
    document.getElementById('smtpHost').value = s.smtp_host || '';
    document.getElementById('smtpPort').value = s.smtp_port || '';
    document.getElementById('smtpEncryption').value = s.smtp_encryption || 'SSL';
    document.getElementById('smtpUsername').value = s.smtp_username || '';
    document.getElementById('smtpSenderName').value = s.sender_name || '';
    document.getElementById('smtpSenderEmail').value = s.sender_email || '';
    document.getElementById('smtpPassword').placeholder = s.smtp_password ? 'Leave blank to keep current' : 'Enter SMTP password';
  } catch (err) { toast(err.message, 'error'); }
}

document.getElementById('smtpForm').addEventListener('submit', async (e) => {
  e.preventDefault();
  try {
    await API.post('/settings_smtp.php', {
      smtp_host: document.getElementById('smtpHost').value,
      smtp_port: document.getElementById('smtpPort').value,
      smtp_encryption: document.getElementById('smtpEncryption').value,
      smtp_username: document.getElementById('smtpUsername').value,
      smtp_password: document.getElementById('smtpPassword').value,
      sender_name: document.getElementById('smtpSenderName').value,
      sender_email: document.getElementById('smtpSenderEmail').value,
    });
    toast('SMTP settings saved.');
    document.getElementById('smtpPassword').value = '';
  } catch (err) { toast(err.message, 'error'); }
});

document.getElementById('sendTestEmailBtn').addEventListener('click', async () => {
  const target = document.getElementById('testEmailTarget').value;
  if (!target) return toast('Enter a target email first.', 'error');
  try {
    await API.post('/test_email.php', { target_email: target });
    toast('Test email sent — check the inbox.');
  } catch (err) { toast(err.message, 'error'); }
});

// ============================================================
// APP SETTINGS
// ============================================================
let appSettingsCache = null;

async function loadAppSettings() {
  try {
    const data = await API.get('/settings_app.php');
    appSettingsCache = data.settings;
    const s = data.settings;
    document.getElementById('setAppName').value = s.app_name || '';
    document.getElementById('setSupportEmail').value = s.support_email || '';
    document.getElementById('setSupportWhatsapp').value = s.support_whatsapp || '';
    document.getElementById('setSupportUpi').value = s.support_upi_id || '';
    document.getElementById('setReferralCommission').value = s.referral_commission || '';
    document.getElementById('setTrialDays').value = s.default_trial_days || '';
    document.getElementById('setAnnouncement').value = s.announcement || '';
    document.getElementById('setGeminiKey').value = s.gemini_api_key || '';

    document.getElementById('setFacebook').value = s.facebook_url || '';
    document.getElementById('setInstagram').value = s.instagram_url || '';
    document.getElementById('setYoutube').value = s.youtube_url || '';
    document.getElementById('setTelegram').value = s.telegram_url || '';
    document.getElementById('setWhatsapp').value = s.whatsapp_url || '';
    document.getElementById('setLinkedin').value = s.linkedin_url || '';
    document.getElementById('setTwitter').value = s.twitter_url || '';

    document.getElementById('legalTextarea').value = s.privacy_policy || '';
  } catch (err) { toast(err.message, 'error'); }
}

document.getElementById('appBasicForm').addEventListener('submit', async (e) => {
  e.preventDefault();
  try {
    await API.post('/settings_app.php', {
      app_name: document.getElementById('setAppName').value,
      support_email: document.getElementById('setSupportEmail').value,
      support_whatsapp: document.getElementById('setSupportWhatsapp').value,
      support_upi_id: document.getElementById('setSupportUpi').value,
      referral_commission: document.getElementById('setReferralCommission').value,
      default_trial_days: document.getElementById('setTrialDays').value,
      announcement: document.getElementById('setAnnouncement').value,
    });
    toast('Settings saved.');
  } catch (err) { toast(err.message, 'error'); }
});

document.getElementById('saveGeminiKeyBtn').addEventListener('click', async () => {
  try {
    await API.post('/settings_app.php', { gemini_api_key: document.getElementById('setGeminiKey').value });
    toast('AI key saved securely.');
  } catch (err) { toast(err.message, 'error'); }
});

document.getElementById('socialForm').addEventListener('submit', async (e) => {
  e.preventDefault();
  try {
    await API.post('/settings_app.php', {
      facebook_url: document.getElementById('setFacebook').value,
      instagram_url: document.getElementById('setInstagram').value,
      youtube_url: document.getElementById('setYoutube').value,
      telegram_url: document.getElementById('setTelegram').value,
      whatsapp_url: document.getElementById('setWhatsapp').value,
      linkedin_url: document.getElementById('setLinkedin').value,
      twitter_url: document.getElementById('setTwitter').value,
    });
    toast('Social links saved.');
  } catch (err) { toast(err.message, 'error'); }
});

let currentLegalKey = 'privacy_policy';
document.querySelectorAll('#legalTabs .nav-link').forEach(tab => {
  tab.addEventListener('click', () => {
    document.querySelectorAll('#legalTabs .nav-link').forEach(t => t.classList.remove('active'));
    tab.classList.add('active');
    currentLegalKey = tab.dataset.legal;
    document.getElementById('legalTextarea').value = (appSettingsCache && appSettingsCache[currentLegalKey]) || '';
  });
});

document.getElementById('saveLegalBtn').addEventListener('click', async () => {
  try {
    const payload = {};
    payload[currentLegalKey] = document.getElementById('legalTextarea').value;
    await API.post('/settings_app.php', payload);
    toast('Legal page saved.');
  } catch (err) { toast(err.message, 'error'); }
});

// ---------------------------------------------------------
// Boot
// ---------------------------------------------------------
checkExistingSession();
