<?php
include __DIR__ . '/../db.php';
?>

<!-- Delivery Order Management Modal -->
<div class="modal fade" id="deliveryModal" tabindex="-1" aria-labelledby="deliveryModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title" id="deliveryModalLabel">
          <i class="fas fa-truck me-2"></i>Delivery Order Management
        </h5>
        <div class="d-flex gap-2">
          <button type="button" class="btn btn-outline-light btn-sm" onclick="refreshDeliveryOrders()">
            <i class="fas fa-sync-alt"></i> Refresh
          </button>
          <button type="button" class="btn btn-outline-light btn-sm" onclick="createNewDeliveryOrder()">
            <i class="fas fa-plus"></i> New Order
          </button>
          <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
      </div>
      
      <div class="modal-body">
        <!-- Statistics Panel -->
        <div class="row mb-4">
          <div class="col-md-4">
            <div class="card bg-info text-white">
              <div class="card-body text-center">
                <h4 class="mb-1" id="total-delivery-orders">0</h4>
                <small>Total Orders</small>
              </div>
            </div>
          </div>
          <div class="col-md-4">
            <div class="card bg-warning text-white">
              <div class="card-body text-center">
                <h4 class="mb-1" id="active-delivery-orders">0</h4>
                <small>Active Orders</small>
              </div>
            </div>
          </div>
          <div class="col-md-4">
            <div class="card bg-success text-white">
              <div class="card-body text-center">
                <h4 class="mb-1" id="total-delivery-amount">Rs 0.00</h4>
                <small>Total Amount</small>
              </div>
            </div>
          </div>
        </div>

        <!-- Delivery Orders List -->
        <div class="card">
          <div class="card-header">
            <h6 class="mb-0">
              <i class="fas fa-list me-2"></i>Existing Delivery Orders
            </h6>
          </div>
          <div class="card-body">
            <div id="delivery-orders-container">
              <div class="text-center py-4">
                <div class="spinner-border text-primary" role="status">
                  <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mt-2 text-muted">Loading delivery orders...</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Delivery Context Menu -->
<div id="delivery-context-menu" class="context-menu">
  <div class="context-menu-header">
    <span id="delivery-context-order-name">Order</span>
  </div>
  <div id="delivery-context-actions" class="context-menu-actions">
    <!-- Actions will be populated dynamically -->
  </div>
</div>

<!-- Delivery Order Details Modal -->
<div class="modal fade" id="deliveryOrderDetailsModal" tabindex="-1" aria-labelledby="deliveryOrderDetailsModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header bg-info text-white">
        <h5 class="modal-title" id="deliveryOrderDetailsModalLabel">
          <i class="fas fa-eye me-2"></i>Delivery Order Details
        </h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div id="delivery-order-details-content">
          <!-- Content will be populated dynamically -->
        </div>
      </div>
    </div>
  </div>
</div>

<script>
// Load delivery orders when modal opens
document.getElementById('deliveryModal').addEventListener('shown.bs.modal', function() {
  loadDeliveryOrders();
});

// Load delivery orders
function loadDeliveryOrders() {
  fetch('ajax/get_delivery_orders.php')
    .then(res => res.json())
    .then(data => {
      if (data.success) {
        updateDeliveryStats(data.stats);
        updateDeliveryOrdersList(data.orders);
      } else {
        console.error('Error loading delivery orders:', data.error);
        document.getElementById('delivery-orders-container').innerHTML = 
          '<div class="text-center py-4"><p class="text-danger">Error loading delivery orders</p></div>';
      }
    })
    .catch(error => {
      console.error('Error:', error);
      document.getElementById('delivery-orders-container').innerHTML = 
        '<div class="text-center py-4"><p class="text-danger">Error loading delivery orders</p></div>';
    });
}

// Update delivery statistics
function updateDeliveryStats(stats) {
  document.getElementById('total-delivery-orders').textContent = stats.total_orders;
  document.getElementById('active-delivery-orders').textContent = stats.active_orders;
  document.getElementById('total-delivery-amount').textContent = 'Rs ' + parseFloat(stats.total_amount).toFixed(2);
}

// Update delivery orders list
function updateDeliveryOrdersList(orders) {
  const container = document.getElementById('delivery-orders-container');
  
  if (orders.length === 0) {
    container.innerHTML = `
      <div class="text-center py-4">
        <i class="fas fa-truck fa-3x text-muted mb-3"></i>
        <h5 class="text-muted">No Delivery Orders</h5>
        <p class="text-muted">No existing delivery orders found. Create a new order to get started.</p>
      </div>
    `;
    return;
  }
  
  let html = '<div class="delivery-orders-grid">';
  
  orders.forEach((order, index) => {
    const orderDate = new Date(order.created_at).toLocaleString();
    const hasKDS = order.has_running_orders;
    
    html += `
      <div class="delivery-order-card" data-order-id="${order.id}" onclick="showDeliveryContextMenu(event, ${order.id}, '${order.reference}', '${order.customer_name}')">
        <div class="order-header">
          <div class="order-reference">${order.reference}</div>
          <div class="order-status">
            <span class="badge ${hasKDS ? 'bg-warning' : 'bg-info'}">${hasKDS ? 'KDS Active' : 'Held'}</span>
          </div>
        </div>
        <div class="order-customer">${order.customer_name}</div>
        <div class="order-amount">Rs ${parseFloat(order.total_amount).toFixed(2)}</div>
        <div class="order-time">${orderDate}</div>
      </div>
    `;
  });
  
  html += '</div>';
  container.innerHTML = html;
}

// Refresh delivery orders
function refreshDeliveryOrders() {
  loadDeliveryOrders();
}

// Create new delivery order
function createNewDeliveryOrder() {
  // Hide context menu if it's open
  hideDeliveryContextMenu();
  
  // Show delivery setup modal instead
  const deliverySetupModal = new bootstrap.Modal(document.getElementById('deliverySetupModal'));
  deliverySetupModal.show();
  
  // Close delivery management modal
  const modal = bootstrap.Modal.getInstance(document.getElementById('deliveryModal'));
  if (modal) modal.hide();
}

// Show delivery context menu
function showDeliveryContextMenu(event, orderId, orderReference, customerName) {
  event.preventDefault();
  event.stopPropagation();
  
  const contextMenu = document.getElementById('delivery-context-menu');
  const orderNameSpan = document.getElementById('delivery-context-order-name');
  const actionsContainer = document.getElementById('delivery-context-actions');
  
  // Set order name
  orderNameSpan.textContent = orderReference;
  
  // Generate actions
  const actionsHtml = `
    <button class="context-menu-action" onclick="resumeDeliveryOrder(${orderId})">
      <i class="fas fa-play"></i>
      <span>Resume Order</span>
    </button>
    <button class="context-menu-action" onclick="viewDeliveryOrderDetails(${orderId})">
      <i class="fas fa-eye"></i>
      <span>View Details</span>
    </button>
    <button class="context-menu-action" onclick="printDeliveryProforma(${orderId})">
      <i class="fas fa-file-invoice"></i>
      <span>Print Proforma</span>
    </button>
  `;
  
  actionsContainer.innerHTML = actionsHtml;
  
  // Position context menu
  const rect = event.target.closest('.delivery-order-card').getBoundingClientRect();
  contextMenu.style.left = rect.left + 'px';
  contextMenu.style.top = (rect.top + rect.height / 2) + 'px';
  
  // Show context menu
  contextMenu.classList.add('show');
}

// Hide delivery context menu
function hideDeliveryContextMenu() {
  const contextMenu = document.getElementById('delivery-context-menu');
  contextMenu.classList.remove('show');
}

// Resume delivery order
function resumeDeliveryOrder(orderId) {
  fetch(`load_held_order.php?id=${orderId}`)
    .then(res => res.json())
    .then(data => {
      if (data.success) {
        // Hide context menu
        hideDeliveryContextMenu();
        
        // Close delivery modal
        bootstrap.Modal.getInstance(document.getElementById('deliveryModal')).hide();
        
        // Resume order (reuse existing logic from pos.js)
        resetCart();

        // ✅ Restore order mode and table
        window.selectedOrderMode = data.order.order_mode || 'delivery';
        window.selectedTableId = data.order.table_id || null;
        window.unholdOrderId = orderId;

        // Update order mode selector if it exists
        const orderModeSelect = document.getElementById('selected-order-mode');
        if (orderModeSelect) {
            orderModeSelect.value = window.selectedOrderMode || '';
        }
        
        // Update table selector if it exists
        const tableSelect = document.getElementById('selected-table-id');
        if (tableSelect) {
            tableSelect.value = window.selectedTableId || '';
        }

        // ✅ Set customer
        const customerName = data.order.customer_name || 'Walk-in';
        const customerDropdown = document.getElementById('top-customer-select');
        const formInput = document.getElementById('form-customer');
        if (customerDropdown) customerDropdown.value = customerName;
        if (formInput) formInput.value = customerName;

        // ✅ Restore cart items (directly add to cart with stored modifiers and remarks)
        data.items.forEach(item => {
            const modifiers = item.modifiers || [];
            const remarks = item.remarks || '';
            const taxType = 'percentage'; // Default tax type
            const taxRate = parseFloat(item.tax_rate) || 0;
            const code = item.item_name.replace(/\s+/g, '-').toLowerCase();
            const itemPrice = parseFloat(item.unit_price) || 0;
            
            // Add directly to cart bypassing modifier selection
            addItemToCart(item.item_id, item.item_name, itemPrice, code, taxType, taxRate, modifiers);
            
            // Set the correct quantity and remarks
            const uniqueCode = modifiers.length > 0 ? 
                `${code}-mod-${modifiers.map(m => m.id).sort().join('-')}` : code;
            const addedRow = document.querySelector(`.product-list[data-code="${uniqueCode}"]`);
            if (addedRow) {
                // Set quantity
                if (item.quantity > 1) {
                    const qtyInput = addedRow.querySelector('input[name="qty"]');
                    if (qtyInput) {
                        qtyInput.value = item.quantity;
                        addedRow.setAttribute('data-qty', item.quantity);
                    }
                }
                
                // Set remarks
                if (remarks) {
                    addedRow.setAttribute('data-remarks', remarks);
                    const remarksDisplay = addedRow.querySelector('.remarks-display');
                    if (remarksDisplay) {
                        remarksDisplay.textContent = remarks;
                        remarksDisplay.style.display = 'block';
                    }
                }
            }
        });

        // Update total
        updateTotal();

        // Show success message
        Swal.fire({
          icon: 'success',
          title: 'Order Resumed',
          text: 'Delivery order has been resumed successfully.',
          timer: 2000,
          showConfirmButton: false
        });
      } else {
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: 'Failed to resume order',
          confirmButtonColor: '#d33'
        });
      }
    })
    .catch(error => {
      console.error('Error resuming delivery order:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to resume order',
        confirmButtonColor: '#d33'
      });
    });
}

// View delivery order details
function viewDeliveryOrderDetails(orderId) {
  hideDeliveryContextMenu();
  
  // Show details modal
  const detailsModal = new bootstrap.Modal(document.getElementById('deliveryOrderDetailsModal'));
  detailsModal.show();
  
  // Load order details
  loadDeliveryOrderDetails(orderId);
}

// Load delivery order details
function loadDeliveryOrderDetails(orderId) {
  fetch(`load_held_order.php?id=${orderId}`)
    .then(res => res.json())
    .then(data => {
      if (data.success) {
        updateDeliveryOrderDetails(data.order, data.items);
      } else {
        document.getElementById('delivery-order-details-content').innerHTML = 
          '<div class="alert alert-danger">Error loading order details</div>';
      }
    })
    .catch(error => {
      console.error('Error loading delivery order details:', error);
      document.getElementById('delivery-order-details-content').innerHTML = 
        '<div class="alert alert-danger">Error loading order details</div>';
    });
}

// Update delivery order details
function updateDeliveryOrderDetails(order, items) {
  const content = document.getElementById('delivery-order-details-content');
  const orderDate = new Date(order.created_at).toLocaleString();
  
  let html = `
    <div class="row">
      <div class="col-md-6">
        <h6>Order Information</h6>
        <table class="table table-sm">
          <tr><td><strong>Reference:</strong></td><td>DEL-${String(order.id).padStart(6, '0')}</td></tr>
          <tr><td><strong>Customer:</strong></td><td>${order.customer_name}</td></tr>
          <tr><td><strong>Total Amount:</strong></td><td>Rs ${parseFloat(order.total_amount).toFixed(2)}</td></tr>
          <tr><td><strong>Created:</strong></td><td>${orderDate}</td></tr>
        </table>
      </div>
      <div class="col-md-6">
        <h6>Order Items</h6>
        <div class="order-items">
          <div class="items-list">
  `;
  
  items.forEach(item => {
    const modifiers = item.modifiers || [];
    const modifierText = modifiers.length > 0 ? 
      ' (' + modifiers.map(m => m.name).join(', ') + ')' : '';
    
    html += `
      <div class="item-row">
        <div class="item-name">${item.item_name}${modifierText}</div>
        <div class="item-qty">${item.quantity}</div>
        <div class="item-price">Rs ${parseFloat(item.unit_price).toFixed(2)}</div>
      </div>
    `;
    
    if (item.remarks) {
      html += `<div class="item-remarks"><small class="text-muted">Note: ${item.remarks}</small></div>`;
    }
  });
  
  html += `
          </div>
        </div>
      </div>
    </div>
  `;
  
  content.innerHTML = html;
}

// Print delivery proforma
function printDeliveryProforma(orderId) {
  hideDeliveryContextMenu();
  
  // Open proforma invoice in new window
  const proformaUrl = `print_proforma_invoice.php?id=${orderId}`;
  window.open(proformaUrl, '_blank', 'width=800,height=600');
}

// Hide context menu when clicking outside
document.addEventListener('click', function(event) {
  const contextMenu = document.getElementById('delivery-context-menu');
  const deliveryOrderCard = event.target.closest('.delivery-order-card');
  
  if (!deliveryOrderCard && !contextMenu.contains(event.target)) {
    hideDeliveryContextMenu();
  }
});
</script>
