<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Transfer Orders</title>
  <style>
    /* CSS for styling the page */
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      background-color: #f9f9f9;
    }

    h1 {
      text-align: center;
      padding: 20px;
      background-color: #4caf50;
      color: white;
      margin: 0;
    }

    #transferOrderList {
      margin: 20px auto;
      max-width: 800px;
      padding: 10px;
    }

    .transfer-order {
      border: 1px solid #ccc;
      border-radius: 8px;
      margin: 10px 0;
      padding: 15px;
      background-color: white;
      display: flex;
      flex-direction: column;
      gap: 10px;
    }

    button {
      padding: 8px 12px;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }

    .accept-btn {
      background-color: #4caf50;
      color: white;
    }

    .reject-btn {
      background-color: #f44336;
      color: white;
    }

    button:disabled {
      background-color: #ccc;
      cursor: not-allowed;
    }
  </style>
</head>
<body>
  <h1>Transfer Orders</h1>
  <div id="passcode-container">
    Enter PassCode:
    <input type="password" id="passCodeInput" required>
  </div>

  <div id="transferOrderList">
    <!-- Dynamic transfer order list will appear here -->
  </div>

  <script>

let currentUserId = null;




   // Add event listener to check input length and verify passcode
   const passCodeInput = document.getElementById("passCodeInput");

passCodeInput.addEventListener("input", function () {
  if (this.value.length === 4) {
    verifyPassCode(this.value);
  }
});

// Function to verify the passcode with the backend
async function verifyPassCode(passcode) {
  try {
    const response = await fetch(`api/users/getByPasscode?passcode=${passcode}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    });

    if (response.ok) {
      currentUserId = await response.json();
      getAllTransferOrders(currentUserId);
      passCodeInput.value = "";
    } else {
      alert('Invalid passcode. Please try again.');
    }
  } catch (error) {
    console.error('Error verifying passcode:', error);
    alert('An error occurred while verifying the passcode.');
  }
}




    // JavaScript for fetching and handling transfer orders
    async function getAllTransferOrders(userId) {

      try {
        const response = await fetch(`/api/cafeTransfer?userId=${userId}`); // Adjust API endpoint as needed
        const transferOrders = await response.json();

        const transferOrderList = document.getElementById('transferOrderList');
        transferOrderList.innerHTML = ''; // Clear existing content
console.log("orders",transferOrders);
        // Loop through transfer orders and create UI elements
        transferOrders.forEach(order => {
          const orderDiv = document.createElement('div');
          orderDiv.className = 'transfer-order';

          // Populate transfer order details
          orderDiv.innerHTML = `
  <p><strong>From:</strong> ${order.fromUserId.username || order.fromUserId}</p>
  <p><strong>To:</strong> ${order.toUserId.username || order.toUserId}</p>
  <p><strong>Order No:</strong> ${order.orderId.orderNo}</p>
  <p><strong>Status:</strong> ${order.status}</p>
  ${
    currentUserId === order.fromUserId._id
      ? `<button class="return-btn" onclick="updateTransferStatus('${userId}', '${order._id}', '${order.orderId._id}','return')" 
          ${order.status !== 'pending' ? 'disabled' : ''}>Return</button>`
      : `
        <button class="accept-btn" onclick="updateTransferStatus('${userId}', '${order._id}', '${order.orderId._id}', 'accept')" 
          ${order.status !== 'pending' ? 'disabled' : ''}>Accept</button>
        <button class="reject-btn" onclick="updateTransferStatus('${userId}', '${order._id}', '${order.orderId._id}', 'reject')" 
          ${order.status !== 'pending' ? 'disabled' : ''}>Reject</button>
      `
  }
`;

          transferOrderList.appendChild(orderDiv);
        });
      } catch (error) {
        console.error('Error fetching transfer orders:', error);
        alert('Failed to fetch transfer orders.');
      }
    }

    // Function to update the status of a transfer order
    async function updateTransferStatus(userId,transferId, orderId, action) {
      try {
      
        const response = await fetch('/api/cafeTransfer/perform-transfer', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        userId,
        transferId,
        orderId,
        action,
      }),
    });
    
        if (response.ok) {
          alert(`Order transfer ${action}ed successfully.`);
          getAllTransferOrders(currentUserId); // Refresh the list
        } else {
          alert('Failed to update transfer order status.');
        }
      } catch (error) {
        console.error(`Error updating transfer order status to ${status}:`, error);
        alert('An error occurred while updating the transfer order status.');
      }
    }

    // Load transfer orders when the page loads
   // document.addEventListener('DOMContentLoaded', getAllTransferOrders);
  </script>
</body>
</html>
