<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title id="pageTitle">Order Management System</title>
    <style>
        /* Base Styles */
        :root {
            --primary-color: #2A5C82;
            --secondary-color: #5C9EAD;
            --success-color: #28a745;
            --warning-color: #ffc107;
            --danger-color: #dc3545;
            --text-color: #2c3e50;
            --background-color: #f8f9fa;
        }

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

        /* Header Section */
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
            padding: 1rem 2rem;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

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

        .modal-content {
            background-color: #fff;
            margin: 10% auto;
            padding: 20px;
            border-radius: 8px;
            width: 80%;
            max-width: 600px;
        }

        .modal-footer {
            display: flex;
            justify-content: flex-end;
            padding-top: 10px;
        }

        #customerTable {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }

        #customerTable th, #customerTable td {
            border: 1px solid #ddd;
            padding: 8px;
        }

        #customerTable th {
            background-color: #f4f4f4;
            text-align: left;
        }

        .system-title {
            font-size: 1.8rem;
            font-weight: 700;
            color: var(--primary-color);
        }

        /* Passcode Input */
        .passcode-container {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .passcode-input {
            padding: 0.8rem 1.2rem;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 1rem;
            transition: border-color 0.3s ease;
        }

        .passcode-input:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 2px rgba(42,92,130,0.1);
        }

        /* Orders Table */
        .orders-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
        }

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

        .orders-table th {
            padding: 1.2rem 1.5rem;
            font-weight: 600;
            text-align: left;
        }

        .orders-table td {
            padding: 1.2rem 1.5rem;
            border-bottom: 1px solid #eee;
        }

        /* Order Number Styling */
        .order-number {
            color: var(--primary-color);
            font-weight: 700;
            font-size: 1.1rem;
        }

        /* Status Badges */
        .status-badge {
            display: inline-block;
            padding: 0.4rem 0.8rem;
            border-radius: 20px;
            font-size: 1.0em;
            font-weight: 900;
        }

        .status-paid {
            background-color: #e8f5e9;
            color: #2e7d32;
        }

        .status-pending {
            background-color: #fff3e0;
            color: #ef6c00;
        }

        .status-cancelled {
            background-color: #ffebee;
            color: #c62828;
        }

        /* Total Price */
        .total-price {
            font-size: 0.9rem;
            color: var(--text-color);
            margin-top: 0.5rem;
        }

        /* Action Dropdown */
        .action-menu {
            position: relative;
            display: inline-block;
        }

        .menu-trigger {
            padding: 0.5rem;
            color: darkblue;
            border: none;
            background: none;
            cursor: pointer;
        }

        .menu-content {
            display: none;
            position: absolute;
            right: 0;
            background: white;
            min-width: 160px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            border-radius: 6px;
            z-index: 1;
        }

        .menu-content.show {
            display: block;
        }

        .menu-item {
            padding: 0.8rem 1.2rem;
            font-size: 0.9rem;
            color: var(--text-color);
            cursor: pointer;
            transition: background-color 0.2s ease;
        }

        .menu-item:hover {
            background-color: #f8f9fa;
        }

        /* Responsive Design */
        @media (max-width: 768px) {
            .header {
                flex-direction: column;
                gap: 1rem;
                padding: 1rem;
            }

            .orders-table {
                display: block;
                overflow-x: auto;
            }
        }

        .orders-table {
            width: 100%;
            border-collapse: collapse;
        }

        .orders-table th,
        .orders-table td {
            border: none;
        }

        .orders-table td {
            border-bottom: 1px solid #ddd;
        }

        .orders-table thead th {
            border-bottom: 2px solid #ccc;
        }

        /* Container Styles */
        .item-list {
            display: flex;
            flex-direction: column;
            gap: 1rem;
            max-width: 600px;
            margin: 0 auto;
            padding: 1rem;
            background: #f9f9f9;
            border-radius: 10px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
            font-family: 'Arial', sans-serif;
            color: #333;
        }

        /* Item Styles */
        .item {
            padding: 0.75rem 1rem;
            border-radius: 8px;
            border: 1px solid #ddd;
            font-weight: 500;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }

        /* Styling for Item Name */
        .item-name {
            color: rgb(4, 59, 110);
            font-weight: bold;
            margin-right: 8px;
        }

        /* Styling for Quantity */
        .item-quantity {
            font-size: 14px;
            color: gray;
            margin-left: 8px;
        }

        /* Styling for Served Quantity */
        .item-served {
            font-size: 14px;
            color: gray;
            margin-left: 8px;
        }

        /* Conditional Colors */
        .item.equal {
            background-color: #4af972;
            border: 1px solid #c3e6cb;
        }

        .item.not-equal {
            background-color: #ffeeba;
            border: 1px solid #ffc107;
        }

        /* Hover Effect */
        .item:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
        }
        
        .filter-container {
            display: flex;
            gap: 0.75rem;
            margin-bottom: 1.5rem;
            padding: 1rem;
            background: linear-gradient(135deg, #1e88e5, #0d47a1);
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            overflow-x: auto;
            white-space: nowrap;
            scrollbar-width: none;
        }

        .filter-container::-webkit-scrollbar {
            display: none;
        }

        .filter-btn {
            flex: 0 0 120px;
            padding: 0.6rem 0;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 24px;
            background: rgba(255, 255, 255, 0.1);
            color: white;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
            text-align: center;
            backdrop-filter: blur(5px);
        }

        .filter-btn:hover {
            background: rgba(255, 255, 255, 0.2);
            transform: translateY(-2px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .filter-btn.active {
            background: #ffffff;
            color: #0d47a1;
            border-color: white;
            font-weight: 600;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="system-title" id="companyTitle">Order Management System</div>
        <div class="passcode-container">
            <label>Access Code:</label>
            <input type="password" class="passcode-input" id="passCodeInput" 
                   placeholder="••••" maxlength="4" required>
        </div>
    </div>

    <!-- Filter buttons container -->
    <div class="filter-container" id="username-filters">
        <button class="filter-btn active" onclick="filterOrdersByUser('all')">All</button>
        <!-- Filter buttons will be added dynamically here -->
    </div>

    <table class="orders-table">
        <thead>
            <tr>
                <th>Order Details</th>
                <th>Items</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody id="orders-container">
            <!-- Orders will be populated here -->
        </tbody>
    </table>

    <!-- Modal Structure -->
    <div id="customerModal" class="modal">
        <div class="modal-content">
            <h3>Customer List</h3>
            <table id="customerTable">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Phone</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- Customer rows will be dynamically inserted here -->
                </tbody>
            </table>
        </div>
        <div class="modal-footer">
            <button onclick="closeModal()">Close</button>
        </div>
    </div>

  
  <script type="module">
    import permissionUtils from "./js/common.js";
    import { CAFE_BASICS } from "./js/frontEndPermission.js";
    // Initialize variables
    window.cancelResume = false;
  // Check permissions
        if (typeof permissionUtils !== 'undefined' && 
            typeof CAFE_BASICS !== 'undefined' &&
            permissionUtils.hasPermission(userPermissions,CAFE_BASICS.CANCEL_RESUME)) {
            window.cancelResume = true;
           
        }
</script>

    
    <!-- Main application script -->
    <script>
  
      
        const companyId = sessionStorage.getItem('companyId');
        const branchId = sessionStorage.getItem('branchId');
        let currentUserId = sessionStorage.getItem('userId');
        let allOrders = [];
        let currentFilter = 'all';
        let defaultTimeOut;

      

        if (!companyId || !branchId) {
            console.log('Company ID and Branch ID are required. Please login again');
            window.location.href = "/";
        }

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

                if (response.ok) {
                    defaultTimeOut = data.defaultTimeOut || '';
                    console.log('Default Timeout:', defaultTimeOut);
                    getAllOrders(null);
                } else {
                    console.error('Failed to fetch settings. Server response:', data);
                }
            } catch (error) {
                console.error('Error fetching default settings:', error);
            }
        }

        async function renderOrders(orders) {
            allOrders = orders;
            updateUserFilters(orders);
            applyCurrentFilter();
        }

        function updateUserFilters(orders) {
            const filterContainer = document.getElementById('username-filters');
            const usernames = [...new Set(orders.map(order => order.userName))];
            
            filterContainer.innerHTML = '<button class="filter-btn active" onclick="filterOrdersByUser(\'all\')">All</button>';
            
            usernames.forEach(username => {
                const btn = document.createElement('button');
                btn.className = 'filter-btn';
                btn.textContent = username;
                btn.onclick = () => filterOrdersByUser(username);
                filterContainer.appendChild(btn);
            });
        }

        function filterOrdersByUser(username) {
            currentFilter = username;
            document.querySelectorAll('.filter-btn').forEach(btn => {
                btn.classList.remove('active');
                if ((username === 'all' && btn.textContent === 'All') || 
                    (btn.textContent === username)) {
                    btn.classList.add('active');
                }
            });
            applyCurrentFilter();
        }

        function applyCurrentFilter() {
            const container = document.getElementById('orders-container');
            container.innerHTML = '';
            const filteredOrders = currentFilter === 'all' ? allOrders : allOrders.filter(order => order.userName === currentFilter);
            const defaultTimeOutMs = defaultTimeOut * 60 * 1000;

            filteredOrders.forEach(order => {
                if (order.status === 'paid') {
                    const createdAt = new Date(order.createdAt);
                    const currentTime = new Date();
                    const timeElapsed = currentTime - createdAt;

                    if (timeElapsed > defaultTimeOutMs) {
                        return;
                    }
                }

                const totalPrice = order.items.reduce((sum, item) => sum + (item.selling_price * item.quantity), 0);
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>
                        <div class="order-number">#${order.orderNo}</div>
                        <div class="order-meta">
                            <small>Table: ${order.tableNo}</small><br>
                            ${order.transferFrom ? `<small>From: ${order.transferFrom}</small><br>` : ""}
                            <small>Waiter: ${order.userName}</small><br>
                            <small>${new Date(order.createdAt).toLocaleString()}</small><br>
                            <small>Time Elapsed: ${calculateTimeElapsed(order.createdAt)}</small>
                        </div>
                    </td>
                    <td>
                        <div class="item-list">
                            ${order.items.map(item => {
                                const className = item.quantity === item.kitchenServedQty ? "equal" : "not-equal";
                                return `<div class="item ${className}">
                                    • <strong class="item-name">${item.itemName}</strong> $${item.selling_price.toFixed(2)}
                                    <span class="item-quantity">Qty: ${item.quantity}</span>
                                    <span class="item-served">Served: ${item.kitchenServedQty}</span>
                                </div>`;
                            }).join('')}
                        </div>
                    </td>
                    <td>
                        <div class="status-badge ${getStatusClass(order.status)}">
                            ${order.status}
                        </div>
                        <div class="total-price">
                            Total: $${totalPrice.toFixed(2)}
                        </div>
                    </td>
                    <td>
                        <div class="action-menu">
                            <button class="menu-trigger" onclick="toggleMenu('${order._id}')">⋮</button>
                            <div id="menu-${order._id}" class="menu-content">
                                <div class="menu-item" onclick="payOrder('${order._id}')">Pay</div>
                                ${window.cancelResume ? `<div class="menu-item" onclick="resumeOrder('${order._id}')">Resume Order</div>` : ''}
                                ${window.cancelResume ? `<div class="menu-item" onclick="cancelOrder('${order._id}')" style="color: var(--danger-color);">Cancel Order</div>` : ''}
                                <div class="menu-item" onclick="openModal('${order._id}')">Credit Customer</div>
                            </div>
                        </div>
                    </td>
                `;
                container.appendChild(row);
            });
        }

        function calculateTimeElapsed(createdAt) {
            const now = new Date();
            const orderTime = new Date(createdAt);
            const diffMs = now - orderTime;
            const diffMinutes = Math.floor(diffMs / (1000 * 60));
            const diffHours = Math.floor(diffMinutes / 60);
            const diffDays = Math.floor(diffHours / 24);

            if (diffDays > 0) return `${diffDays} day(s) ago`;
            if (diffHours > 0) return `${diffHours} hour(s) ago`;
            if (diffMinutes > 0) return `${diffMinutes} minute(s) ago`;
            return `Just now`;
        }

        function getStatusClass(status) {
            const statusMap = {
                'paid': 'status-paid',
                'pending': 'status-pending',
                'cancelled': 'status-cancelled'
            };
            return statusMap[status.toLowerCase()] || '';
        }

        function toggleMenu(orderId) {
            const menu = document.getElementById(`menu-${orderId}`);
            menu.classList.toggle('show');
        }

        document.addEventListener('click', function(e) {
            if (!e.target.closest('.action-menu')) {
                document.querySelectorAll('.menu-content').forEach(d => d.classList.remove('show'));
            }
        });

        async function payOrder(orderId, customerId) {
            try {
                const response = await fetch(`/api/cafeorder/pay-order?orderId=${orderId}${customerId ? `&customerId=${customerId}` : ''}&userId=${currentUserId}&branchId=${branchId}`, {
                    method: 'POST'
                });
                if (response.ok) {
                    alert('Order paid successfully.');
                    getAllOrders(currentUserId);
                } else {
                    const errorData = await response.json();
                    alert(`Failed to pay order: ${errorData.message}`);
                }
            } catch (error) {
                console.error('Error paying order:', error);
                alert('An error occurred. Please try again.');
            }
        }

        function resumeOrder(orderId) {
            fetch(`/api/cafeorder/resume-order?orderId=${orderId}&userId=${currentUserId}`, { 
                method: 'POST' 
            })
            .then(response => {
                if (response.ok) {
                    alert('Order resumed successfully.');
                    getAllOrders(currentUserId);
                } else {
                    alert('Failed to resume order.');
                }
            })
            .catch(error => console.error('Error:', error));
        }

        function cancelOrder(orderId) {
            if (confirm('Are you sure you want to cancel this order?')) {
                fetch(`/api/cafeorder/cancel-order?orderId=${orderId}&userId=${currentUserId}`, { 
                    method: 'POST' 
                })
                .then(response => {
                    if (response.ok) {
                        alert('Order canceled successfully.');
                        getAllOrders(currentUserId);
                    } else {
                        alert('Failed to cancel order.');
                    }
                })
                .catch(error => console.error('Error:', error));
            }
        }

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

        async function verifyPassCode(passcode) {
            try {
                const response = await fetch(`/api/users/getByPasscode?passcode=${passcode}`);
                if (response.ok) {
                    currentUserId = await response.json();
                    getAllOrders(currentUserId);
                    document.getElementById('passCodeInput').value = "";
                } else {
                    alert("Invalid passcode. Please try again.");
                }
            } catch (error) {
                console.error("Error verifying passcode:", error);
            }
        }

        function getAllOrders(userId) {
            fetch(`/api/cafeorder?companyId=${companyId}${userId=''}`)
                .then(response => response.json())
                .then(data => renderOrders(data.data))
                .catch(error => console.error('Error:', error));
        }

        function openModal(orderId) {
            fetchCustomers(orderId);
            document.getElementById('customerModal').style.display = 'block';
        }

        function closeModal() {
            document.getElementById('customerModal').style.display = 'none';
        }

        async function fetchCustomers(orderId) {
            try {
                const response = await fetch(`/api/customers/List?companyId=${companyId}`);
                const customers = await response.json();
                const tbody = document.querySelector('#customerTable tbody');
                tbody.innerHTML = '';
                customers.forEach(customer => {
                    const row = tbody.insertRow();
                    row.insertCell().textContent = customer.name;
                    row.insertCell().textContent = customer.phone;
                    const actionCell = row.insertCell();
                    actionCell.innerHTML = `<button onclick="useCustomer('${customer._id}','${orderId}')">Use</button>`;
                });
            } catch (err) {
                console.error('Error:', err);
            }
        }

        function useCustomer(customerId, orderId) {
            if (!customerId) return alert('No customer selected.');
            payOrder(orderId, customerId);
            closeModal();
        }

        // Initialize when page loads
        document.addEventListener('DOMContentLoaded', function() {
            fetchDefaultSettings();
             // Refresh orders every 30 seconds
            setInterval(  getAllOrders(null), 30000);
            
            // Load and display company name
            (async function() {
              const companyId = sessionStorage.getItem('companyId');
              const branchId = sessionStorage.getItem('branchId');
              
              if (companyId && branchId) {
                try {
                  const response = await fetch(`/api/settings?companyId=${companyId}&branchId=${branchId}`);
                  if (response.ok) {
                    const data = await response.json();
                    if (data.companyName) {
                      localStorage.setItem('companyName', data.companyName);
                      updateCompanyNameDisplay(data.companyName);
                    }
                  }
                } catch (error) {
                  console.error('Error loading company name:', error);
                }
              }
              
              // Fallback to localStorage or default
              const companyName = localStorage.getItem('companyName') || 'Zad';
              updateCompanyNameDisplay(companyName);
            })();
        });
        
        function updateCompanyNameDisplay(companyName) {
          const titleElement = document.getElementById('companyTitle');
          const pageTitleElement = document.getElementById('pageTitle');
          if (titleElement) {
            titleElement.textContent = companyName + ' Order Management System';
          }
          if (pageTitleElement) {
            pageTitleElement.textContent = companyName + ' Order Management System';
          }
        }

 

    </script>
</body>
</html>