const API_URL = '/api/cafeorder'; // Replace with your backend API endpoint

document.addEventListener('DOMContentLoaded', () => {
    const companyId=sessionStorage.getItem('companyId');
const branchId=sessionStorage.getItem('branchId');
const userId=sessionStorage.getItem('userId');

  const ordersTableBody = document.getElementById('ordersTable').querySelector('tbody');

  // Fetch and display orders on page load
  fetchOrders();


  async function fetchOrders() {
    try {

      
      const response = await fetch(API_URL+`?companyId=${companyId}&branchId=${branchId}`);
      const data = await response.json();
     

      if (data.success) {
        renderOrders(data.data);
      } else {
        // Show toast notification instead of alert
        if (window.showToast) {
          window.showToast('Failed to fetch orders.', 'error', 3000);
        } else {
          alert('Failed to fetch orders.');
        }
      }

    } catch (error) {
      console.error('Error fetching orders:', error);
    }
  }



  // Render orders in the table
  function renderOrders(orders) {
    ordersTableBody.innerHTML = '';
    orders.forEach((order) => {
      const row = document.createElement('tr');
      row.innerHTML = `
        <td>${order.userId}</td>
        <td>${order.itemId}</td>
        <td>${order.quantity}</td>
        <td>${order.status}</td>
        <td>
          <button class="edit-btn" data-id="${order._id}">Edit</button>
          <button class="delete-btn" data-id="${order._id}">Delete</button>
        </td>
      `;
      ordersTableBody.appendChild(row);
    });

    // Attach event listeners for edit and delete buttons
    document.querySelectorAll('.edit-btn').forEach((button) => {
      button.addEventListener('click', () => editOrder(button.dataset.id));
    });
    document.querySelectorAll('.delete-btn').forEach((button) => {
      button.addEventListener('click', () => deleteOrder(button.dataset.id));
    });
  }

  // Edit an order
  async function editOrder(orderId) {
    const newStatus = prompt('Enter new status (Pending, Paid, served, cancelled):');
    if (!newStatus || !['Pending', 'Paid', 'served', 'cancelled'].includes(newStatus)) {
      // Show toast notification instead of alert
      if (window.showToast) {
        window.showToast('Invalid status.', 'error', 3000);
      } else {
        alert('Invalid status.');
      }
      return;
    }

    try {
      const response = await fetch(`${API_URL}/${orderId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: newStatus }),
      });
      const data = await response.json();
      if (data.success) {
        // Show toast notification instead of alert
        if (window.showToast) {
          window.showToast('Order updated successfully!', 'success', 3000);
        } else {
          alert('Order updated successfully!');
        }
        fetchOrders();
      } else {
        // Show toast notification instead of alert
        if (window.showToast) {
          window.showToast('Failed to update order.', 'error', 3000);
        } else {
          alert('Failed to update order.');
        }
      }
    } catch (error) {
      console.error('Error updating order:', error);
    }
  }

  // Delete an order
  async function deleteOrder(orderId) {
    if (!confirm('Are you sure you want to delete this order?')) return;

    try {
      const response = await fetch(`${API_URL}/${orderId}`, { method: 'DELETE' });
      const data = await response.json();
      if (data.success) {
        // Show toast notification instead of alert
        if (window.showToast) {
          window.showToast('Order deleted successfully!', 'success', 3000);
        } else {
          alert('Order deleted successfully!');
        }
        fetchOrders();
      } else {
        // Show toast notification instead of alert
        if (window.showToast) {
          window.showToast('Failed to delete order.', 'error', 3000);
        } else {
          alert('Failed to delete order.');
        }
      }
    } catch (error) {
      console.error('Error deleting order:', error);
    }
  }
});
