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

$pageTitle = 'Product Management';
$pageSection = 'products';

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">
                <!-- Dashboard Home -->
                <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>

                <!-- CATEGORY: BUSINESS OPERATIONS -->
                <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 text-emerald-100 hover:bg-emerald-700/50">
                    <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 bg-emerald-700 text-white">
                    <i class="fas fa-boxes w-5"></i>
                    <span>Products</span>
                </a>

                <!-- CATEGORY: CUSTOMERS -->
                <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>

                <!-- CATEGORY: INSIGHTS -->
                <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>

                <!-- CATEGORY: AUTOMATION & TOOLS -->
                <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>

                <!-- CATEGORY: SETTINGS -->
                <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">Product Management</h1>
                        <p class="text-sm text-gray-600 mt-1">Create, edit, and manage store products</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">

    <!-- Tab Navigation -->
    <div class="flex gap-4 mb-8 border-b border-gray-200">
      <button onclick="showTab('products')" 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>Products List
      </button>
      <button onclick="showTab('archived')" 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-archive mr-2"></i>Archived
      </button>
      <button onclick="showTab('add')" 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-plus mr-2"></i>Add Product
      </button>
    </div>

    <!-- Products List Tab -->
    <div id="products-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 Products</h2>
          <input type="text" id="search-products" placeholder="Search products..." 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">Product Name</th>
                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Category</th>
                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Price</th>
                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Stock</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-center text-sm font-semibold text-gray-900">Actions</th>
              </tr>
            </thead>
            <tbody id="products-tbody">
              <!-- Products will load here -->
            </tbody>
          </table>
        </div>

        <!-- Pagination -->
        <div class="mt-6 flex justify-between items-center">
          <p class="text-sm text-gray-600">Showing <span id="product-count">0</span> products</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>

    <!-- Archived Products Tab -->
    <div id="archived-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">Archived Products</h2>
          <p class="text-sm text-gray-600">Showing <span id="archived-count">0</span> archived products</p>
        </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">Product Name</th>
                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Category</th>
                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Price</th>
                <th class="px-6 py-3 text-left text-sm font-semibold text-gray-900">Stock</th>
                <th class="px-6 py-3 text-center text-sm font-semibold text-gray-900">Actions</th>
              </tr>
            </thead>
            <tbody id="archived-tbody">
              <!-- Archived products here -->
            </tbody>
          </table>
        </div>

        <div class="mt-6 flex justify-between items-center">
          <p class="text-sm text-gray-600">Use Restore to return an item or Purge to delete permanently.</p>
        </div>
      </div>
    </div>

    <!-- Add Product Tab -->
    <div id="add-tab" class="tab-content hidden">
      <div class="bg-white rounded-lg shadow p-8 max-w-2xl">
        <form id="product-form" onsubmit="submitProduct(event)">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <!-- Product Name -->
            <div class="md:col-span-2">
              <label class="block text-sm font-medium text-gray-700 mb-2">Product Name *</label>
              <input type="text" id="product-name" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-transparent" required placeholder="E.g., Healing Trinity Beef Soup">
            </div>

            <!-- Category -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">Category *</label>
              <select id="product-category" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-transparent" required>
                <option value="">Select a category</option>
              </select>
            </div>

            <!-- Price -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">Price ($) *</label>
              <input type="number" id="product-price" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-transparent" required step="0.01" min="0" placeholder="29.99">
            </div>

            <!-- Stock Quantity -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">Stock Quantity *</label>
              <input type="number" id="product-stock" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-transparent" required min="0" placeholder="50">
            </div>

            <!-- SKU -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">SKU</label>
              <input type="text" id="product-sku" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-transparent" placeholder="e.g., ATA-PRODUCT-123">
            </div>

            <!-- Description -->
            <div class="md:col-span-2">
              <label class="block text-sm font-medium text-gray-700 mb-2">Description</label>
              <textarea id="product-description" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-transparent h-32" placeholder="Detailed product description..."></textarea>
            </div>

            <!-- Image Upload -->
            <div class="md:col-span-2">
              <label class="block text-sm font-medium text-gray-700 mb-2">Product Image</label>
              <div class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center cursor-pointer hover:bg-gray-50 transition" onclick="document.getElementById('product-image').click()">
                <i class="fas fa-cloud-upload-alt text-4xl text-emerald-600 mb-4"></i>
                <p class="text-gray-900 font-semibold mb-2">Click to upload image</p>
                <p class="text-sm text-gray-600">or drag and drop</p>
                <input type="file" id="product-image" class="hidden" accept="image/*" onchange="previewImage(event)">
              </div>
              <div id="image-preview" class="mt-4 hidden">
                <img id="preview-img" src="" alt="Preview" class="h-48 w-48 object-cover rounded-lg">
                <button type="button" onclick="clearImage()" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 mt-2">Remove Image</button>
              </div>
            </div>

            <!-- Active Status -->
            <div class="md:col-span-2">
              <label class="flex items-center gap-3">
                <input type="checkbox" id="product-active" class="w-5 h-5 text-emerald-600 rounded focus:ring-emerald-500" checked>
                <span class="text-gray-900 font-medium">Active (visible in store)</span>
              </label>
            </div>
          </div>

          <!-- Buttons -->
          <div class="flex gap-4 mt-8">
            <button type="submit" class="px-6 py-3 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors font-semibold">
              <i class="fas fa-save mr-2"></i>Save Product
            </button>
            <button type="button" onclick="resetForm()" class="px-6 py-3 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors font-semibold">
              <i class="fas fa-redo mr-2"></i>Reset
            </button>
          </div>

          <p id="form-message" class="mt-4 hidden p-4 rounded-lg"></p>
        </form>
      </div>
    </div>
            </main>
        </div>
    </div>

<script>
let currentPage = 1;
const itemsPerPage = 10;
let allProducts = [];
let filteredProducts = [];
let archivedProducts = [];
let filteredArchived = [];

// Load Categories
async function loadCategories() {
  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/products/categories.php');
    const data = await response.json();
    if (!data.success) throw new Error(data.error || 'Failed to load categories');

    const select = document.getElementById('product-category');
    select.innerHTML = '<option value="">Select a category</option>';
    (data.categories || []).forEach(cat => {
      const option = document.createElement('option');
      option.value = cat.id;
      option.textContent = cat.name;
      select.appendChild(option);
    });
    console.log('Categories loaded:', data.categories?.length || 0);
  } catch (error) {
    console.error('Error loading categories:', error);
    showMessage('Error loading categories', true);
  }
}

// Load Products (active)
async function loadProducts() {
  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/products/list.php?limit=100&active=1');
    const data = await response.json();
    if (!data.success) throw new Error(data.error || 'Failed to load products');

    allProducts = data.products || [];
    filteredProducts = [...allProducts];
    document.getElementById('product-count').textContent = filteredProducts.length;
    displayProducts();
    console.log('Products loaded:', filteredProducts.length);
  } catch (error) {
    console.error('Error loading products:', error);
    showMessage('Error loading products', true);
  }
}

// Load Archived Products
async function loadArchivedProducts() {
  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/products/list.php?limit=200&active=0');
    const data = await response.json();
    if (!data.success) throw new Error(data.error || 'Failed to load archived products');

    archivedProducts = data.products || [];
    filteredArchived = [...archivedProducts];
    document.getElementById('archived-count').textContent = filteredArchived.length;
    displayArchivedProducts();
    console.log('Archived products loaded:', filteredArchived.length);
  } catch (error) {
    console.error('Error loading archived products:', error);
    showMessage('Error loading archived products', true);
  }
}

// Display Products
function displayProducts() {
  const tbody = document.getElementById('products-tbody');
  const start = (currentPage - 1) * itemsPerPage;
  const end = start + itemsPerPage;
  const paginatedProducts = filteredProducts.slice(start, end);

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

  tbody.innerHTML = paginatedProducts.map(product => `
    <tr class="border-b border-gray-200 hover:bg-gray-50">
      <td class="px-6 py-4 font-semibold text-gray-900">${product.name}</td>
      <td class="px-6 py-4 text-gray-600">${product.category_name || 'Uncategorized'}</td>
      <td class="px-6 py-4 font-semibold text-emerald-600">$${parseFloat(product.price).toFixed(2)}</td>
      <td class="px-6 py-4 text-gray-900">${product.stock_quantity}</td>
      <td class="px-6 py-4">
        <span class="px-3 py-1 rounded-full text-xs font-semibold ${product.active ? 'bg-emerald-100 text-emerald-800' : 'bg-gray-100 text-gray-800'}">
          ${product.active ? 'Active' : 'Inactive'}
        </span>
      </td>
      <td class="px-6 py-4 text-center">
        <button onclick="editProduct(${product.id})" class="text-blue-600 hover:text-blue-800 mr-3" title="Edit">
          <i class="fas fa-edit"></i>
        </button>
        <button onclick="deleteProduct(${product.id})" class="text-red-600 hover:text-red-800" title="Delete">
          <i class="fas fa-trash"></i>
        </button>
      </td>
    </tr>
  `).join('');
}

// Display Archived
function displayArchivedProducts() {
  const tbody = document.getElementById('archived-tbody');
  if (!filteredArchived.length) {
    tbody.innerHTML = '<tr><td colspan="5" class="px-6 py-8 text-center text-gray-500">No archived products</td></tr>';
    return;
  }

  tbody.innerHTML = filteredArchived.map(product => `
    <tr class="border-b border-gray-200 hover:bg-gray-50">
      <td class="px-6 py-4 font-semibold text-gray-900">${product.name}</td>
      <td class="px-6 py-4 text-gray-600">${product.category_name || 'Uncategorized'}</td>
      <td class="px-6 py-4 font-semibold text-emerald-600">$${parseFloat(product.price).toFixed(2)}</td>
      <td class="px-6 py-4 text-gray-900">${product.stock_quantity}</td>
      <td class="px-6 py-4 text-center space-x-3">
        <button onclick="restoreProduct(${product.id})" class="text-emerald-600 hover:text-emerald-800" title="Restore">
          <i class="fas fa-undo"></i>
        </button>
        <button onclick="purgeProduct(${product.id})" class="text-red-600 hover:text-red-800" title="Delete permanently">
          <i class="fas fa-trash"></i>
        </button>
      </td>
    </tr>
  `).join('');
}

// Show Message
function showMessage(message, isError = false) {
  const msgEl = document.getElementById('form-message');
  msgEl.textContent = message;
  msgEl.className = 'mt-4 p-4 rounded-lg ' + (isError ? 'bg-red-100 text-red-700' : 'bg-emerald-100 text-emerald-700');
  msgEl.classList.remove('hidden');
  setTimeout(() => msgEl.classList.add('hidden'), 5000);
}

// Submit Product
async function submitProduct(event) {
  event.preventDefault();

  const categoryId = document.getElementById('product-category').value;
  if (!categoryId) {
    showMessage('Please select a category', true);
    return;
  }

  const formData = new FormData();
  formData.append('name', document.getElementById('product-name').value);
  formData.append('category_id', categoryId);
  formData.append('price', document.getElementById('product-price').value);
  formData.append('stock_quantity', document.getElementById('product-stock').value);
  formData.append('sku', document.getElementById('product-sku').value);
  formData.append('description', document.getElementById('product-description').value);
  formData.append('active', document.getElementById('product-active').checked ? '1' : '0');

  const imageFile = document.getElementById('product-image').files[0];
  if (imageFile) formData.append('image', imageFile);

  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/products/create.php', {
      method: 'POST',
      body: formData,
      credentials: 'same-origin'
    });

    const responseText = await response.text();
    let data;
    try {
      data = JSON.parse(responseText);
    } catch (err) {
      console.error('Invalid JSON:', responseText);
      showMessage('Server error while creating product', true);
      return;
    }

    if (data.success) {
      showMessage('Product created successfully!');
      resetForm();
      await loadProducts();
      setTimeout(() => showTab('products'), 1000);
    } else {
      showMessage(data.error || data.message || 'Error creating product', true);
    }
  } catch (error) {
    console.error('Network error:', error);
    showMessage('Network error: ' + error.message, true);
  }
}

// Archive (soft delete)
async function deleteProduct(productId) {
  if (!confirm('Archive this product? You can restore it later.')) return;

  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/products/archive.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ id: productId, action: 'archive' })
    });

    const data = await response.json();
    if (data.success) {
      showMessage('Product archived.');
      await loadProducts();
      await loadArchivedProducts();
    } else {
      showMessage(data.message || 'Error archiving product', true);
    }
  } catch (error) {
    console.error('Error archiving product:', error);
    showMessage('Error archiving product', true);
  }
}

async function restoreProduct(productId) {
  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/products/archive.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ id: productId, action: 'restore' })
    });

    const data = await response.json();
    if (data.success) {
      showMessage('Product restored.');
      await loadProducts();
      await loadArchivedProducts();
    } else {
      showMessage(data.message || 'Error restoring product', true);
    }
  } catch (error) {
    console.error('Error restoring product:', error);
    showMessage('Error restoring product', true);
  }
}

async function purgeProduct(productId) {
  if (!confirm('Permanently delete this product? This cannot be undone.')) return;

  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/products/purge.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ id: productId })
    });

    const data = await response.json();
    if (data.success) {
      showMessage('Product permanently deleted.');
      await loadArchivedProducts();
    } else {
      showMessage(data.message || 'Error deleting product', true);
    }
  } catch (error) {
    console.error('Error purging product:', error);
    showMessage('Error deleting product', true);
  }
}

// Edit Product (placeholder)
function editProduct(productId) {
  alert('Edit feature coming soon. Product ID: ' + productId);
}

// Image Preview
function previewImage(event) {
  const file = event.target.files[0];
  if (!file) return;
  const reader = new FileReader();
  reader.onload = function(e) {
    document.getElementById('preview-img').src = e.target.result;
    document.getElementById('image-preview').classList.remove('hidden');
  };
  reader.readAsDataURL(file);
}

function clearImage() {
  document.getElementById('product-image').value = '';
  document.getElementById('image-preview').classList.add('hidden');
}

function resetForm() {
  document.getElementById('product-form').reset();
  clearImage();
}

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

function prevPage() {
  if (currentPage > 1) {
    currentPage--;
    displayProducts();
    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 === 'products') {
    document.getElementById('products-tab').classList.remove('hidden');
    const btn = document.querySelector('[onclick="showTab(\'products\')"]');
    btn?.classList.add('active', 'text-emerald-600', 'border-emerald-600');
    btn?.classList.remove('text-gray-600', 'border-transparent');
  } else if (tab === 'archived') {
    document.getElementById('archived-tab').classList.remove('hidden');
    const btn = document.querySelector('[onclick="showTab(\'archived\')"]');
    btn?.classList.add('active', 'text-emerald-600', 'border-emerald-600');
    btn?.classList.remove('text-gray-600', 'border-transparent');
  } else {
    document.getElementById('add-tab').classList.remove('hidden');
    const btn = document.querySelector('[onclick="showTab(\'add\')"]');
    btn?.classList.add('active', 'text-emerald-600', 'border-emerald-600');
    btn?.classList.remove('text-gray-600', 'border-transparent');
  }
}

// Search Products
document.getElementById('search-products')?.addEventListener('keyup', function(e) {
  const term = e.target.value.toLowerCase();
  if (!term) {
    filteredProducts = [...allProducts];
  } else {
    filteredProducts = allProducts.filter(p => p.name.toLowerCase().includes(term));
  }
  document.getElementById('product-count').textContent = filteredProducts.length;
  currentPage = 1;
  displayProducts();
});

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