<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Printed Data History</title>
  <!-- Socket.IO Client Library -->
  <script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
  <style>
    :root {
      --primary-color: #007bff;
      --success-color: #28a745;
      --danger-color: #dc3545;
      --background-color: #f9f9f9;
      --card-background: white;
      --text-color: #333;
      --border-color: #ddd;
      --shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: Arial, sans-serif;
      background-color: var(--background-color);
      padding: 20px;
      color: var(--text-color);
    }

    .container {
      max-width: 1400px;
      margin: 0 auto;
      background-color: var(--card-background);
      border-radius: 8px;
      box-shadow: var(--shadow);
      padding: 30px;
    }

    h1 {
      text-align: center;
      color: var(--primary-color);
      margin-bottom: 30px;
      font-size: 2rem;
    }

    .table-container {
      overflow-x: auto;
    }

    table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 20px;
    }

    thead {
      background-color: var(--primary-color);
      color: white;
    }

    th, td {
      padding: 12px;
      text-align: left;
      border-bottom: 1px solid var(--border-color);
    }

    th {
      font-weight: bold;
      text-transform: uppercase;
      font-size: 0.85rem;
    }

    tbody tr:hover {
      background-color: #f5f5f5;
    }

    .print-btn {
      background-color: var(--primary-color);
      color: white;
      border: none;
      padding: 8px 16px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 0.9rem;
      transition: background-color 0.3s;
    }

    .print-btn:hover {
      background-color: #0056b3;
    }

    .print-btn:active {
      background-color: #004085;
    }

    .print-btn:disabled {
      background-color: #ccc;
      cursor: not-allowed;
    }

    /* Simple print type styling - just colored text */
    .type-new {
      color: #28a745;
      font-weight: bold;
      font-size: 0.9rem;
    }

    .type-update {
      color: #ffc107;
      font-weight: bold;
      font-size: 0.9rem;
    }

    .loading {
      text-align: center;
      padding: 20px;
      color: #666;
    }

    .error {
      text-align: center;
      padding: 20px;
      color: var(--danger-color);
      background-color: #f8d7da;
      border-radius: 4px;
      margin: 20px 0;
    }

    .empty-state {
      text-align: center;
      padding: 40px;
      color: #666;
    }

    .refresh-btn {
      background-color: var(--success-color);
      color: white;
      border: none;
      padding: 10px 20px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 1rem;
      margin-bottom: 20px;
      transition: background-color 0.3s;
    }

    .refresh-btn:hover {
      background-color: #218838;
    }

    /* Modal Styles */
    .detail-modal {
      display: none;
      position: fixed;
      z-index: 10000;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: auto;
      background-color: rgba(0, 0, 0, 0.5);
    }

    .detail-modal-content {
      background-color: #fff;
      margin: 5% auto;
      padding: 30px;
      border: 1px solid #ddd;
      border-radius: 8px;
      width: 90%;
      max-width: 500px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
      font-family: 'Courier New', monospace;
      font-size: 14px;
      line-height: 1.6;
    }

    .detail-modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      border-bottom: 2px solid #ddd;
      padding-bottom: 15px;
    }

    .detail-modal-header h2 {
      margin: 0;
      color: #333;
      font-size: 1.5rem;
    }

    .detail-modal-close {
      color: #aaa;
      font-size: 28px;
      font-weight: bold;
      cursor: pointer;
      background: none;
      border: none;
      padding: 0;
      line-height: 1;
    }

    .detail-modal-close:hover {
      color: #000;
    }

    .detail-modal-body {
      white-space: pre-wrap;
      background-color: #f9f9f9;
      padding: 20px;
      border-radius: 4px;
      border: 1px solid #ddd;
      max-height: 70vh;
      overflow-y: auto;
    }

    .detail-row {
      margin-bottom: 8px;
    }

    .detail-section {
      margin: 15px 0;
      padding: 10px 0;
      border-top: 1px dashed #ccc;
    }

    .detail-section-title {
      font-weight: bold;
      font-size: 16px;
      margin-bottom: 10px;
      text-align: center;
      text-decoration: underline;
    }

    tbody tr {
      cursor: pointer;
      transition: background-color 0.2s;
    }

    tbody tr:hover {
      background-color: #e8f4f8;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>Printed Data History</h1>
    
    <button class="refresh-btn" onclick="fetchPrintedData()">🔄 Refresh</button>
    
    <div id="loading" class="loading" style="display: none;">Loading...</div>
    <div id="error" class="error" style="display: none;"></div>
    
    <div class="table-container">
      <table id="printedDataTable">
        <thead>
          <tr>
            <th>Order No</th>
            <th>Table No</th>
            <th>Waiter Name</th>
            <th>Print Type</th>
            <th>Items Count</th>
            <th>Printed At</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody id="tableBody">
          <!-- Data will be inserted here -->
        </tbody>
      </table>
    </div>

    <div id="emptyState" class="empty-state" style="display: none;">
      <p>No printed data found.</p>
    </div>
  </div>

  <!-- Detail Modal -->
  <div id="detailModal" class="detail-modal">
    <div class="detail-modal-content">
      <div class="detail-modal-header">
        <h2>Print Details</h2>
        <button class="detail-modal-close" onclick="closeDetailModal()">&times;</button>
      </div>
      <div id="detailModalBody" class="detail-modal-body">
        <!-- Details will be inserted here -->
      </div>
    </div>
  </div>

  <script>
    // Kitchen Printer Class (reused from other pages)
    class KitchenPrinter {
      constructor() {
        this.printerIP = localStorage.getItem('kitchenPrinterIP') || '192.168.20.100';
      }

      async printOrder(orderData) {
        try {
          const escposData = this.generateESC_POS(orderData);

          const bridgeProtocol = localStorage.getItem('kitchenPrinterBridgeProtocol') || (window.location.protocol === 'https:' ? 'https' : 'http');
          const bridgeIP = localStorage.getItem('kitchenPrinterBridgeIP') || 'localhost';
          const bridgePort = localStorage.getItem('kitchenPrinterBridgePort') || '3000';
          const bridgeUrl = `${bridgeProtocol}://${bridgeIP}:${bridgePort}/print`;

          const response = await fetch(bridgeUrl, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              printerIP: this.printerIP,
              port: 9100,
              data: Array.from(escposData)
            })
          });

          const result = await response.json();

          if (result.success) {
            console.log('✓ Print job sent successfully!');
         //   alert('Print job sent successfully!');
          } else {
            throw new Error(result.error);
          }

        } catch (error) {
          console.error('Print failed:', error);
       //   alert('Print failed: ' + error.message);
        }
      }

      async printOrderChanges(orderData) {
        try {
          const escposData = this.generateESC_POS_Changes(orderData);

          const bridgeProtocol = localStorage.getItem('kitchenPrinterBridgeProtocol') || (window.location.protocol === 'https:' ? 'https' : 'http');
          const bridgeIP = localStorage.getItem('kitchenPrinterBridgeIP') || 'localhost';
          const bridgePort = localStorage.getItem('kitchenPrinterBridgePort') || '3000';
          const bridgeUrl = `${bridgeProtocol}://${bridgeIP}:${bridgePort}/print`;

          const response = await fetch(bridgeUrl, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              printerIP: this.printerIP,
              port: 9100,
              data: Array.from(escposData)
            })
          });

          const result = await response.json();

          if (result.success) {
            console.log('✓ Print job sent successfully!');
          //  alert('Print job sent successfully!');
          } else {
            throw new Error(result.error);
          }

        } catch (error) {
          console.error('Print failed:', error);
        //  alert('Print failed: ' + error.message);
        }
      }

      generateESC_POS(order) {
        const encoder = new TextEncoder();
        const commands = [
          '\x1B\x40',
          '\x1B\x61\x01',
          '\x1B\x21\x10',
          'KITCHEN ORDER\n',
          '\x1B\x21\x00',
          '\x1B\x61\x00',
          `${'='.repeat(32)}\n`,
        ];

        const twoColumn = (left, right, maxWidth = 32) => {
          const leftText = left || '';
          const rightText = right || '';
          const padding = maxWidth - leftText.length - rightText.length;
          return padding > 0
            ? leftText + ' '.repeat(padding) + rightText + '\n'
            : leftText + ' ' + rightText + '\n';
        };

        const orderText = `Order: #${order.id || order.orderNo || 'N/A'}`;
        const tableText = order.table ? `Table: ${order.table}` : '';
        commands.push(twoColumn(orderText, tableText));

        const waiterText = order.waiter ? `Waiter: ${order.waiter}` : '';
        const now = new Date();
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const timeText = `Time: ${hours}:${minutes}`;
        commands.push(twoColumn(waiterText, timeText));

        commands.push(`${'='.repeat(32)}\n\n`);

        if (order.items && Array.isArray(order.items) && order.items.length > 0) {
          order.items.forEach(item => {
            if (item) {
              commands.push(`${item.quantity || 0}x ${item.name || 'Unknown'}\n`);
              if (item.notes && Array.isArray(item.notes) && item.notes.length > 0) {
                commands.push(`  - ${item.notes.join(', ')}\n`);
              }
              if (item.specialNeeds && Array.isArray(item.specialNeeds) && item.specialNeeds.length > 0) {
                commands.push(`  Special: ${item.specialNeeds.join(', ')}\n`);
              }
              commands.push('\n');
            }
          });
        } else if (order.items && !Array.isArray(order.items)) {
          console.warn('order.items is not an array:', order.items);
        }

        commands.push(
          `${'='.repeat(32)}\n\n\n\n`,
          '\x1B\x69'
        );
        return encoder.encode(commands.join(''));
      }

      generateESC_POS_Changes(order) {
        const encoder = new TextEncoder();
        const commands = [
          '\x1B\x40',
          '\x1B\x61\x01',
          '\x1B\x21\x10',
          'ORDER UPDATE\n',
          '\x1B\x21\x00',
          '\x1B\x61\x00',
          `${'='.repeat(32)}\n`,
        ];

        const twoColumn = (left, right, maxWidth = 32) => {
          const leftText = left || '';
          const rightText = right || '';
          const padding = maxWidth - leftText.length - rightText.length;
          return padding > 0
            ? leftText + ' '.repeat(padding) + rightText + '\n'
            : leftText + ' ' + rightText + '\n';
        };

        const orderText = `Order: #${order.id || order.orderNo || 'N/A'}`;
        const tableText = order.table ? `Table: ${order.table}` : '';
        commands.push(twoColumn(orderText, tableText));

        const waiterText = order.waiter ? `Waiter: ${order.waiter}` : '';
        const now = new Date();
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const timeText = `Time: ${hours}:${minutes}`;
        commands.push(twoColumn(waiterText, timeText));

        commands.push(`${'='.repeat(32)}\n\n`);

        const changes = order.changes || {};

        if (changes.added && Array.isArray(changes.added) && changes.added.length > 0) {
          commands.push('\x1B\x61\x01');
          commands.push('\x1B\x21\x08');
          commands.push('ADDED ITEMS\n');
          commands.push('\x1B\x21\x00');
          commands.push('\x1B\x61\x00');
          commands.push(`${'-'.repeat(32)}\n`);
          
          changes.added.forEach(item => {
            if (item) {
              commands.push(`${item.quantity || 0}x ${item.itemName || 'Unknown'}\n`);
              if (item.specialNeeds && Array.isArray(item.specialNeeds) && item.specialNeeds.length > 0) {
                commands.push(`  Special: ${item.specialNeeds.join(', ')}\n`);
              }
              commands.push('\n');
            }
          });
        } else if (changes.added && !Array.isArray(changes.added)) {
          console.warn('changes.added is not an array:', changes.added);
        }

        if (changes.quantityChanged && Array.isArray(changes.quantityChanged) && changes.quantityChanged.length > 0) {
          if (changes.added && Array.isArray(changes.added) && changes.added.length > 0) {
            commands.push('\n');
          }
          commands.push('\x1B\x61\x01');
          commands.push('\x1B\x21\x08');
          commands.push('QUANTITY CHANGED\n');
          commands.push('\x1B\x21\x00');
          commands.push('\x1B\x61\x00');
          commands.push(`${'-'.repeat(32)}\n`);
          
          changes.quantityChanged.forEach(item => {
            if (item) {
              const change = item.currentQuantity > item.previousQuantity ? '+' : '';
              const qtyChange = item.currentQuantity - item.previousQuantity;
              commands.push(`${item.itemName || 'Unknown'}\n`);
              commands.push(`  ${item.previousQuantity || 0} -> ${item.currentQuantity || 0} (${change}${qtyChange})\n`);
              if (item.specialNeeds && Array.isArray(item.specialNeeds) && item.specialNeeds.length > 0) {
                commands.push(`  Special: ${item.specialNeeds.join(', ')}\n`);
              }
              commands.push('\n');
            }
          });
        } else if (changes.quantityChanged && !Array.isArray(changes.quantityChanged)) {
          console.warn('changes.quantityChanged is not an array:', changes.quantityChanged);
        }

        if (changes.removed && Array.isArray(changes.removed) && changes.removed.length > 0) {
          if ((changes.added && Array.isArray(changes.added) && changes.added.length > 0) || 
              (changes.quantityChanged && Array.isArray(changes.quantityChanged) && changes.quantityChanged.length > 0)) {
            commands.push('\n');
          }
          commands.push('\x1B\x61\x01');
          commands.push('\x1B\x21\x08');
          commands.push('REMOVED ITEMS\n');
          commands.push('\x1B\x21\x00');
          commands.push('\x1B\x61\x00');
          commands.push(`${'-'.repeat(32)}\n`);
          
          changes.removed.forEach(item => {
            if (item) {
              commands.push(`${item.quantity || 0}x ${item.itemName || 'Unknown'}\n`);
              if (item.specialNeeds && Array.isArray(item.specialNeeds) && item.specialNeeds.length > 0) {
                commands.push(`  Special: ${item.specialNeeds.join(', ')}\n`);
              }
              commands.push('\n');
            }
          });
        } else if (changes.removed && !Array.isArray(changes.removed)) {
          console.warn('changes.removed is not an array:', changes.removed);
        }

        commands.push(
          `${'='.repeat(32)}\n\n\n\n`,
          '\x1B\x69'
        );

        return encoder.encode(commands.join(''));
      }
    }

    // Create global printer instance (will use localStorage, which we'll sync from DB)
    const kitchenPrinter = new KitchenPrinter();

    // Load printer settings from database on page load
    async function loadPrinterSettingsFromDatabase() {
      try {
        const companyId = sessionStorage.getItem('companyId');
        const branchId = sessionStorage.getItem('branchId');

        if (!companyId || !branchId) {
          console.warn('Company ID or Branch ID not found in session. Using localStorage values.');
          return;
        }

        const response = await fetch(`/api/settings?companyId=${companyId}&branchId=${branchId}`);
        const data = await response.json();

        if (response.ok && data) {
          // Update localStorage with database values (with fallbacks)
          if (data.kitchenPrinterIP) {
            localStorage.setItem('kitchenPrinterIP', data.kitchenPrinterIP);
          }
          if (data.kitchenPrinterBridgeProtocol) {
            localStorage.setItem('kitchenPrinterBridgeProtocol', data.kitchenPrinterBridgeProtocol);
          }
          if (data.kitchenPrinterBridgeIP) {
            localStorage.setItem('kitchenPrinterBridgeIP', data.kitchenPrinterBridgeIP);
          }
          if (data.kitchenPrinterBridgePort) {
            localStorage.setItem('kitchenPrinterBridgePort', data.kitchenPrinterBridgePort);
          }

          // Update the kitchenPrinter instance with new values
          kitchenPrinter.printerIP = data.kitchenPrinterIP || localStorage.getItem('kitchenPrinterIP') || '192.168.20.100';
          
          console.log('✓ Printer settings loaded from database and synced to localStorage');
        } else {
          console.warn('Failed to fetch printer settings from database. Using localStorage values.');
        }
      } catch (error) {
        console.error('Error loading printer settings from database:', error);
        // Continue with localStorage values (fallback)
      }
    }

    // Fetch and display printed data
    async function fetchPrintedData() {
      const loading = document.getElementById('loading');
      const error = document.getElementById('error');
      const tableBody = document.getElementById('tableBody');
      const emptyState = document.getElementById('emptyState');
      const table = document.getElementById('printedDataTable');

      try {
        loading.style.display = 'block';
        error.style.display = 'none';
        table.style.display = 'none';
        emptyState.style.display = 'none';

        const response = await fetch('/api/printed-data/get-all');
        const result = await response.json();

        if (result.success) {
          const data = result.data || [];
          
          // Ensure data is an array
          if (!Array.isArray(data)) {
            console.error('Data is not an array:', data);
            throw new Error('Invalid data format received from server');
          }
          
          if (data.length === 0) {
            emptyState.style.display = 'block';
            table.style.display = 'none';
          } else {
            renderTable(data);
            table.style.display = 'table';
            emptyState.style.display = 'none';
          }
        } else {
          throw new Error(result.message || 'Failed to fetch printed data');
        }
      } catch (err) {
        console.error('Error fetching printed data:', err);
        error.textContent = 'Error: ' + err.message;
        error.style.display = 'block';
        table.style.display = 'none';
        emptyState.style.display = 'none';
      } finally {
        loading.style.display = 'none';
      }
    }

    function renderTable(data) {
      const tableBody = document.getElementById('tableBody');
      if (!tableBody) {
        console.error('tableBody element not found');
        return;
      }
      
      tableBody.innerHTML = '';

      // Ensure data is an array before iterating
      if (!data || !Array.isArray(data)) {
        console.error('Invalid data passed to renderTable:', data);
        return;
      }

      data.forEach(item => {
        const row = document.createElement('tr');
        
        // Calculate total items count
        const itemsCount = (item.addedItems?.length || 0) + 
                          (item.quantityChanged?.length || 0) + 
                          (item.removedItems?.length || 0);

        // Format date
        const printedAt = new Date(item.createdAt).toLocaleString();

        // Simple print type determination
        const isNewOrder = item.printType === 'new_order' || 
                          ((item.addedItems?.length > 0) && 
                           (!item.quantityChanged?.length || item.quantityChanged.length === 0) && 
                           (!item.removedItems?.length || item.removedItems.length === 0));
        
        const printTypeText = isNewOrder ? 'New Order' : 'Update';
        const printTypeClass = isNewOrder ? 'type-new' : 'type-update';

        // Create row
        row.innerHTML = `
          <td>${item.orderNo}</td>
          <td>${item.tableNo || 'N/A'}</td>
          <td>${item.waiterName || 'N/A'}</td>
          <td class="${printTypeClass}">${printTypeText}</td>
          <td>${itemsCount}</td>
          <td>${printedAt}</td>
          <td>
            <button class="print-btn" onclick="event.stopPropagation(); reprintData('${item._id}')">🖨️ Print</button>
          </td>
        `;

        // Add click event to show details in modal
        row.style.cursor = 'pointer';
        row.addEventListener('click', (e) => {
          // Don't trigger if clicking on the print button
          if (e.target.closest('.print-btn')) {
            return;
          }
          showDetailModal(item);
        });

        tableBody.appendChild(row);
      });
    }

    // Reprint function
    async function reprintData(printDataId) {
      try {
        // Fetch the specific print data
        const response = await fetch('/api/printed-data/get-all');
        const result = await response.json();

        if (!result.success) {
          throw new Error('Failed to fetch print data');
        }

        const printData = result.data.find(item => item._id === printDataId);
        
        if (!printData) {
          throw new Error('Print data not found');
        }

        // Convert PrintedData format to print format
        if (printData.printType === 'new_order') {
          // Convert to new order format
          const orderData = {
            id: printData.orderNo,
            orderNo: printData.orderNo,
            table: printData.tableNo,
            waiter: printData.waiterName,
            items: (printData.addedItems || []).map(item => ({
              itemId: item.itemId,
              quantity: item.quantity,
              name: item.itemName,
              specialNeeds: item.specialNeeds || []
            }))
          };
          await kitchenPrinter.printOrder(orderData);
        } else {
          // Convert to order update format
          const orderData = {
            id: printData.orderNo,
            orderNo: printData.orderNo,
            table: printData.tableNo,
            waiter: printData.waiterName,
            changes: {
              added: (printData.addedItems || []).map(item => ({
                itemId: item.itemId,
                itemName: item.itemName,
                quantity: item.quantity,
                specialNeeds: item.specialNeeds || []
              })),
              quantityChanged: (printData.quantityChanged || []).map(item => ({
                itemId: item.itemId,
                itemName: item.itemName,
                previousQuantity: item.previousQuantity,
                currentQuantity: item.currentQuantity,
                specialNeeds: item.specialNeeds || []
              })),
              removed: (printData.removedItems || []).map(item => ({
                itemId: item.itemId,
                itemName: item.itemName,
                quantity: item.quantity,
                specialNeeds: item.specialNeeds || []
              }))
            }
          };
          await kitchenPrinter.printOrderChanges(orderData);
        }
      } catch (error) {
        console.error('Error reprinting:', error);
        alert('Error reprinting: ' + error.message);
      }
    }

    // Initialize Socket.IO connection (uses same origin as current page)
    window.socket = io({
      transports: ['websocket', 'polling']
    });

    window.socket.on('connect', () => {
      console.log('✓ Socket.IO connected');
    });

    window.socket.on('disconnect', () => {
      console.log('Socket.IO disconnected');
    });

    // Listen for print data broadcasts and automatically print
    window.socket.on('new-print-data', async (printData) => {
      console.log('📢 New print data received from another client:', printData);
      
      // Automatically print the received data
      try {
        if (!printData || !printData.printType) {
          console.warn('Invalid print data received:', printData);
          return;
        }

        // Log when data is accepted from socket to print
        console.log(`📥 Print data accepted from socket - Type: ${printData.printType}, Order: #${printData.orderNo || 'N/A'}, Table: ${printData.tableNo || 'N/A'}`);

        if (printData.printType === 'new_order') {
          // Convert to new order format
          const items = Array.isArray(printData.items) ? printData.items : [];
          const orderData = {
            id: printData.orderNo,
            orderNo: printData.orderNo,
            table: printData.tableNo,
            waiter: printData.waiterName,
            items: items.map(item => ({
              itemId: item.itemId,
              quantity: item.quantity,
              name: item.name || item.itemName,
              specialNeeds: Array.isArray(item.specialNeeds) ? item.specialNeeds : []
            }))
          };
          
          if (orderData.items.length === 0) {
            console.warn('No items to print for new order');
            return;
          }
          
          await kitchenPrinter.printOrder(orderData);
            } else if (printData.printType === 'order_update') {
          // Convert to order update format
          const changes = printData.changes || {};
          const orderData = {
            id: printData.orderNo,
            orderNo: printData.orderNo,
            table: printData.tableNo,
            waiter: printData.waiterName,
            changes: {
              added: Array.isArray(changes.added) ? changes.added : [],
              quantityChanged: Array.isArray(changes.quantityChanged) ? changes.quantityChanged : [],
              removed: Array.isArray(changes.removed) ? changes.removed : []
            }
          };
          
          // Check if there are any changes to print
          const hasChanges = orderData.changes.added.length > 0 || 
                            orderData.changes.quantityChanged.length > 0 || 
                            orderData.changes.removed.length > 0;
          
          if (!hasChanges) {
            console.warn('No changes to print for order update');
            return;
          }
          
          await kitchenPrinter.printOrderChanges(orderData);
          const addedCount = orderData.changes.added.length;
          const changedCount = orderData.changes.quantityChanged.length;
          const removedCount = orderData.changes.removed.length;
        //  console.log(`✅ Successfully auto-printed order update from socket - Order: #${printData.orderNo}, Table: ${printData.tableNo || 'N/A'}, Added: ${addedCount}, Changed: ${changedCount}, Removed: ${removedCount}`);
        }
        
        // Refresh the table to show the new print data
        fetchPrintedData();
      } catch (error) {
        console.error('Error auto-printing received data:', error);
        // Don't show alert for auto-print failures - just log
      }
    });

    window.socket.on('connect_error', (error) => {
      console.warn('Socket.IO connection error:', error);
    });

    // Show detail modal function
    function showDetailModal(item) {
      const modal = document.getElementById('detailModal');
      const modalBody = document.getElementById('detailModalBody');
      
      if (!modal || !modalBody) {
        console.error('Modal elements not found');
        return;
      }

      // Format the data exactly like print format
      let detailText = '';
      
      if (item.printType === 'new_order') {
        // New order format
        detailText = '════════════════════════\n';
        detailText += '      KITCHEN ORDER\n';
        detailText += '════════════════════════\n\n';
        
        const orderText = `Order: #${item.orderNo || 'N/A'}`;
        const tableText = item.tableNo ? `Table: ${item.tableNo}` : '';
        detailText += `${orderText.padEnd(16)}${tableText}\n`;
        
        const waiterText = item.waiterName ? `Waiter: ${item.waiterName}` : '';
        const createdAt = new Date(item.createdAt);
        const hours = String(createdAt.getHours()).padStart(2, '0');
        const minutes = String(createdAt.getMinutes()).padStart(2, '0');
        const timeText = `Time: ${hours}:${minutes}`;
        detailText += `${waiterText.padEnd(16)}${timeText}\n`;
        
        // Add date
        const year = createdAt.getFullYear();
        const month = String(createdAt.getMonth() + 1).padStart(2, '0');
        const day = String(createdAt.getDate()).padStart(2, '0');
        const dateText = `Date: ${year}-${month}-${day}`;
        detailText += `${dateText}\n`;
        
        detailText += '════════════════════════\n\n';
        
        if (item.addedItems && item.addedItems.length > 0) {
          item.addedItems.forEach(itemData => {
            if (itemData) {
              detailText += `${itemData.quantity || 0}x ${itemData.itemName || 'Unknown'}\n`;
              if (itemData.specialNeeds && Array.isArray(itemData.specialNeeds) && itemData.specialNeeds.length > 0) {
                detailText += `  Special: ${itemData.specialNeeds.join(', ')}\n`;
              }
              detailText += '\n';
            }
          });
        }
      } else {
        // Order update format
        detailText = '════════════════════════\n';
        detailText += '      ORDER UPDATE\n';
        detailText += '════════════════════════\n\n';
        
        const orderText = `Order: #${item.orderNo || 'N/A'}`;
        const tableText = item.tableNo ? `Table: ${item.tableNo}` : '';
        detailText += `${orderText.padEnd(16)}${tableText}\n`;
        
        const waiterText = item.waiterName ? `Waiter: ${item.waiterName}` : '';
        const createdAt = new Date(item.createdAt);
        const hours = String(createdAt.getHours()).padStart(2, '0');
        const minutes = String(createdAt.getMinutes()).padStart(2, '0');
        const timeText = `Time: ${hours}:${minutes}`;
        detailText += `${waiterText.padEnd(16)}${timeText}\n`;
        
        // Add date
        const year = createdAt.getFullYear();
        const month = String(createdAt.getMonth() + 1).padStart(2, '0');
        const day = String(createdAt.getDate()).padStart(2, '0');
        const dateText = `Date: ${year}-${month}-${day}`;
        detailText += `${dateText}\n`;
        
        detailText += '════════════════════════\n\n';
        
        // ADDED ITEMS
        if (item.addedItems && item.addedItems.length > 0) {
          detailText += 'ADDED ITEMS\n';
          detailText += '────────────────────────────────\n';
          item.addedItems.forEach(itemData => {
            if (itemData) {
              detailText += `${itemData.quantity || 0}x ${itemData.itemName || 'Unknown'}\n`;
              if (itemData.specialNeeds && Array.isArray(itemData.specialNeeds) && itemData.specialNeeds.length > 0) {
                detailText += `  Special: ${itemData.specialNeeds.join(', ')}\n`;
              }
              detailText += '\n';
            }
          });
        }
        
        // QUANTITY CHANGED
        if (item.quantityChanged && item.quantityChanged.length > 0) {
          if (item.addedItems && item.addedItems.length > 0) {
            detailText += '\n';
          }
          detailText += 'QUANTITY CHANGED\n';
          detailText += '────────────────────────────────\n';
          item.quantityChanged.forEach(itemData => {
            if (itemData) {
              const change = itemData.currentQuantity > itemData.previousQuantity ? '+' : '';
              const qtyChange = itemData.currentQuantity - itemData.previousQuantity;
              detailText += `${itemData.itemName || 'Unknown'}\n`;
              detailText += `  ${itemData.previousQuantity || 0} -> ${itemData.currentQuantity || 0} (${change}${qtyChange})\n`;
              if (itemData.specialNeeds && Array.isArray(itemData.specialNeeds) && itemData.specialNeeds.length > 0) {
                detailText += `  Special: ${itemData.specialNeeds.join(', ')}\n`;
              }
              detailText += '\n';
            }
          });
        }
        
        // REMOVED ITEMS
        if (item.removedItems && item.removedItems.length > 0) {
          if ((item.addedItems && item.addedItems.length > 0) || 
              (item.quantityChanged && item.quantityChanged.length > 0)) {
            detailText += '\n';
          }
          detailText += 'REMOVED ITEMS\n';
          detailText += '────────────────────────────────\n';
          item.removedItems.forEach(itemData => {
            if (itemData) {
              detailText += `${itemData.quantity || 0}x ${itemData.itemName || 'Unknown'}\n`;
              if (itemData.specialNeeds && Array.isArray(itemData.specialNeeds) && itemData.specialNeeds.length > 0) {
                detailText += `  Special: ${itemData.specialNeeds.join(', ')}\n`;
              }
              detailText += '\n';
            }
          });
        }
      }
      
      detailText += '════════════════════════\n';
      
      modalBody.textContent = detailText;
      modal.style.display = 'block';
    }

    // Close detail modal
    function closeDetailModal() {
      const modal = document.getElementById('detailModal');
      if (modal) {
        modal.style.display = 'none';
      }
    }

    // Close modal when clicking outside
    window.onclick = function(event) {
      const modal = document.getElementById('detailModal');
      if (event.target === modal) {
        closeDetailModal();
      }
    };

    // Load data on page load
    document.addEventListener('DOMContentLoaded', async () => {
      // Load printer settings from database first, then fetch printed data
      await loadPrinterSettingsFromDatabase();
      fetchPrintedData();
    });
  </script>
</body>
</html>

