/* =========================================================
   ZA-FARM-KH — Admin Live Inspector & Customer Orders JS
   Features: Real-time Order Feed, #idowder Search, 360° Customer Profile
   ========================================================= */

const API = '/zapi/admin';
const token = localStorage.getItem('zafarm_token');
let currentFilterService = '';
let currentUserIdFilter = '';
let currentPage = 1;
let currentInspectUser = null;

document.addEventListener('DOMContentLoaded', () => {
  if (!token) { window.location.replace('/login'); return; }
  const user = JSON.parse(localStorage.getItem('zafarm_user') || '{}');
  if (user.role !== 'admin') { window.location.replace('/'); return; }

  loadInspectorData();
  
  // Search input enter key
  const searchInput = document.getElementById('searchInput');
  if (searchInput) {
    searchInput.addEventListener('keyup', (e) => {
      if (e.key === 'Enter') loadOrders(1);
    });
  }

  // Auto-refresh every 15 seconds
  setInterval(() => {
    if (!document.getElementById('customer360Modal').classList.contains('show')) {
      loadOrders(currentPage, true);
      loadKpis();
    }
  }, 15000);
});

async function loadInspectorData() {
  await Promise.all([
    loadKpis(),
    loadOrders(1),
    loadTopBuyers()
  ]);
}

/* ---------- 1. KPI Stats ---------- */
async function loadKpis() {
  try {
    const [resStats, resLicenses] = await Promise.all([
      fetch('/zapi/admin/stats', { headers: { 'Authorization': 'Bearer ' + token } }),
      fetch('/zapi/admin/licenses', { headers: { 'Authorization': 'Bearer ' + token } })
    ]);

    if (resStats.ok) {
      const stats = await resStats.json();
      document.getElementById('kpiUsers').textContent = stats.totalUsers || 0;
      document.getElementById('kpiOrders').textContent = stats.totalOrders || 0;
      document.getElementById('kpiRevenue').textContent = '$' + parseFloat(stats.totalRevenue || 0).toFixed(2);
    }
    if (resLicenses.ok) {
      const lData = await resLicenses.json();
      document.getElementById('kpiLicenses').textContent = (lData.licenses || []).length;
    }
  } catch (err) {
    console.error('KPIs load error:', err);
  }
}

/* ---------- 2. Filter Pills ---------- */
function filterByService(service) {
  currentFilterService = service;
  document.querySelectorAll('.pill').forEach(el => {
    el.classList.toggle('active', el.dataset.service === service);
  });
  loadOrders(1);
}

/* ---------- 3. Load Orders Table ---------- */
async function loadOrders(page = 1, silent = false) {
  currentPage = page;
  const searchVal = (document.getElementById('searchInput')?.value || '').trim();
  const tbody = document.getElementById('ordersTableBody');
  if (!tbody) return;

  if (!silent) {
    tbody.innerHTML = `<tr><td colspan="8" style="padding:32px;text-align:center;color:var(--text-muted);"><span class="spinner"></span> កំពុងទាញយកទិន្នន័យ...</td></tr>`;
  }

  try {
    const query = new URLSearchParams({
      page: page,
      limit: 50,
      search: searchVal || currentFilterService,
      userId: currentUserIdFilter
    });
    const res = await fetch(`${API}/orders?${query}`, {
      headers: { 'Authorization': 'Bearer ' + token }
    });
    if (!res.ok) throw new Error('Failed to load orders');

    const data = await res.json();
    const orders = data.orders || [];

    if (orders.length === 0) {
      tbody.innerHTML = `<tr><td colspan="8" style="padding:40px;text-align:center;color:var(--text-muted);">📭 មិនទាន់មានប្រវត្តិការបញ្ជាទិញឡើយ</td></tr>`;
      renderPagination(data.total, page);
      return;
    }

    tbody.innerHTML = orders.map(o => {
      const dateStr = new Date(o.createdAt).toLocaleString('en-US', {
        month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit'
      });
      const stColor = o.status === 'success' ? '#22c55e' : (o.status === 'failed' ? '#ef4444' : '#f59e0b');
      const stBg = o.status === 'success' ? 'rgba(34,197,94,0.15)' : (o.status === 'failed' ? 'rgba(239,68,68,0.15)' : 'rgba(245,158,11,0.15)');

      return `
        <tr style="border-bottom:1px solid var(--border);transition:background 0.15s;">
          <td style="padding:14px 16px;">
            <span class="id-badge" title="Copy Order ID" onclick="copyId('${o.id}')">#${o.id.substring(0,8)}</span>
          </td>
          <td style="padding:14px 16px;">
            <div class="user-pill" onclick="inspectCustomer('${o.userId || ''}')">
              <span style="display:inline-block;width:24px;height:24px;border-radius:50%;background:var(--surface-3);text-align:center;line-height:24px;font-size:11px;">
                ${(o.username || 'U')[0].toUpperCase()}
              </span>
              <div>
                <div style="font-size:13.5px;font-weight:700;color:var(--text);">${escapeHtml(o.username || 'Unknown')}</div>
                <div style="font-size:11.5px;color:var(--text-muted);">${escapeHtml(o.email || '')}</div>
              </div>
            </div>
          </td>
          <td style="padding:14px 16px;font-weight:600;color:var(--text);">
            ${getServiceBadge(o.service)}
          </td>
          <td style="padding:14px 16px;color:var(--text-2);">${o.qty || 1}</td>
          <td style="padding:14px 16px;font-weight:700;color:var(--gold-light);">$${parseFloat(o.total || 0).toFixed(3)}</td>
          <td style="padding:14px 16px;">
            <span style="font-size:12px;font-weight:700;color:${stColor};background:${stBg};padding:4px 10px;border-radius:20px;text-transform:uppercase;">
              ${o.status || 'pending'}
            </span>
          </td>
          <td style="padding:14px 16px;color:var(--text-muted);font-size:12.5px;">${dateStr}</td>
          <td style="padding:14px 16px;text-align:right;">
            <button class="inspect-btn" onclick="inspectCustomer('${o.userId || ''}')">
              🔍 ពិនិត្យប្រវត្តិភ្ញៀវ
            </button>
          </td>
        </tr>
      `;
    }).join('');

    renderPagination(data.total, page);
  } catch (err) {
    console.error('Orders table error:', err);
    tbody.innerHTML = `<tr><td colspan="8" style="padding:32px;text-align:center;color:var(--red);">បរាជ័យក្នុងការទាញយកទិន្នន័យ៖ ${err.message}</td></tr>`;
  }
}

function getServiceBadge(service = '') {
  if (service.includes('license') || service === 'license') {
    return `<span style="color:var(--gold);">🔑 ${escapeHtml(service)}</span>`;
  } else if (service.includes('gmail')) {
    return `<span style="color:#60a5fa;">📧 ${escapeHtml(service)}</span>`;
  } else if (service.includes('phone')) {
    return `<span style="color:var(--green);">📱 ${escapeHtml(service)}</span>`;
  }
  return escapeHtml(service);
}

/* ---------- 4. Inspect Customer 360° Profile ---------- */
async function inspectCustomer(userId) {
  if (!userId) {
    alert('រកមិនឃើញ User ID សម្រាប់គណនីនេះទេ');
    return;
  }
  try {
    const res = await fetch(`${API}/customer/${userId}/history`, {
      headers: { 'Authorization': 'Bearer ' + token }
    });
    if (!res.ok) throw new Error('Failed to load customer profile');

    const data = await res.json();
    currentInspectUser = data.user;

    document.getElementById('m360Name').textContent = data.user.username || 'Customer';
    document.getElementById('m360Email').textContent = data.user.email || '—';
    document.getElementById('m360Spent').textContent = '$' + (data.stats.totalSpent || '0.000');
    document.getElementById('m360OrdersCount').textContent = data.stats.orderCount || 0;
    document.getElementById('m360LicensesCount').textContent = data.stats.licenseCount || 0;
    document.getElementById('m360Balance').textContent = '$' + parseFloat(data.user.balance || 0).toFixed(3);
    document.getElementById('m360Role').textContent = data.user.role || 'user';

    // Populate Customer Orders Sub-table
    const obody = document.getElementById('m360OrdersBody');
    if (obody) {
      if ((data.orders || []).length === 0) {
        obody.innerHTML = `<tr><td colspan="5" style="padding:20px;text-align:center;color:var(--text-muted);">មិនទាន់មានការទិញ</td></tr>`;
      } else {
        obody.innerHTML = data.orders.map(o => `
          <tr style="border-bottom:1px solid var(--border);">
            <td style="padding:10px 12px;font-family:monospace;color:var(--gold-light);">#${o.id.substring(0,8)}</td>
            <td style="padding:10px 12px;font-weight:600;">${getServiceBadge(o.service)}</td>
            <td style="padding:10px 12px;color:var(--gold-light);">$${parseFloat(o.total || 0).toFixed(3)}</td>
            <td style="padding:10px 12px;"><span style="font-weight:700;color:${o.status === 'success' ? '#22c55e' : '#f59e0b'};">${o.status}</span></td>
            <td style="padding:10px 12px;color:var(--text-muted);font-size:12px;">${new Date(o.createdAt).toLocaleString('en-US', { month:'short', day:'numeric', hour:'2-digit', minute:'2-digit' })}</td>
          </tr>
        `).join('');
      }
    }

    // Populate Customer Licenses Sub-table
    const lbody = document.getElementById('m360LicensesBody');
    if (lbody) {
      if ((data.licenses || []).length === 0) {
        lbody.innerHTML = `<tr><td colspan="5" style="padding:20px;text-align:center;color:var(--text-muted);">គ្មាន License Key ទេ</td></tr>`;
      } else {
        lbody.innerHTML = data.licenses.map(l => `
          <tr style="border-bottom:1px solid var(--border);">
            <td style="padding:10px 12px;font-family:monospace;color:var(--gold-light);font-weight:700;">${escapeHtml(l.license_key)}</td>
            <td style="padding:10px 12px;">${escapeHtml(l.package_name || l.package_id || 'License')}</td>
            <td style="padding:10px 12px;color:var(--text-2);">${l.expiry_date}</td>
            <td style="padding:10px 12px;"><span style="color:${l.is_active ? '#22c55e' : '#ef4444'};font-weight:700;">${l.is_active ? 'Active' : 'Expired'}</span></td>
            <td style="padding:10px 12px;color:var(--text-muted);font-size:12px;">${new Date(l.created_at).toLocaleDateString()}</td>
          </tr>
        `).join('');
      }
    }

    document.getElementById('customer360Modal').classList.add('show');
  } catch (err) {
    alert('បរាជ័យក្នុងការមើលព័ត៌មានអតិថិជន៖ ' + err.message);
  }
}

function closeCustomer360() {
  document.getElementById('customer360Modal').classList.remove('show');
}

function switch360Tab(tab) {
  document.getElementById('btnTabOrders').classList.toggle('active', tab === 'orders');
  document.getElementById('btnTabLicenses').classList.toggle('active', tab === 'licenses');
  document.getElementById('view360Orders').style.display = tab === 'orders' ? 'block' : 'none';
  document.getElementById('view360Licenses').style.display = tab === 'licenses' ? 'block' : 'none';
}

/* ---------- 5. Top Buyers Leaderboard ---------- */
async function loadTopBuyers() {
  const container = document.getElementById('topBuyersList');
  if (!container) return;

  try {
    const res = await fetch('/zapi/admin/top-buyers?limit=10', {
      headers: { 'Authorization': 'Bearer ' + token }
    });
    if (!res.ok) throw new Error('Failed to load top buyers');

    const data = await res.json();
    const buyers = Array.isArray(data) ? data : [];

    if (buyers.length === 0) {
      container.innerHTML = `<div style="text-align:center;color:var(--text-muted);padding:20px;">មិនទាន់មានអ្នកទិញទេ</div>`;
      return;
    }

    container.innerHTML = buyers.map((b, idx) => `
      <div style="display:flex;justify-content:space-between;align-items:center;padding:12px 0;border-bottom:1px solid var(--border);cursor:pointer;" onclick="inspectCustomer('${b.id}')">
        <div style="display:flex;align-items:center;gap:10px;">
          <span style="font-size:14px;font-weight:800;color:${idx === 0 ? 'var(--gold)' : (idx === 1 ? '#94a3b8' : '#b45309')};width:20px;">
            #${idx + 1}
          </span>
          <div>
            <div style="font-size:13.5px;font-weight:700;color:var(--text);">${escapeHtml(b.username || 'User')}</div>
            <div style="font-size:11.5px;color:var(--text-muted);">${b.orderCount || 0} ដងបញ្ជាទិញ</div>
          </div>
        </div>
        <div style="text-align:right;">
          <div style="font-size:14px;font-weight:800;color:var(--gold-light);">$${parseFloat(b.totalSpent || 0).toFixed(2)}</div>
          <span style="font-size:11px;color:var(--text-muted);">Inspect 🔍</span>
        </div>
      </div>
    `).join('');
  } catch (err) {
    container.innerHTML = `<div style="color:var(--red);text-align:center;padding:16px;">Error loading buyers</div>`;
  }
}

/* ---------- 6. Quick Action Prompts in 360 Modal ---------- */
async function promptTopupUser() {
  if (!currentInspectUser) return;
  const amtStr = prompt(`បញ្ចូលចំនួនលុយដែលចង់បន្ថែម ($) សម្រាប់ ${currentInspectUser.username}:`, '5');
  if (!amtStr) return;
  const amount = parseFloat(amtStr);
  if (isNaN(amount) || amount <= 0) { alert('ចំនួនលុយមិនត្រឹមត្រូវ'); return; }

  const res = await fetch(`${API}/topup`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
    body: JSON.stringify({ userId: currentInspectUser.id, amount })
  });
  const data = await res.json();
  if (res.ok) {
    alert(data.message);
    inspectCustomer(currentInspectUser.id);
  } else {
    alert('បរាជ័យ៖ ' + data.message);
  }
}

async function promptDeductUser() {
  if (!currentInspectUser) return;
  const amtStr = prompt(`បញ្ចូលចំនួនលុយដែលចង់ដក ($) ពី ${currentInspectUser.username}:`, '1');
  if (!amtStr) return;
  const amount = parseFloat(amtStr);
  if (isNaN(amount) || amount <= 0) { alert('ចំនួនលុយមិនត្រឹមត្រូវ'); return; }

  const res = await fetch(`${API}/deduct`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
    body: JSON.stringify({ userId: currentInspectUser.id, amount })
  });
  const data = await res.json();
  if (res.ok) {
    alert(data.message);
    inspectCustomer(currentInspectUser.id);
  } else {
    alert('បរាជ័យ៖ ' + data.message);
  }
}

async function promptSetRole() {
  if (!currentInspectUser) return;
  const currentRole = currentInspectUser.role || 'user';
  const newRole = currentRole === 'admin' ? 'user' : 'admin';
  if (!confirm(`តើចង់ប្ដូរ Role របស់ ${currentInspectUser.username} ពី "${currentRole}" ទៅជា "${newRole}" មែនទេ?`)) return;

  const res = await fetch(`${API}/set-role`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
    body: JSON.stringify({ userId: currentInspectUser.id, role: newRole })
  });
  const data = await res.json();
  if (res.ok) {
    alert(data.message);
    inspectCustomer(currentInspectUser.id);
  } else {
    alert('បរាជ័យ៖ ' + data.message);
  }
}

/* ---------- 7. Helpers ---------- */
function renderPagination(total, page) {
  const cont = document.getElementById('ordersPagination');
  if (!cont) return;
  const pages = Math.ceil(total / 50);
  if (pages <= 1) { cont.innerHTML = ''; return; }

  let html = '';
  for (let i = 1; i <= pages; i++) {
    html += `<button class="pill ${i === page ? 'active' : ''}" onclick="loadOrders(${i})">${i}</button>`;
  }
  cont.innerHTML = html;
}

function copyId(id) {
  navigator.clipboard.writeText(id).then(() => {
    alert('បានចម្លង Order ID: #' + id);
  });
}

function escapeHtml(str) {
  if (!str) return '';
  return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
