/**
 * admin.js - Logic Dashboard Admin Penjualan
 * Terintegrasi dengan Cockpit CMS & sistem existing
 */

const API_URL = 'api.php';
let currentOrders = [];
let currentOrderId = null;

document.addEventListener('DOMContentLoaded', function() {
  loadOrders();
  setupEventListeners();
});

// === LOAD ORDERS ===
async function loadOrders(filter = 'all', search = '', sort = 'newest') {
  try {
    const res = await fetch(
      `${API_URL}?action=get_orders&filter=${filter}&search=${encodeURIComponent(search)}&sort=${sort}`
    );
    const data = await res.json();
    
    if (data.success) {
      currentOrders = data.orders;
      renderStats(data.stats);
      renderOrders(data.orders);
      updateOrderCount(data.orders.length);
    }
  } catch (err) {
    console.error('Gagal memuat orders:', err);
    document.getElementById('ordersTableBody').innerHTML = 
      '<tr><td colspan="7" class="text-center text-danger py-4">❌ Gagal memuat data</td></tr>';
  }
}

// === RENDER STATS ===
function renderStats(stats) {
  document.getElementById('stat-baru').textContent = stats.baru || 0;
  document.getElementById('stat-packing').textContent = stats.packing || 0;
  document.getElementById('stat-kurir').textContent = stats.kurir || 0;
  document.getElementById('stat-dikirim').textContent = stats.dikirim || 0;
  document.getElementById('stat-selesai').textContent = stats.selesai || 0;
  document.getElementById('stat-batal').textContent = stats.batal || 0;
}

// === RENDER ORDERS TABLE ===
function renderOrders(orders) {
  const tbody = document.getElementById('ordersTableBody');
  
  if (orders.length === 0) {
    tbody.innerHTML = '<tr><td colspan="7" class="text-center py-5 text-muted">Tidak ada pesanan</td></tr>';
    return;
  }
  
  tbody.innerHTML = orders.map(order => {
    const statusLabels = {
      'diterima': '🟦 Diterima',
      'packing': '🟧 Packing',
      'kurir': '🟪 Ke Kurir',
      'perjalanan': '🟦 Dikirim',
      'selesai': '🟩 Selesai',
      'batal': '🟥 Batal'
    };
    
    const firstProduct = order.produk?.[0] || {nama: '-', qty: 0};
    const statusClass = `status-${order.status}`;
    
    return `
      <tr class="order-row ${statusClass}" data-id="${order.id}" data-status="${order.status}">
        <td class="ps-4 fw-medium">${order.order_id}</td>
        <td>
          <div class="fw-medium">${escapeHtml(order.nama)}</div>
          <small class="text-muted">
            ${escapeHtml(order.wa)}<br>
            ${escapeHtml(order.kota)}
          </small>
        </td>
        <td>
          <div class="d-flex align-items-center gap-2">
            <div class="product-thumb">🌿</div>
            <div>
              <div class="small fw-medium">${escapeHtml(firstProduct.nama)}</div>
              <small class="text-muted">+${order.produk?.length - 1 || 0} item</small>
            </div>
          </div>
        </td>
        <td class="fw-bold">Rp ${formatRupiah(order.total)}</td>
        <td>
          ${formatDate(order.tanggal)}<br>
          <small class="text-muted">${formatTime(order.tanggal)}</small>
        </td>
        <td>
          <span class="status-badge ${statusClass}">
            ${statusLabels[order.status] || order.status}
          </span>
        </td>
        <td class="text-end pe-4">
          <button class="action-btn btn-outline-primary" title="Detail" 
                  onclick="openOrderDetail('${order.id}')">
            <i class="bi bi-eye"></i>
          </button>
          <button class="action-btn btn-success" title="Update Status"
                  onclick="openOrderDetail('${order.id}')">
            <i class="bi bi-pencil"></i>
          </button>
        </td>
      </tr>
    `;
  }).join('');
}

// === OPEN ORDER DETAIL MODAL ===
async function openOrderDetail(orderId) {
  currentOrderId = orderId;
  const order = currentOrders.find(o => o.id === orderId);
  if (!order) return;
  
  // Populate modal
  document.getElementById('modalOrderId').textContent = order.order_id;
  document.getElementById('custName').textContent = order.nama;
  document.getElementById('custPhone').textContent = order.wa;
  document.getElementById('custAddress').textContent = `${order.alamat}, ${order.kota}`;
  document.getElementById('orderDate').textContent = formatDate(order.tanggal) + ' ' + formatTime(order.tanggal);
  document.getElementById('orderCourier').textContent = order.kurir;
  document.getElementById('orderOngkir').textContent = `Rp ${formatRupiah(order.ongkir)}`;
  document.getElementById('orderTotal').textContent = `Rp ${formatRupiah(order.total)}`;
  
  // Products table
  const productsBody = document.querySelector('#productsTable tbody');
  productsBody.innerHTML = order.produk?.map(p => `
    <tr>
      <td>${escapeHtml(p.nama)}</td>
      <td>-</td>
      <td>${p.qty}</td>
      <td>-</td>
    </tr>
  `).join('') || '<tr><td colspan="4" class="text-muted">Tidak ada detail produk</td></tr>';
  
  // Status timeline
  document.querySelectorAll('.timeline-step').forEach(step => {
    step.classList.remove('active', 'completed');
    const stepVal = step.dataset.step;
    const orderStatus = order.status;
    
    const statusOrder = ['diterima', 'packing', 'kurir', 'perjalanan', 'selesai'];
    const currentIdx = statusOrder.indexOf(orderStatus);
    const stepIdx = statusOrder.indexOf(stepVal);
    
    if (stepIdx < currentIdx) step.classList.add('completed');
    if (stepIdx === currentIdx) step.classList.add('active');
  });
  
  // Set current status in dropdown
  document.getElementById('statusSelect').value = order.status;
  
  // Activity log
  document.getElementById('activityLog').innerHTML = order.status_history?.map(h => `
    <div class="d-flex gap-3 mb-2">
      <span class="text-muted" style="min-width:130px">
        ${formatDate(h.timestamp)} ${formatTime(h.timestamp)}
      </span>
      <span>
        <strong>${h.status}</strong>
        ${h.note ? `<br><small class="text-muted">📝 ${escapeHtml(h.note)}</small>` : ''}
        <br><small class="text-muted">by: ${h.admin}</small>
      </span>
    </div>
  `).join('') || '<p class="text-muted small">Belum ada riwayat status</p>';
  
  // Show modal
  new bootstrap.Modal(document.getElementById('modalDetail')).show();
}

// === UPDATE STATUS ===
document.getElementById('btnSaveStatus')?.addEventListener('click', async function() {
  if (!currentOrderId) return;
  
  const status = document.getElementById('statusSelect').value;
  const note = document.getElementById('statusNote').value;
  
  try {
    const res = await fetch(`${API_URL}?action=update_status`, {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({
        order_id: currentOrderId,
        status: status,
        note: note
      })
    });
    
    const result = await res.json();
    
    if (result.success) {
      showToast('Status berhasil diperbarui!');
      bootstrap.Modal.getInstance(document.getElementById('modalDetail')).hide();
      loadOrders(); // Refresh list
    } else {
      alert('Gagal: ' + (result.message || 'Unknown error'));
    }
  } catch (err) {
    alert('Error koneksi: ' + err.message);
  }
});

// === SEND WA ===
document.getElementById('btnSendWA')?.addEventListener('click', async function() {
  const order = currentOrders.find(o => o.id === currentOrderId);
  if (!order) return;
  
  const status = document.getElementById('statusSelect').value;
  
  try {
    const res = await fetch(`${API_URL}?action=send_wa`, {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({
        order_id: order.order_id,
        wa: order.wa,
        status: status
      })
    });
    
    const result = await res.json();
    if (result.success && result.wa_link) {
      window.open(result.wa_link, '_blank');
    }
  } catch (err) {
    console.error('WA error:', err);
  }
});

// === FILTER & SEARCH ===
function setupEventListeners() {
  // Filter chips
  document.querySelectorAll('.filter-chip').forEach(chip => {
    chip.addEventListener('click', function() {
      document.querySelectorAll('.filter-chip').forEach(c => c.classList.remove('active'));
      this.classList.add('active');
      loadOrders(this.dataset.filter, document.getElementById('searchOrder').value, document.getElementById('sortOrder').value);
    });
  });
  
  // Search
  document.getElementById('searchOrder')?.addEventListener('input', debounce(function(e) {
    const activeFilter = document.querySelector('.filter-chip.active')?.dataset.filter || 'all';
    loadOrders(activeFilter, e.target.value, document.getElementById('sortOrder').value);
  }, 300));
  
  // Sort
  document.getElementById('sortOrder')?.addEventListener('change', function() {
    const activeFilter = document.querySelector('.filter-chip.active')?.dataset.filter || 'all';
    loadOrders(activeFilter, document.getElementById('searchOrder').value, this.value);
  });
  
  // Refresh
  document.getElementById('btnRefresh')?.addEventListener('click', function() {
    this.disabled = true;
    this.innerHTML = '<i class="bi bi-arrow-clockwise spinner-border spinner-border-sm"></i>';
    loadOrders(
      document.querySelector('.filter-chip.active')?.dataset.filter || 'all',
      document.getElementById('searchOrder').value,
      document.getElementById('sortOrder').value
    ).finally(() => {
      this.disabled = false;
      this.innerHTML = '<i class="bi bi-arrow-clockwise"></i> Refresh';
    });
  });
  
  // Export
  document.getElementById('btnDoExport')?.addEventListener('click', function() {
    const format = document.querySelector('[id^="export"]:checked')?.id || 'exportCSV';
    const period = document.getElementById('exportPeriod').value;
    alert(`Export ${format.replace('export','').toUpperCase()} untuk periode: ${period}\n\n(Fitur export memerlukan library tambahan seperti SheetJS/pdf-lib)`);
  });
}

// === UTILITIES ===
function formatRupiah(num) {
  return Number(num).toLocaleString('id-ID');
}

function formatDate(dateStr) {
  if (!dateStr) return '-';
  const d = new Date(dateStr);
  return d.toLocaleDateString('id-ID', {day:'2-digit', month:'short', year:'numeric'});
}

function formatTime(dateStr) {
  if (!dateStr) return '-';
  const d = new Date(dateStr);
  return d.toLocaleTimeString('id-ID', {hour:'2-digit', minute:'2-digit'});
}

function escapeHtml(text) {
  if (!text) return '';
  const map = {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'};
  return text.replace(/[&<>"']/g, m => map[m]);
}

function debounce(func, wait) {
  let timeout;
  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), wait);
  };
}

function showToast(message) {
  document.getElementById('toastMessage').textContent = message;
  const toast = new bootstrap.Toast(document.getElementById('liveToast'));
  toast.show();
}

function updateOrderCount(count) {
  document.getElementById('orderCount').textContent = `(${count} pesanan)`;
}

// Global functions for onclick handlers
window.openOrderDetail = openOrderDetail;