<?php
declare(strict_types=1);
require_once __DIR__ . '/../../api/lib.php';

$pageTitle = 'Sales & Orders';
$pageSection = 'sales';

hw_require_auth(['admin']);
$user = hw_get_auth_user();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($pageTitle); ?> - Herbal Wellness Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="bg-gray-50">
    <div class="flex h-screen bg-gray-100">
        <!-- Sidebar Navigation -->
        <aside class="w-64 bg-gradient-to-b from-emerald-900 to-emerald-800 text-white shadow-lg flex flex-col">
            <!-- Logo/Brand -->
            <div class="p-6 border-b border-emerald-700 flex-shrink-0">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 bg-emerald-300 rounded-lg flex items-center justify-center">
                        <i class="fas fa-leaf text-emerald-900 text-lg"></i>
                    </div>
                    <div>
                        <h1 class="font-bold text-lg">Herbal Admin</h1>
                        <p class="text-emerald-200 text-xs">Management Portal</p>
                    </div>
                </div>
            </div>

            <!-- Navigation Menu -->
            <nav class="flex-1 overflow-y-auto p-4 space-y-2">
                <a href="/files/atasteofafricanmarketplace/dashboard/admin/" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-home w-5"></i>
                    <span class="font-medium">Dashboard</span>
                </a>

                <div class="pt-4 pb-2">
                    <p class="px-4 text-xs font-bold text-emerald-300 uppercase tracking-wider">Business</p>
                </div>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/sales.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors bg-emerald-700 text-white">
                    <i class="fas fa-shopping-cart w-5"></i>
                    <span>Sales & Orders</span>
                </a>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/bookings.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-calendar-check w-5"></i>
                    <span>Booking Calendar</span>
                </a>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/coaches.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                  <i class="fas fa-user-md w-5"></i>
                  <span>Coaches</span>
                </a>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/products.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-boxes w-5"></i>
                    <span>Products</span>
                </a>

                <div class="pt-4 pb-2">
                    <p class="px-4 text-xs font-bold text-emerald-300 uppercase tracking-wider">Customers</p>
                </div>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/customers.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-users w-5"></i>
                    <span>All Customers</span>
                </a>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/contacts.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-address-book w-5"></i>
                    <span>Contacts & Leads</span>
                </a>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/loyalty.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-gift w-5"></i>
                    <span>Loyalty Program</span>
                </a>

                <div class="pt-4 pb-2">
                    <p class="px-4 text-xs font-bold text-emerald-300 uppercase tracking-wider">Insights</p>
                </div>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/analytics.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-chart-line w-5"></i>
                    <span>Analytics</span>
                </a>

                <div class="pt-4 pb-2">
                    <p class="px-4 text-xs font-bold text-emerald-300 uppercase tracking-wider">Tools</p>
                </div>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/automations.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-robot w-5"></i>
                    <span>Automations</span>
                </a>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/cms.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-file-alt w-5"></i>
                    <span>Content Manager</span>
                </a>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/developers.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-code w-5"></i>
                    <span>Developer Tools</span>
                </a>

                <div class="pt-4 pb-2">
                    <p class="px-4 text-xs font-bold text-emerald-300 uppercase tracking-wider">System</p>
                </div>

                <a href="/files/atasteofafricanmarketplace/dashboard/admin/settings.php" class="flex items-center gap-3 px-4 py-3 rounded-lg transition-colors text-emerald-100 hover:bg-emerald-700/50">
                    <i class="fas fa-cog w-5"></i>
                    <span>Settings</span>
                </a>
            </nav>

            <!-- User Profile Footer -->
            <div class="flex-shrink-0 p-4 border-t border-emerald-700 bg-emerald-800">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 bg-emerald-300 rounded-full flex items-center justify-center">
                        <i class="fas fa-user text-emerald-900"></i>
                    </div>
                    <div class="flex-1 min-w-0">
                        <p class="text-sm font-semibold truncate"><?php echo htmlspecialchars($user['first_name'] ?? 'Admin'); ?></p>
                        <p class="text-xs text-emerald-200 truncate"><?php echo htmlspecialchars($user['email'] ?? ''); ?></p>
                    </div>
                    <a href="/files/atasteofafricanmarketplace/api/auth/logout.php" class="text-emerald-200 hover:text-white">
                        <i class="fas fa-sign-out-alt"></i>
                    </a>
                </div>
            </div>
        </aside>

        <!-- Main Content -->
        <div class="flex-1 flex flex-col overflow-hidden">
            <!-- Top Header Bar -->
            <header class="bg-white border-b border-gray-200 px-8 py-4 shadow-sm">
                <div class="flex items-center justify-between">
                    <div>
                        <h1 class="text-2xl font-bold text-gray-900">Sales & Orders</h1>
                        <p class="text-sm text-gray-600 mt-1">Manage orders and track payments</p>
                    </div>
                    <div class="flex items-center gap-4">
                        <button class="p-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">
                            <i class="fas fa-bell text-lg"></i>
                        </button>
                    </div>
                </div>
            </header>

            <!-- Content Area -->
            <main class="flex-1 overflow-auto p-8">

    <!-- Sales Overview Section -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
      <!-- Total Revenue -->
      <div class="bg-gradient-to-br from-emerald-50 to-emerald-100 rounded-lg shadow p-6">
        <div class="flex items-start justify-between">
          <div>
            <p class="text-sm text-gray-600 font-medium">Total Revenue</p>
            <p class="text-3xl font-bold text-gray-900 mt-2" id="total-revenue">$0</p>
            <p class="text-xs text-gray-600 mt-1">All time</p>
          </div>
          <div class="w-12 h-12 bg-emerald-500 rounded-lg flex items-center justify-center">
            <i class="fas fa-dollar-sign text-white text-xl"></i>
          </div>
        </div>
      </div>

      <!-- Total Orders -->
      <div class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg shadow p-6">
        <div class="flex items-start justify-between">
          <div>
            <p class="text-sm text-gray-600 font-medium">Total Orders</p>
            <p class="text-3xl font-bold text-gray-900 mt-2" id="total-orders">0</p>
            <p class="text-xs text-gray-600 mt-1">Completed orders</p>
          </div>
          <div class="w-12 h-12 bg-blue-500 rounded-lg flex items-center justify-center">
            <i class="fas fa-shopping-bag text-white text-xl"></i>
          </div>
        </div>
      </div>

      <!-- Average Order Value -->
      <div class="bg-gradient-to-br from-purple-50 to-purple-100 rounded-lg shadow p-6">
        <div class="flex items-start justify-between">
          <div>
            <p class="text-sm text-gray-600 font-medium">Avg. Order Value</p>
            <p class="text-3xl font-bold text-gray-900 mt-2" id="avg-order-value">$0</p>
            <p class="text-xs text-gray-600 mt-1">Per order</p>
          </div>
          <div class="w-12 h-12 bg-purple-500 rounded-lg flex items-center justify-center">
            <i class="fas fa-chart-bar text-white text-xl"></i>
          </div>
        </div>
      </div>

      <!-- Pending Orders -->
      <div class="bg-gradient-to-br from-orange-50 to-orange-100 rounded-lg shadow p-6">
        <div class="flex items-start justify-between">
          <div>
            <p class="text-sm text-gray-600 font-medium">Pending Orders</p>
            <p class="text-3xl font-bold text-gray-900 mt-2" id="pending-orders">0</p>
            <p class="text-xs text-gray-600 mt-1">Awaiting processing</p>
          </div>
          <div class="w-12 h-12 bg-orange-500 rounded-lg flex items-center justify-center">
            <i class="fas fa-hourglass-half text-white text-xl"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- Analytics Row -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
      <!-- Top Products -->
      <div class="bg-white rounded-lg shadow p-6">
        <h3 class="text-lg font-bold text-gray-900 mb-4">Top Products</h3>
        <div id="top-products-list" class="space-y-3">
          <p class="text-sm text-gray-500">Loading...</p>
        </div>
      </div>

      <!-- Top Customers -->
      <div class="bg-white rounded-lg shadow p-6">
        <h3 class="text-lg font-bold text-gray-900 mb-4">Top Customers</h3>
        <div id="top-customers-list" class="space-y-3">
          <p class="text-sm text-gray-500">Loading...</p>
        </div>
      </div>

      <!-- Sales by Status -->
      <div class="bg-white rounded-lg shadow p-6">
        <h3 class="text-lg font-bold text-gray-900 mb-4">Orders by Status</h3>
        <div id="status-breakdown" class="space-y-3">
          <p class="text-sm text-gray-500">Loading...</p>
        </div>
      </div>
    </div>

    <!-- Tab Navigation -->
    <div class="flex gap-4 mb-8 border-b border-gray-200">
      <button onclick="showTab('orders')" class="tab-btn active py-4 px-6 font-semibold text-emerald-600 border-b-2 border-emerald-600 transition-colors">
        <i class="fas fa-list mr-2"></i>Orders
      </button>
      <button onclick="showTab('payments')" class="tab-btn py-4 px-6 font-semibold text-gray-600 hover:text-gray-900 border-b-2 border-transparent hover:border-gray-300 transition-colors">
        <i class="fas fa-credit-card mr-2"></i>Payments
      </button>
    </div>

    <!-- Orders Tab -->
    <div id="orders-tab" class="tab-content">
      <div class="bg-white rounded-lg shadow p-6">
        <div class="flex justify-between items-center mb-6">
          <h2 class="text-2xl font-bold text-gray-900">All Orders</h2>
          <input type="text" id="search-orders" placeholder="Search orders..." class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-transparent w-64">
        </div>

        <div class="overflow-x-auto">
          <table class="w-full">
            <thead>
              <tr class="bg-gray-50 border-b border-gray-200">
                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Order ID</th>
                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Date Created</th>
                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Customer</th>
                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Items</th>
                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Total</th>
                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Payment</th>
                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Fulfillment</th>
              </tr>
            </thead>
            <tbody id="orders-tbody">
              <!-- Orders will load here -->
            </tbody>
          </table>
        </div>

        <div class="mt-6 flex justify-between items-center">
          <p class="text-sm text-gray-600">Showing <span id="orders-count">0</span> orders</p>
          <div class="flex gap-2">
            <button onclick="prevPage()" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors">Previous</button>
            <button onclick="nextPage()" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors">Next</button>
          </div>
        </div>
      </div>
    </div>

    <!-- Payments Tab -->
    <div id="payments-tab" class="tab-content hidden">
      <div class="bg-white rounded-lg shadow p-6">
        <div class="flex justify-between items-center mb-6">
          <h2 class="text-2xl font-bold text-gray-900">All Payments</h2>
          <input type="text" id="search-payments" placeholder="Search payments..." class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-transparent w-64">
        </div>

        <div class="overflow-x-auto">
          <table class="w-full">
            <thead>
              <tr class="bg-gray-50 border-b border-gray-200">
                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Payment Date</th>
                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Customer</th>
                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Product/Service</th>
                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Amount</th>
                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Method</th>
                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Status</th>
                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Transaction Date</th>
              </tr>
            </thead>
            <tbody id="payments-tbody">
              <!-- Payments will load here -->
            </tbody>
          </table>
        </div>

        <div class="mt-6 flex justify-between items-center">
          <p class="text-sm text-gray-600">Showing <span id="payments-count">0</span> payments</p>
          <div class="flex gap-2">
            <button onclick="prevPaymentPage()" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors">Previous</button>
            <button onclick="nextPaymentPage()" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors">Next</button>
          </div>
        </div>
      </div>
    </div>

            </main>
        </div>
    </div>

<script>
let currentOrderPage = 1;
let currentPaymentPage = 1;
const itemsPerPage = 10;
let allOrders = [];
let filteredOrders = [];
let allPayments = [];
let filteredPayments = [];

// Load Orders
async function loadOrders() {
  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/orders/list.php?limit=200');
    const data = await response.json();
    if (!data.success) throw new Error(data.error || 'Failed to load orders');

    allOrders = data.orders || [];
    filteredOrders = [...allOrders];
    document.getElementById('orders-count').textContent = filteredOrders.length;
    displayOrders();
    updateAnalytics();
    console.log('Orders loaded:', filteredOrders.length);
  } catch (error) {
    console.error('Error loading orders:', error);
    showMessage('Error loading orders', true);
  }
}

// Load Payments
async function loadPayments() {
  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/orders/payments.php?limit=200');
    const data = await response.json();
    if (!data.success) throw new Error(data.error || 'Failed to load payments');

    allPayments = data.payments || [];
    filteredPayments = [...allPayments];
    document.getElementById('payments-count').textContent = filteredPayments.length;
    displayPayments();
    console.log('Payments loaded:', filteredPayments.length);
  } catch (error) {
    console.error('Error loading payments:', error);
    showMessage('Error loading payments', true);
  }
}

// Update Analytics
function updateAnalytics() {
  // Calculate totals
  const totalRevenue = allOrders.reduce((sum, o) => sum + parseFloat(o.total_amount || 0), 0);
  const totalOrders = allOrders.length;
  const avgOrderValue = totalOrders > 0 ? totalRevenue / totalOrders : 0;
  const pendingOrders = allOrders.filter(o => o.status === 'pending').length;
  
  // Update overview cards
  document.getElementById('total-revenue').textContent = '$' + totalRevenue.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  document.getElementById('total-orders').textContent = totalOrders.toLocaleString();
  document.getElementById('avg-order-value').textContent = '$' + avgOrderValue.toFixed(2);
  document.getElementById('pending-orders').textContent = pendingOrders;

  // Top Products (by frequency)
  const productFreq = {};
  allPayments.forEach(p => {
    const name = p.product_name || 'Unknown';
    productFreq[name] = (productFreq[name] || 0) + 1;
  });
  const topProducts = Object.entries(productFreq)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 5);
  
  const topProductsEl = document.getElementById('top-products-list');
  if (topProducts.length) {
    topProductsEl.innerHTML = topProducts.map(([name, count], i) => `
      <div class="flex items-center justify-between p-2 hover:bg-gray-50 rounded">
        <div class="flex items-center gap-3">
          <span class="text-xs font-bold text-emerald-600">#${i+1}</span>
          <span class="text-sm text-gray-900">${name}</span>
        </div>
        <span class="text-xs font-semibold text-gray-600">${count} sold</span>
      </div>
    `).join('');
  } else {
    topProductsEl.innerHTML = '<p class="text-sm text-gray-500">No sales data</p>';
  }

  // Top Customers (by spending)
  const customerSpend = {};
  allOrders.forEach(o => {
    const name = o.customer_name || 'Unknown';
    customerSpend[name] = (customerSpend[name] || 0) + parseFloat(o.total_amount || 0);
  });
  const topCustomers = Object.entries(customerSpend)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 5);
  
  const topCustomersEl = document.getElementById('top-customers-list');
  if (topCustomers.length) {
    topCustomersEl.innerHTML = topCustomers.map(([name, spent], i) => `
      <div class="flex items-center justify-between p-2 hover:bg-gray-50 rounded">
        <div class="flex items-center gap-3">
          <span class="text-xs font-bold text-blue-600">#${i+1}</span>
          <span class="text-sm text-gray-900">${name}</span>
        </div>
        <span class="text-xs font-semibold text-gray-600">$${spent.toFixed(2)}</span>
      </div>
    `).join('');
  } else {
    topCustomersEl.innerHTML = '<p class="text-sm text-gray-500">No customer data</p>';
  }

  // Order Status Breakdown
  const statusCount = {};
  allOrders.forEach(o => {
    const status = o.status || 'unknown';
    statusCount[status] = (statusCount[status] || 0) + 1;
  });
  
  const statusColors = {
    pending: 'bg-yellow-100 text-yellow-800',
    processing: 'bg-blue-100 text-blue-800',
    shipped: 'bg-cyan-100 text-cyan-800',
    delivered: 'bg-emerald-100 text-emerald-800',
    cancelled: 'bg-red-100 text-red-800'
  };

  const statusEl = document.getElementById('status-breakdown');
  const statusEntries = Object.entries(statusCount)
    .sort((a, b) => b[1] - a[1]);
  
  if (statusEntries.length) {
    statusEl.innerHTML = statusEntries.map(([status, count]) => `
      <div class="flex items-center justify-between p-2 hover:bg-gray-50 rounded">
        <div class="flex items-center gap-2">
          <span class="px-2 py-1 rounded text-xs font-semibold ${statusColors[status] || 'bg-gray-100 text-gray-800'}">
            ${status.charAt(0).toUpperCase() + status.slice(1)}
          </span>
        </div>
        <span class="text-sm font-semibold text-gray-900">${count}</span>
      </div>
    `).join('');
  } else {
    statusEl.innerHTML = '<p class="text-sm text-gray-500">No order data</p>';
  }
}

// Display Orders
function displayOrders() {
  const tbody = document.getElementById('orders-tbody');
  const start = (currentOrderPage - 1) * itemsPerPage;
  const end = start + itemsPerPage;
  const paginatedOrders = filteredOrders.slice(start, end);

  if (!paginatedOrders.length) {
    tbody.innerHTML = '<tr><td colspan="7" class="px-6 py-8 text-center text-gray-500">No orders found</td></tr>';
    return;
  }

  tbody.innerHTML = paginatedOrders.map(order => `
    <tr class="border-b border-gray-200 hover:bg-gray-50">
      <td class="px-6 py-4 font-semibold text-gray-900">#${order.id}</td>
      <td class="px-6 py-4 text-gray-600">${new Date(order.created_at).toLocaleDateString()}</td>
      <td class="px-6 py-4 text-gray-900">${order.customer_name || 'Unknown'}</td>
      <td class="px-6 py-4 text-gray-600">${order.item_count || 0} items</td>
      <td class="px-6 py-4 font-semibold text-emerald-600">$${parseFloat(order.total_amount).toFixed(2)}</td>
      <td class="px-6 py-4">
        <span class="px-3 py-1 rounded-full text-xs font-semibold ${order.payment_status === 'paid' ? 'bg-emerald-100 text-emerald-800' : 'bg-yellow-100 text-yellow-800'}">
          ${order.payment_status || 'Pending'}
        </span>
      </td>
      <td class="px-6 py-4">
        <span class="px-3 py-1 rounded-full text-xs font-semibold ${order.status === 'delivered' ? 'bg-emerald-100 text-emerald-800' : order.status === 'shipped' ? 'bg-blue-100 text-blue-800' : 'bg-gray-100 text-gray-800'}">
          ${order.status || 'Pending'}
        </span>
      </td>
    </tr>
  `).join('');
}

// Display Payments
function displayPayments() {
  const tbody = document.getElementById('payments-tbody');
  const start = (currentPaymentPage - 1) * itemsPerPage;
  const end = start + itemsPerPage;
  const paginatedPayments = filteredPayments.slice(start, end);

  if (!paginatedPayments.length) {
    tbody.innerHTML = '<tr><td colspan="7" class="px-6 py-8 text-center text-gray-500">No payments found</td></tr>';
    return;
  }

  tbody.innerHTML = paginatedPayments.map(payment => `
    <tr class="border-b border-gray-200 hover:bg-gray-50">
      <td class="px-6 py-4 text-gray-600">${new Date(payment.created_at).toLocaleDateString()}</td>
      <td class="px-6 py-4 text-gray-900">${payment.customer_name || 'Unknown'}</td>
      <td class="px-6 py-4 text-gray-600">${payment.product_name || 'Service'}</td>
      <td class="px-6 py-4 font-semibold text-emerald-600">$${parseFloat(payment.amount).toFixed(2)}</td>
      <td class="px-6 py-4 text-gray-600">${payment.payment_method || 'Unknown'}</td>
      <td class="px-6 py-4">
        <span class="px-3 py-1 rounded-full text-xs font-semibold ${payment.status === 'paid' ? 'bg-emerald-100 text-emerald-800' : payment.status === 'pending' ? 'bg-yellow-100 text-yellow-800' : 'bg-red-100 text-red-800'}">
          ${payment.status || 'Unknown'}
        </span>
      </td>
      <td class="px-6 py-4 text-gray-600">${payment.updated_at ? new Date(payment.updated_at).toLocaleDateString() : 'N/A'}</td>
    </tr>
  `).join('');
}

// Show Message
function showMessage(message, isError = false) {
  console.log(isError ? `Error: ${message}` : `Success: ${message}`);
}

// Pagination
function nextPage() {
  const totalPages = Math.ceil(filteredOrders.length / itemsPerPage);
  if (currentOrderPage < totalPages) {
    currentOrderPage++;
    displayOrders();
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }
}

function prevPage() {
  if (currentOrderPage > 1) {
    currentOrderPage--;
    displayOrders();
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }
}

function nextPaymentPage() {
  const totalPages = Math.ceil(filteredPayments.length / itemsPerPage);
  if (currentPaymentPage < totalPages) {
    currentPaymentPage++;
    displayPayments();
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }
}

function prevPaymentPage() {
  if (currentPaymentPage > 1) {
    currentPaymentPage--;
    displayPayments();
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }
}

// Tab Switching
function showTab(tab) {
  document.querySelectorAll('.tab-content').forEach(el => el.classList.add('hidden'));
  document.querySelectorAll('.tab-btn').forEach(btn => {
    btn.classList.remove('active', 'text-emerald-600', 'border-emerald-600');
    btn.classList.add('text-gray-600', 'border-transparent');
  });

  if (tab === 'orders') {
    document.getElementById('orders-tab').classList.remove('hidden');
    const btn = document.querySelector('[onclick="showTab(\'orders\')"]');
    btn?.classList.add('active', 'text-emerald-600', 'border-emerald-600');
    btn?.classList.remove('text-gray-600', 'border-transparent');
  } else {
    document.getElementById('payments-tab').classList.remove('hidden');
    const btn = document.querySelector('[onclick="showTab(\'payments\')"]');
    btn?.classList.add('active', 'text-emerald-600', 'border-emerald-600');
    btn?.classList.remove('text-gray-600', 'border-transparent');
  }
}

// Search Orders
document.getElementById('search-orders')?.addEventListener('keyup', function(e) {
  const term = e.target.value.toLowerCase();
  if (!term) {
    filteredOrders = [...allOrders];
  } else {
    filteredOrders = allOrders.filter(o => 
      o.id.toString().includes(term) || 
      (o.customer_name || '').toLowerCase().includes(term)
    );
  }
  document.getElementById('orders-count').textContent = filteredOrders.length;
  currentOrderPage = 1;
  displayOrders();
});

// Search Payments
document.getElementById('search-payments')?.addEventListener('keyup', function(e) {
  const term = e.target.value.toLowerCase();
  if (!term) {
    filteredPayments = [...allPayments];
  } else {
    filteredPayments = allPayments.filter(p => 
      (p.customer_name || '').toLowerCase().includes(term) || 
      (p.product_name || '').toLowerCase().includes(term)
    );
  }
  document.getElementById('payments-count').textContent = filteredPayments.length;
  currentPaymentPage = 1;
  displayPayments();
});

// Initialize on page load
window.addEventListener('DOMContentLoaded', () => {
  loadOrders();
  loadPayments();
});
</script>
</body>
</html>
