<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
include __DIR__ . '/../db.php';
?>

<!-- Take Away Modal -->
<div class="modal fade dine-in-modal" id="takeAwayModal" tabindex="-1">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">
          <i class="fas fa-shopping-bag me-2"></i>Take Away Orders
        </h5>
        <div class="d-flex align-items-center">
          <button type="button" class="btn btn-outline-light btn-sm me-2" onclick="refreshTakeAwayOrders()">
            <i class="fas fa-sync-alt"></i> Refresh
          </button>
          <button type="button" class="btn btn-outline-light btn-sm me-2" onclick="createNewTakeAwayOrder()">
            <i class="fas fa-plus"></i> New Order
          </button>
          <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
        </div>
      </div>
      <div class="modal-body">
        <!-- Statistics Panel -->
        <div class="stats-panel">
          <div class="stats-grid">
            <div class="stat-item">
              <div class="stat-number" id="takeaway-total-orders">0</div>
              <div class="stat-label">Total Orders</div>
            </div>
            <div class="stat-item">
              <div class="stat-number" id="takeaway-total-items">0</div>
              <div class="stat-label">Total Items</div>
            </div>
            <div class="stat-item">
              <div class="stat-number" id="takeaway-total-amount">0</div>
              <div class="stat-label">Total Amount</div>
            </div>
            <div class="stat-item">
              <div class="stat-number" id="takeaway-active-kds">0</div>
              <div class="stat-label">Active KDS</div>
            </div>
          </div>
        </div>

        <!-- Orders List -->
        <div class="orders-section">
          <h6 class="mb-3">
            <i class="fas fa-list me-2"></i>Take Away Orders
            <span class="badge bg-secondary ms-2" id="takeaway-orders-count">0</span>
          </h6>
          <div id="takeaway-orders-container">
            <div class="text-center text-muted py-4">
              <i class="fas fa-spinner fa-spin"></i>
              <p class="mt-2">Loading orders...</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Take Away Context Menu -->
<div id="takeaway-context-menu" class="context-menu">
  <div class="context-menu-header">
    <i class="fas fa-shopping-bag me-2"></i>
    <span id="takeaway-context-order-name">Order</span>
  </div>
  <div class="context-menu-actions" id="takeaway-context-actions">
    <!-- Actions will be populated dynamically -->
  </div>
</div>

<!-- Take Away Order Details Modal -->
<div class="modal fade dine-in-modal" id="takeAwayOrderDetailsModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header py-3">
        <h5 class="modal-title">
          <i class="fas fa-eye me-2"></i>Order Details
        </h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body py-3">
        <!-- Order Information -->
        <div class="row mb-3">
          <div class="col-12">
            <div class="card border-0 bg-light">
              <div class="card-body p-3">
                <div class="d-flex justify-content-between align-items-center mb-2">
                  <h6 class="mb-0">
                    <i class="fas fa-shopping-bag me-2"></i>
                    <span id="takeaway-detail-order-name">Loading...</span>
                    <span class="badge ms-2" id="takeaway-detail-order-status">Loading...</span>
                  </h6>
                  <span class="h5 mb-0 text-primary" id="takeaway-detail-amount">Loading...</span>
                </div>
                <div class="text-muted small">
                  <i class="fas fa-user me-1"></i>
                  <span id="takeaway-detail-customer">Loading...</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Order Items -->
        <div class="orders-section">
          <div class="d-flex justify-content-between align-items-center mb-2">
            <h6 class="mb-0">
              <i class="fas fa-list me-2"></i>Order Items
            </h6>
          </div>
          <div id="takeaway-order-items-container">
            <div class="text-center text-muted py-3">
              <i class="fas fa-spinner fa-spin"></i>
              <p class="mt-2 mb-0">Loading order items...</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
// Take Away Modal Management
let takeAwayData = { orders: [], stats: {} };

document.addEventListener("DOMContentLoaded", function () {
  // Load take-away orders when modal is shown
  const takeAwayModal = document.getElementById('takeAwayModal');
  takeAwayModal.addEventListener('show.bs.modal', function () {
    loadTakeAwayOrders();
  });
});

// Load take-away orders data
async function loadTakeAwayOrders() {
  try {
    const response = await fetch('ajax/get_take_away_orders.php');
    const data = await response.json();
    
    if (!data.success) {
      throw new Error(data.message || 'Failed to load take-away orders');
    }
    
    takeAwayData = data;
    
    // Update statistics
    updateTakeAwayStats(data.stats);
    
    // Update orders list
    updateTakeAwayOrdersList(data.orders);
    
  } catch (error) {
    console.error('Error loading take-away orders:', error);
    Swal.fire({
      icon: 'error',
      title: 'Error',
      text: 'Failed to load take-away orders: ' + error.message,
      confirmButtonColor: '#d33'
    });
  }
}

// Update take-away statistics
function updateTakeAwayStats(stats) {
  document.getElementById('takeaway-total-orders').textContent = stats.total_orders;
  document.getElementById('takeaway-total-items').textContent = stats.total_items;
  document.getElementById('takeaway-total-amount').textContent = 'Rs ' + parseFloat(stats.total_amount).toFixed(2);
  document.getElementById('takeaway-active-kds').textContent = stats.has_active_kds ? 'Yes' : 'No';
}

// Update take-away orders list
function updateTakeAwayOrdersList(orders) {
  const container = document.getElementById('takeaway-orders-container');
  const countBadge = document.getElementById('takeaway-orders-count');
  
  countBadge.textContent = orders.length;
  
  if (orders.length === 0) {
    container.innerHTML = `
      <div class="text-center text-muted py-5">
        <i class="fas fa-shopping-bag"></i>
        <p class="mt-3">No take-away orders found</p>
        <button type="button" class="btn btn-primary" onclick="createNewTakeAwayOrder()">
          <i class="fas fa-plus me-1"></i>Create New Order
        </button>
      </div>
    `;
    return;
  }
  
  let html = '<div class="takeaway-orders-grid">';
  
  orders.forEach((order, index) => {
    const orderDate = new Date(order.created_at).toLocaleString();
    const hasKDS = order.has_running_orders;
    
    html += `
      <div class="takeaway-order-card" data-order-id="${order.id}" onclick="showTakeAwayContextMenu(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 take-away orders
function refreshTakeAwayOrders() {
  loadTakeAwayOrders();
}

// Create new take-away order
function createNewTakeAwayOrder() {
  // Hide context menu if it's open
  hideTakeAwayContextMenu();
  
  // Set order mode to take-away
  window.selectedOrderMode = 'take_away';
  window.selectedTableId = null;
  window.unholdOrderId = null; // Clear any existing order ID for new order
  
  // Update form inputs
  document.getElementById('selected-order-mode').value = 'take_away';
  document.getElementById('selected-table-id').value = '';
  
  // Close modal
  const modal = bootstrap.Modal.getInstance(document.getElementById('takeAwayModal'));
  if (modal) modal.hide();
  
  // Show success message
  Swal.fire({
    icon: 'success',
    title: 'Take Away Mode Selected',
    text: 'You can now add items to create a new take-away order.',
    timer: 2000,
    showConfirmButton: false
  });
}

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

        // ✅ Restore order mode and table
        window.selectedOrderMode = data.order.order_mode || 'take_away';
        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"]');
                    qtyInput.value = item.quantity;
                }
                
                // Set remarks
                if (remarks) {
                    addedRow.setAttribute('data-remarks', remarks);
                    const remarksSection = addedRow.querySelector('.remarks-section');
                    const remarksText = addedRow.querySelector('.remarks-text');
                    if (remarksSection && remarksText) {
                        remarksSection.style.display = 'block';
                        remarksText.textContent = `💬 ${remarks}`;
                    }
                }
            }
        });
        
        // Update totals after adding all items
        updateTotal();
        
        // Show success message
        Swal.fire({
          icon: 'success',
          title: 'Order Resumed',
          text: 'Take-away order has been loaded back to cart',
          timer: 2000,
          showConfirmButton: false
        });
      } else {
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: data.error || 'Failed to resume order',
          confirmButtonColor: '#d33'
        });
      }
    })
    .catch(error => {
      console.error('Error resuming take-away order:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to resume order',
        confirmButtonColor: '#d33'
      });
    });
}

// Show take-away context menu
function showTakeAwayContextMenu(event, orderId, orderReference, customerName) {
  event.preventDefault();
  event.stopPropagation();
  
  const contextMenu = document.getElementById('takeaway-context-menu');
  const orderNameSpan = document.getElementById('takeaway-context-order-name');
  const actionsContainer = document.getElementById('takeaway-context-actions');
  
  // Set order name
  orderNameSpan.textContent = orderReference;
  
  // Generate actions
  const actionsHtml = `
    <button class="context-menu-action" onclick="resumeTakeAwayOrder(${orderId})">
      <i class="fas fa-play"></i>
      <span>Resume Order</span>
    </button>
    <button class="context-menu-action" onclick="viewTakeAwayOrderDetails(${orderId})">
      <i class="fas fa-eye"></i>
      <span>View Details</span>
    </button>
    <button class="context-menu-action" onclick="printTakeAwayProforma(${orderId})">
      <i class="fas fa-file-invoice"></i>
      <span>Print Proforma</span>
    </button>
  `;
  
  actionsContainer.innerHTML = actionsHtml;
  
  // Position context menu
  const rect = event.target.closest('.takeaway-order-card').getBoundingClientRect();
  contextMenu.style.left = rect.right + 10 + 'px';
  contextMenu.style.top = rect.top + 'px';
  contextMenu.classList.add('show');
  
  // Store current order info
  window.currentTakeAwayOrderId = orderId;
  window.currentTakeAwayOrderReference = orderReference;
  window.currentTakeAwayCustomerName = customerName;
}

// Hide take-away context menu
function hideTakeAwayContextMenu() {
  const contextMenu = document.getElementById('takeaway-context-menu');
  contextMenu.classList.remove('show');
}

// View take-away order details
function viewTakeAwayOrderDetails(orderId) {
  // Hide context menu
  hideTakeAwayContextMenu();
  
  // Show order details modal
  const modal = new bootstrap.Modal(document.getElementById('takeAwayOrderDetailsModal'));
  modal.show();
  
  // Load order details
  loadTakeAwayOrderDetails(orderId);
}

// Load take-away order details
async function loadTakeAwayOrderDetails(orderId) {
  try {
    const response = await fetch(`load_held_order.php?id=${orderId}`);
    const data = await response.json();
    
    if (!data.success) {
      throw new Error(data.error || 'Failed to load order details');
    }
    
    // Update order information
    document.getElementById('takeaway-detail-order-name').textContent = `HOLD-${String(orderId).padStart(6, '0')}`;
    document.getElementById('takeaway-detail-customer').textContent = data.order.customer_name || 'Walk-in Customer';
    document.getElementById('takeaway-detail-amount').textContent = 'Rs ' + parseFloat(data.order.total_amount).toFixed(2);
    
    // Update status badge
    const statusBadge = document.getElementById('takeaway-detail-order-status');
    statusBadge.textContent = 'Held';
    statusBadge.className = 'badge ms-2 bg-info';
    
    // Update order items
    updateTakeAwayOrderItems(data.items);
    
    // Update payment breakdown if available
    updateTakeAwayPaymentBreakdown(data);
    
  } catch (error) {
    console.error('Error loading take-away order details:', error);
    Swal.fire({
      icon: 'error',
      title: 'Error',
      text: 'Failed to load order details',
      confirmButtonColor: '#d33'
    });
  }
}

// Update take-away order items display
function updateTakeAwayOrderItems(items) {
  const container = document.getElementById('takeaway-order-items-container');
  
  if (items.length === 0) {
    container.innerHTML = `
      <div class="text-center text-muted py-4">
        <i class="fas fa-shopping-bag"></i>
        <p class="mt-2">No items in this order</p>
      </div>
    `;
    return;
  }
  
  let html = '';
  
  items.forEach((item, index) => {
    const modifiers = item.modifiers && item.modifiers.length > 0 ? 
      ` (${item.modifiers.map(m => m.name).join(', ')})` : '';
    const remarks = item.remarks ? ` - ${item.remarks}` : '';
    
    html += `
      <div class="d-flex justify-content-between align-items-center py-1 border-bottom">
        <div class="flex-grow-1">
          <div class="fw-bold" style="font-size: 0.7rem;">${item.item_name}</div>
          ${modifiers || remarks ? `<div class="text-muted" style="font-size: 0.6rem;">${modifiers}${remarks}</div>` : ''}
          <div class="text-muted" style="font-size: 0.6rem;">Unit: Rs ${parseFloat(item.unit_price).toFixed(2)}</div>
        </div>
        <div class="text-end">
          <span class="badge bg-secondary me-1" style="font-size: 0.6rem;">${item.quantity}x</span>
          <span class="fw-bold" style="font-size: 0.7rem;">Rs ${parseFloat(item.quantity * item.unit_price).toFixed(2)}</span>
        </div>
      </div>
    `;
  });
  
  container.innerHTML = html;
}

// Update payment breakdown for take-away orders
function updateTakeAwayPaymentBreakdown(data) {
  const container = document.getElementById('takeaway-payment-breakdown-container');
  
  if (!container) {
    // Create container if it doesn't exist
    const itemsContainer = document.getElementById('takeaway-order-items-container');
    if (itemsContainer && data.payment_totals && Object.keys(data.payment_totals).length > 0) {
      const breakdownHtml = `
        <div class="payment-breakdown mt-2" id="takeaway-payment-breakdown-container">
          <h6 class="text-primary mb-1 small">
            <i class="fas fa-credit-card me-1"></i>Payment Options
          </h6>
          <div class="row">
            ${Object.entries(data.payment_totals)
              .filter(([method]) => method === 'cash' || method === 'card')
              .map(([method, paymentData]) => `
              <div class="col-6 mb-1">
                <div class="border rounded p-1 bg-light">
                  <div class="d-flex justify-content-between align-items-center">
                    <div>
                      <span class="fw-bold text-capitalize" style="font-size: 0.7rem;">${method}</span>
                      <div class="text-muted" style="font-size: 0.6rem;">(${paymentData.rate.toFixed(1)}% tax)</div>
                    </div>
                    <div class="text-end">
                      <div class="fw-bold text-primary" style="font-size: 0.7rem;">Rs ${paymentData.total.toFixed(2)}</div>
                      <div class="text-muted" style="font-size: 0.6rem;">Rs ${paymentData.subtotal.toFixed(2)} + Rs ${paymentData.tax_amount.toFixed(2)}</div>
                    </div>
                  </div>
                </div>
              </div>
            `).join('')}
          </div>
        </div>
      `;
      itemsContainer.insertAdjacentHTML('afterend', breakdownHtml);
    }
  } else if (data.payment_totals && Object.keys(data.payment_totals).length > 0) {
    // Update existing container
    container.innerHTML = `
      <h6 class="text-primary mb-1 small">
        <i class="fas fa-credit-card me-1"></i>Payment Options
      </h6>
      <div class="row">
        ${Object.entries(data.payment_totals)
          .filter(([method]) => method === 'cash' || method === 'card')
          .map(([method, paymentData]) => `
          <div class="col-6 mb-1">
            <div class="border rounded p-1 bg-light">
              <div class="d-flex justify-content-between align-items-center">
                <div>
                  <span class="fw-bold text-capitalize" style="font-size: 0.7rem;">${method}</span>
                  <div class="text-muted" style="font-size: 0.6rem;">(${paymentData.rate.toFixed(1)}% tax)</div>
                </div>
                <div class="text-end">
                  <div class="fw-bold text-primary" style="font-size: 0.7rem;">Rs ${paymentData.total.toFixed(2)}</div>
                  <div class="text-muted" style="font-size: 0.6rem;">Rs ${paymentData.subtotal.toFixed(2)} + Rs ${paymentData.tax_amount.toFixed(2)}</div>
                </div>
              </div>
            </div>
          </div>
        `).join('')}
      </div>
    `;
  } else {
    // Hide container if no payment totals
    if (container) {
      container.style.display = 'none';
    }
  }
}

// View KDS for take-away order
function viewKDS(orderId) {
  window.open('kds.php', '_blank');
}

// Print proforma for take-away order
function printTakeAwayProforma(orderId) {
  // Hide context menu
  hideTakeAwayContextMenu();
  
  // Open proforma invoice print window
  const proformaWindow = window.open(`print_proforma_invoice.php?id=${orderId}`, 'Proforma_Print', 'width=800,height=900');
  if (proformaWindow) {
    proformaWindow.focus();
  } else {
    Swal.fire({
      icon: 'error',
      title: 'Popup Blocked',
      text: 'Please allow popups for this site to print proforma invoices',
      confirmButtonColor: '#d33'
    });
  }
}

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