// Custom confirm modal (replaces native confirm() for PHP Desktop/CEF compatibility) function customConfirm(message) { return new Promise(resolve => { const overlay = document.getElementById('confirmOverlay'); const msgEl = document.getElementById('confirmMessage'); msgEl.textContent = message; overlay.classList.add('show'); document.getElementById('confirmBtnCancel').style.display = ''; document.getElementById('confirmBtnOk').onclick = () => { overlay.classList.remove('show'); resolve(true); }; document.getElementById('confirmBtnCancel').onclick = () => { overlay.classList.remove('show'); resolve(false); }; }); } // Custom alert modal (single OK button, same style as customConfirm) function customAlert(message) { return new Promise(resolve => { const overlay = document.getElementById('confirmOverlay'); const msgEl = document.getElementById('confirmMessage'); msgEl.textContent = message; document.getElementById('confirmBtnCancel').style.display = 'none'; overlay.classList.add('show'); document.getElementById('confirmBtnOk').onclick = () => { overlay.classList.remove('show'); document.getElementById('confirmBtnCancel').style.display = ''; resolve(true); }; }); } // Custom prompt modal (text input with OK/Cancel, same style as customConfirm) function customPrompt(message, placeholder) { return new Promise(resolve => { const overlay = document.getElementById('promptOverlay'); document.getElementById('promptMessage').textContent = message; const input = document.getElementById('promptInput'); input.value = ''; input.placeholder = placeholder || ''; overlay.classList.add('show'); setTimeout(() => input.focus(), 100); document.getElementById('promptBtnOk').onclick = () => { const val = input.value; overlay.classList.remove('show'); resolve(val); }; document.getElementById('promptBtnCancel').onclick = () => { overlay.classList.remove('show'); resolve(null); }; input.onkeydown = (e) => { if (e.key === 'Enter') document.getElementById('promptBtnOk').click(); }; }); } // Global variables let currentView = 'list'; // 'list' or 'grid' let currentPOS = null; let currentCategory = null; let cart = []; let allItems = []; let categories = []; let currentModalItem = null; // Store the item being added via modal let selectedCartIndex = null; // Track selected item in cart let currentOrderType = 'in_dining'; // 'in_dining', 'delivery', or 'takeaway' let selectedDeliveryClient = null; // Store selected delivery client for header flow let selectedDeliveryCourier = null; // Store selected courier for header delivery flow let deliveryModeFromHeader = false; // Track if delivery was selected from header // Category color palette - light backgrounds with accent borders const CATEGORY_COLORS = [ { bg: '#e3f2fd', border: '#90caf9', active: '#42a5f5' }, // Blue { bg: '#e8f5e9', border: '#a5d6a7', active: '#66bb6a' }, // Green { bg: '#fff3e0', border: '#ffcc80', active: '#ffa726' }, // Orange { bg: '#f3e5f5', border: '#ce93d8', active: '#ab47bc' }, // Purple { bg: '#fce4ec', border: '#f48fb1', active: '#ec407a' }, // Pink { bg: '#e0f2f1', border: '#80cbc4', active: '#26a69a' }, // Teal { bg: '#e8eaf6', border: '#9fa8da', active: '#5c6bc0' }, // Indigo { bg: '#fff8e1', border: '#ffe082', active: '#ffca28' }, // Amber { bg: '#e0f7fa', border: '#80deea', active: '#26c6da' }, // Cyan { bg: '#fbe9e7', border: '#ffab91', active: '#ff7043' }, // Deep Orange { bg: '#f1f8e9', border: '#aed581', active: '#9ccc65' }, // Light Green { bg: '#ede7f6', border: '#b39ddb', active: '#7e57c2' }, // Deep Purple { bg: '#ffebee', border: '#ef9a9a', active: '#ef5350' }, // Red { bg: '#e1f5fe', border: '#81d4fa', active: '#29b6f6' }, // Light Blue { bg: '#f9fbe7', border: '#c5e1a5', active: '#d4e157' }, // Lime ]; let categoryColorMap = {}; // Maps category ID to color object let closingTimeSetting = null; // Store the POS closing time setting let userPermissions = null; // Store user permissions based on role let userGroup = null; // Store user's role (Waiter, Cashier, Supervisor, Manager) // Notes applicable let allPosNotes = []; // All pos_notes loaded from database // Accompaniment mode state let accompMode = false; // true when in accompaniment selection mode let accompParentItem = null; // the "sold with accompaniments" item that triggered the mode let accompParentQuantity = 0; // quantity of the parent item let accompParentMaxAcc = 0; // max_no_of_acc from res_item (0=unlimited) let accompSelectedCount = 0; // how many accompaniments added in this session // Show notification toast message function showNotification(message, type = 'info') { // Remove any existing notification const existingNotification = document.querySelector('.pos-notification'); if (existingNotification) { existingNotification.remove(); } // Create notification element const notification = document.createElement('div'); notification.className = `pos-notification pos-notification-${type}`; const icon = type === 'error' ? '❌' : type === 'warning' ? '⚠️' : type === 'success' ? '✅' : 'ℹ️'; notification.innerHTML = ` ${icon} ${message} `; // Add to body document.body.appendChild(notification); // Auto-remove after 5 seconds (longer for errors/warnings) const duration = (type === 'error' || type === 'warning') ? 8000 : 5000; setTimeout(() => { if (notification.parentElement) { notification.remove(); } }, duration); } function showToast(message) { const toast = document.createElement('div'); toast.className = 'pos-toast'; toast.textContent = message; document.body.appendChild(toast); setTimeout(() => { toast.classList.add('pos-toast-hide'); toast.addEventListener('transitionend', () => toast.remove()); }, 2500); } // Custom table name editing async function editCustomName() { const currentCustomName = document.getElementById('tableCustomName')?.value || ''; const newName = await customPrompt('Enter custom name for this table (leave empty to clear):', currentCustomName); if (newName === null) return; // User cancelled const tableId = document.getElementById('tableId')?.value; if (!tableId) return; const formData = new FormData(); formData.append('action', 'set_custom_name'); formData.append('table_id', tableId); formData.append('custom_name', newName.trim()); fetch('api/tables.php', { method: 'POST', body: formData }) .then(res => res.json()) .then(data => { if (data.success) { const display = document.getElementById('customNameDisplay'); const hiddenInput = document.getElementById('tableCustomName'); if (newName.trim()) { display.textContent = '- ' + newName.trim(); hiddenInput.value = newName.trim(); } else { display.textContent = ''; hiddenInput.value = ''; } showToast(newName.trim() ? 'Table name updated' : 'Custom name cleared'); } else { showNotification('Failed to update table name: ' + (data.message || 'Unknown error'), 'error'); } }) .catch(() => { showNotification('Failed to update table name', 'error'); }); } // Initialize user permissions from hidden input function initializePermissions() { try { const permissionsEl = document.getElementById('userPermissions'); const groupEl = document.getElementById('userGroup'); if (permissionsEl && permissionsEl.value) { userPermissions = JSON.parse(permissionsEl.value); } if (groupEl) { userGroup = groupEl.value; } // Apply permission-based UI restrictions applyPermissionRestrictions(); } catch (error) { console.error('Error initializing permissions:', error); } } // Check if user has a specific permission function hasPermission(permissionName) { if (!userPermissions) return false; return parseInt(userPermissions[permissionName]) === 1; } // Apply UI restrictions based on user permissions function applyPermissionRestrictions() { if (!userPermissions) return; // Apply permissions to cart action buttons applyCartActionPermissions(); // Apply permission to top bar Delivery button on page load applyTopBarDeliveryPermission(); console.log('User permissions loaded:', userGroup, userPermissions); } // Apply permission restrictions to cart action buttons (KOT, Print Bill, Settle) function applyCartActionPermissions() { if (!userPermissions) return; // Send / Print KOT button - check send_print_kot permission const kotBtn = document.getElementById('btnSendPrintKOT'); if (kotBtn) { if (!hasPermission('send_print_kot')) { kotBtn.disabled = true; kotBtn.classList.add('btn-disabled'); kotBtn.title = 'You do not have permission to Send/Print KOT'; } } // Print Bill button - check print_bill permission const printBillBtn = document.getElementById('btnPrintBill'); if (printBillBtn) { if (!hasPermission('print_bill')) { printBillBtn.disabled = true; printBillBtn.classList.add('btn-disabled'); printBillBtn.title = 'You do not have permission to Print Bill'; } } // Settle button - check process permission (settlement/processing) const settleBtn = document.getElementById('btnSettle'); if (settleBtn) { if (!hasPermission('process')) { settleBtn.disabled = true; settleBtn.classList.add('btn-disabled'); settleBtn.title = 'You do not have permission to Settle Payments'; } } } // Apply permission restrictions to Options dialog buttons function applyOptionsPermissions() { if (!userPermissions) return; // The options grid buttons - show/hide based on permissions const optionsGrid = document.querySelector('.options-grid'); if (!optionsGrid) return; // Get all option buttons const optionButtons = optionsGrid.querySelectorAll('.option-btn'); optionButtons.forEach(btn => { const btnText = btn.textContent.trim().toLowerCase(); // Discounts - check discount permission if (btnText.includes('discount')) { btn.style.display = hasPermission('discount') ? '' : 'none'; } // Split Bill - check transfer_order_to_table permission if (btnText.includes('split bill')) { btn.style.display = hasPermission('transfer_order_to_table') ? '' : 'none'; } // Delete Items - check remove_items permission if (btnText.includes('delete item')) { btn.style.display = hasPermission('remove_items') ? '' : 'none'; } // Returns - check remove_items permission (reverse sale) if (btnText.includes('returns')) { btn.style.display = hasPermission('remove_items') ? '' : 'none'; } // Order List - check order_list permission if (btnText.includes('order list')) { btn.style.display = hasPermission('order_list') ? '' : 'none'; } // Room Service - check room_service permission if (btnText.includes('room service')) { btn.style.display = hasPermission('room_service') ? '' : 'none'; } // Posting Date - check posting_date permission if (btnText.includes('posting date')) { btn.style.display = hasPermission('posting_date') ? '' : 'none'; } // Sales Report - check sales_report permission if (btnText.includes('sales report')) { btn.style.display = hasPermission('sales_report') ? '' : 'none'; } // Extra Charge - check extra_charge permission if (btnText.includes('extra charge')) { btn.style.display = hasPermission('extra_charge') ? '' : 'none'; } // Close Day - check close_day permission if (btnText.includes('close day')) { btn.style.display = hasPermission('close_day') ? '' : 'none'; } // Redeemable - check redeemable permission if (btnText.includes('redeemable')) { btn.style.display = hasPermission('redeemable') ? '' : 'none'; } // Delivery - check manage_delivery permission (disable with message instead of hiding) if (btnText.includes('delivery') && btn.id === 'deliveryOptionBtn') { if (!hasPermission('manage_delivery')) { btn.disabled = true; btn.classList.add('btn-disabled'); btn.title = `'${userGroup || 'Your role'}' does not have access to manage this feature`; btn.style.opacity = '0.6'; btn.style.cursor = 'not-allowed'; btn.onclick = async function(e) { e.preventDefault(); await customAlert(`'${userGroup || 'Your role'}' does not have access to manage this feature`); return false; }; } } // Loyalty Program - check loyalty_program permission (disable with message instead of hiding) if (btnText.includes('loyalty')) { if (!hasPermission('loyalty_program')) { btn.disabled = true; btn.classList.add('btn-disabled'); btn.title = `'${userGroup || 'Your role'}' does not have access to manage this feature`; btn.style.opacity = '0.6'; btn.style.cursor = 'not-allowed'; btn.onclick = async function(e) { e.preventDefault(); await customAlert(`'${userGroup || 'Your role'}' does not have access to manage this feature`); return false; }; } } }); // Apply permission to top bar Delivery button applyTopBarDeliveryPermission(); } // Apply permission restriction to the top bar Delivery button function applyTopBarDeliveryPermission() { const btnDelivery = document.getElementById('btnDelivery'); if (btnDelivery && !hasPermission('manage_delivery')) { btnDelivery.disabled = true; btnDelivery.classList.add('btn-disabled'); btnDelivery.title = `'${userGroup || 'Your role'}' does not have access to manage this feature`; btnDelivery.style.opacity = '0.6'; btnDelivery.style.cursor = 'not-allowed'; // Override the onclick to show alert instead btnDelivery.onclick = async function(e) { e.preventDefault(); await customAlert(`'${userGroup || 'Your role'}' does not have access to manage this feature`); return false; }; } } // Check and apply automatic back-dating based on closing time setting async function checkAndApplyClosingTimeBackdate() { try { // Get server time const serverTimeResponse = await fetch('../get_server_time'); const serverTimeData = await serverTimeResponse.json(); if (!serverTimeData || !serverTimeData.time) { console.log('Could not get server time'); return; } // Parse server time (format: "YYYY-MM-DD HH:MM:SS") const timeParts = serverTimeData.time.split(' '); const serverDate = timeParts[0]; const serverTimePart = timeParts[1]; const currentHour = parseInt(serverTimePart.split(':')[0]); // Get closing time setting from database const closingResponse = await fetch('../getPos.php?getPOSclosingtime'); const closingData = await closingResponse.json(); if (closingData && closingData.length > 0) { closingTimeSetting = parseInt(closingData[0].closing_time); } else { closingTimeSetting = 12; // Default to 12 (no back-dating) } // Check if we're in the back-dating window (between midnight and closing_time) // Only apply back-dating if closing_time is NOT 12 if (closingTimeSetting !== 12 && currentHour >= 0 && currentHour < closingTimeSetting) { // Calculate previous day's date const prevDate = getPreviousDay(new Date(serverDate)); // Only auto-set if user hasn't manually selected a different date if (!sessionStorage.getItem('dateSelected')) { sessionStorage.setItem('dateSelected', prevDate); sessionStorage.setItem('autoBackdated', 'true'); // Flag to indicate auto back-dating console.log(`Auto back-dating enabled. Posting date set to: ${prevDate} (closing_time: ${closingTimeSetting})`); } } else { // Outside back-dating window, clear auto-backdated flag if (sessionStorage.getItem('autoBackdated') === 'true') { sessionStorage.removeItem('dateSelected'); sessionStorage.removeItem('autoBackdated'); console.log('Outside back-dating window. Cleared auto back-date.'); } } } catch (error) { console.error('Error checking closing time setting:', error); } } // Get previous day's date in YYYY-MM-DD format function getPreviousDay(date) { const prevDate = new Date(date); prevDate.setDate(prevDate.getDate() - 1); const year = prevDate.getFullYear(); const month = String(prevDate.getMonth() + 1).padStart(2, '0'); const day = String(prevDate.getDate()).padStart(2, '0'); return `${year}-${month}-${day}`; } // Format number with commas and 2 decimal places function formatAmount(amount) { return parseFloat(amount).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); } // Initialize on page load document.addEventListener('DOMContentLoaded', function() { // Initialize user permissions first initializePermissions(); // Load the default POS const defaultPosId = document.getElementById('currentPosId').value; if (defaultPosId) { currentPOS = defaultPosId; loadPOSData(defaultPosId); // Check if this POS has membership packages checkPOSMembershipAccess(defaultPosId); checkLoyaltyAccess(); } loadExistingOrder(); loadTableDeliveryInfo(); // Check if this table has delivery assigned checkAndApplyClosingTimeBackdate(); // Check if automatic back-dating should apply // Listen for pending checks completion to update POS button styles window.addEventListener('pendingChecksComplete', updateUnclosedPOSStyles); }); // Update POS button styles to indicate unclosed POS function updateUnclosedPOSStyles() { if (!window.unclosedPOSList || window.unclosedPOSList.length === 0) return; const allTabButtons = document.querySelectorAll('.pos-tab-button'); allTabButtons.forEach(btn => { const posId = btn.dataset.posId; if (window.unclosedPOSList.includes(String(posId))) { btn.classList.add('pos-unclosed'); btn.title = 'Yesterday not closed - Adding items disabled'; } }); // Also show warning if current POS is unclosed if (isPOSUnclosed(currentPOS)) { showNotification('Warning: Yesterday\'s orders for this POS have not been closed. Adding new items is disabled until the day is closed.', 'warning'); } } // Select order type (In Dining, Delivery, Takeaway) async function selectOrderType(type) { // If switching away from delivery and we had a delivery client, ask for confirmation if (type !== 'delivery' && selectedDeliveryClient) { const confirmed = await customConfirm( `This order is currently assigned to delivery client "${selectedDeliveryClient.client_name}".\n\n` + `Switching to ${type === 'in_dining' ? 'In Dining' : 'Takeaway'} will remove the delivery details from this order.\n\n` + `Do you want to continue?` ); if (!confirmed) { return; // User cancelled, don't switch } const tableNo = document.getElementById('tableNo').value; if (tableNo) { try { await fetch('api/orders.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'clear_table_delivery', table_no: tableNo }) }); } catch (error) { console.error('Error clearing delivery:', error); } } selectedDeliveryClient = null; selectedDeliveryCourier = null; deliveryModeFromHeader = false; updateDeliveryClientDisplay(); } currentOrderType = type; // Update button states (desktop + mobile) document.getElementById('btnInDining').classList.remove('active'); document.getElementById('btnDelivery').classList.remove('active'); document.getElementById('btnTakeaway').classList.remove('active'); var mInDining = document.getElementById('btnInDiningMobile'); var mDelivery = document.getElementById('btnDeliveryMobile'); if (mInDining) mInDining.classList.remove('active'); if (mDelivery) mDelivery.classList.remove('active'); if (type === 'in_dining') { document.getElementById('btnInDining').classList.add('active'); if (mInDining) mInDining.classList.add('active'); } else if (type === 'delivery') { document.getElementById('btnDelivery').classList.add('active'); if (mDelivery) mDelivery.classList.add('active'); // Set flag that delivery was selected from header deliveryModeFromHeader = true; // Open delivery dialog to select client showDeliveryForClientSelection(); } else if (type === 'takeaway') { document.getElementById('btnTakeaway').classList.add('active'); } } // Show delivery dialog specifically for client selection (from header) function showDeliveryForClientSelection() { // Show the delivery modal with "Select Client" button instead of "Assign Order" document.getElementById('deliveryModal').style.display = 'flex'; document.getElementById('deliveryAssignBtn').style.display = 'none'; document.getElementById('deliverySelectClientBtn').style.display = 'inline-block'; loadDeliveryClients(); } // Update delivery client display in the header/cart area function updateDeliveryClientDisplay() { const displayEl = document.getElementById('deliveryClientDisplay'); if (displayEl) { if (selectedDeliveryClient) { const courierName = selectedDeliveryCourier ? selectedDeliveryCourier.name : ''; displayEl.innerHTML = `
🚚 ${selectedDeliveryClient.client_name} ${selectedDeliveryClient.location} ${courierName ? `🏍️ ${courierName}` : ''}
`; displayEl.style.display = 'block'; } else { displayEl.style.display = 'none'; } } } // Change delivery client function changeDeliveryClient() { deliveryModeFromHeader = true; showDeliveryForClientSelection(); } // Load delivery info for the current table (on page load) async function loadTableDeliveryInfo() { const tableNo = document.getElementById('tableNo').value; if (!tableNo) { return; } try { const response = await fetch(`api/orders.php?action=get_table_delivery&table_no=${tableNo}`); const result = await response.json(); if (result.success && result.has_delivery) { // Table has delivery assigned - restore the state selectedDeliveryClient = { id: result.delivery.id, client_name: result.delivery.client_name, contact: result.delivery.contact, location: result.delivery.location }; deliveryModeFromHeader = true; currentOrderType = 'delivery'; // Update UI updateDeliveryClientDisplay(); // Update header buttons document.getElementById('btnInDining').classList.remove('active'); document.getElementById('btnTakeaway').classList.remove('active'); document.getElementById('btnDelivery').classList.add('active'); } } catch (error) { console.error('Error loading table delivery info:', error); } } // Select client and close modal (for header flow) - then show courier selection async function selectClientAndClose() { if (!selectedClientForOrder) { await customAlert('Please select a client first.'); return; } const client = deliveryClients.find(c => c.id == selectedClientForOrder); if (!client) { await customAlert('Client not found.'); return; } // Store the selected client locally (temporarily) selectedDeliveryClient = client; // Close delivery modal document.getElementById('deliveryModal').style.display = 'none'; // Reset button visibility for next time document.getElementById('deliveryAssignBtn').style.display = 'inline-block'; document.getElementById('deliverySelectClientBtn').style.display = 'none'; // Now show courier selection modal await loadCouriers(); if (couriers.length === 0) { await customAlert('No couriers available. Please add a courier first.'); selectedDeliveryClient = null; return; } // Populate courier dropdown const courierSelect = document.getElementById('headerDeliveryCourierSelect'); courierSelect.innerHTML = ''; couriers.forEach(courier => { const option = document.createElement('option'); option.value = courier.id; option.textContent = courier.name; courierSelect.appendChild(option); }); // Show selected client name in courier modal document.getElementById('headerDeliveryClientName').textContent = client.client_name; // Show courier selection modal document.getElementById('headerDeliveryCourierModal').style.display = 'flex'; } // Close header delivery courier modal function closeHeaderDeliveryCourierModal() { document.getElementById('headerDeliveryCourierModal').style.display = 'none'; // If user cancels courier selection, clear the delivery client and revert to In Dining if (!selectedDeliveryCourier) { selectedDeliveryClient = null; deliveryModeFromHeader = false; currentOrderType = 'in_dining'; document.getElementById('btnDelivery').classList.remove('active'); document.getElementById('btnInDining').classList.add('active'); updateDeliveryClientDisplay(); } } // Confirm header delivery courier selection async function confirmHeaderDeliveryCourier() { const selectedCourierId = document.getElementById('headerDeliveryCourierSelect').value; if (!selectedCourierId) { await customAlert('Please select a courier'); return; } // Store selected courier selectedDeliveryCourier = couriers.find(c => c.id == selectedCourierId); const tableNo = document.getElementById('tableNo').value; // Save delivery info to database try { const response = await fetch('api/orders.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'set_table_delivery', table_no: tableNo, delivery_client_id: selectedDeliveryClient.id, courier_id: selectedCourierId }) }); const result = await response.json(); if (!result.success) { showNotification('Error setting delivery: ' + result.message, 'error'); return; } // Close modal document.getElementById('headerDeliveryCourierModal').style.display = 'none'; // Update display updateDeliveryClientDisplay(); console.log('Delivery set - Client:', selectedDeliveryClient, 'Courier:', selectedDeliveryCourier); } catch (error) { console.error('Error setting delivery:', error); showNotification('Error setting delivery. Please try again.', 'error'); } } // Toggle between list and grid view function toggleView() { const itemsList = document.getElementById('itemsList'); const itemsGrid = document.getElementById('itemsGrid'); const toggleText = document.getElementById('viewToggleText'); const toggleTextMobile = document.getElementById('viewToggleTextMobile'); if (currentView === 'list') { currentView = 'grid'; itemsList.style.display = 'none'; itemsGrid.style.display = 'grid'; toggleText.textContent = '📋 List View'; if (toggleTextMobile) toggleTextMobile.textContent = '📋 List'; } else { currentView = 'list'; itemsList.style.display = 'block'; itemsGrid.style.display = 'none'; toggleText.textContent = '📱 Grid View'; if (toggleTextMobile) toggleTextMobile.textContent = '📱 Grid'; } // Reload items in new view if (currentPOS) { displayItems(allItems); } } // Load POS data when POS is selected async function loadPOSData(posId = null) { // If no posId provided, use current POS if (!posId) { posId = currentPOS; } if (!posId) { document.getElementById('itemsPlaceholder').style.display = 'block'; document.getElementById('itemsList').style.display = 'none'; document.getElementById('itemsGrid').style.display = 'none'; document.getElementById('categoryTabs').style.display = 'none'; return; } currentPOS = posId; try { // Load categories and items for this POS in parallel (independent requests) const [categoriesResponse, itemsResponse] = await Promise.all([ fetch(`api/items.php?action=get_categories&pos_id=${posId}`), fetch(`api/items.php?action=get_all_items&pos_id=${posId}`) ]); const [categoriesData, itemsData] = await Promise.all([ categoriesResponse.json(), itemsResponse.json() ]); if (categoriesData.success) { categories = categoriesData.categories; displayCategories(categories); } if (itemsData.success) { allItems = itemsData.items; document.getElementById('itemsPlaceholder').style.display = 'none'; displayItems(allItems); } // Load all pos_notes (for notes applicable dropdown) if (allPosNotes.length === 0) { try { const notesResponse = await fetch('api/items.php?action=get_pos_notes'); const notesData = await notesResponse.json(); if (notesData.success) { allPosNotes = notesData.notes; } } catch (e) { console.error('Error loading pos_notes:', e); } } } catch (error) { console.error('Error loading POS data:', error); showNotification('Error loading items. Please try again.', 'error'); } } // Helper function to capitalize first letter function capitalizeFirstLetter(str) { return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase(); } // Display categories as tabs function displayCategories(categoriesList) { const categoryTabs = document.getElementById('categoryTabs'); categoryTabs.style.display = 'block'; categoryTabs.innerHTML = ''; // Sort: accompaniment categories (accomp_status=1) go to the end const sortedCategories = [...categoriesList].sort((a, b) => { const aIsAccomp = parseInt(a.accomp_status) === 1 ? 1 : 0; const bIsAccomp = parseInt(b.accomp_status) === 1 ? 1 : 0; if (aIsAccomp !== bIsAccomp) return aIsAccomp - bIsAccomp; return (a.category_name || '').localeCompare(b.category_name || ''); }); // Create category row container const categoryRow = document.createElement('div'); categoryRow.className = 'category-row'; categoryRow.id = 'categoryRow'; // Add "All" category button const allTab = document.createElement('button'); allTab.className = 'category-tab active'; allTab.textContent = 'All'; allTab.dataset.isAllButton = 'true'; categoryRow.appendChild(allTab); // Assign colors to categories categoryColorMap = {}; sortedCategories.forEach((category, index) => { categoryColorMap[category.id] = CATEGORY_COLORS[index % CATEGORY_COLORS.length]; }); // Add all categories initially sortedCategories.forEach(category => { const tab = document.createElement('div'); tab.className = 'category-tab'; // Apply category color const catColor = categoryColorMap[category.id]; if (catColor) { tab.style.background = catColor.bg; tab.style.borderColor = catColor.border; } // Mark accompaniment categories visually if (parseInt(category.accomp_status) === 1) { tab.classList.add('category-tab-accompaniment'); } // Add category image or default icon if (category.category_image && category.category_image.trim() !== '') { const img = document.createElement('img'); // Fix image path - go up one level from v2 to pos directory let imagePath = category.category_image; if (imagePath.startsWith('posimages/')) { imagePath = '../' + imagePath; } img.src = imagePath; img.alt = category.category_name; img.className = 'category-image'; tab.appendChild(img); } else { // Use default icon if no image const iconSpan = document.createElement('span'); iconSpan.className = 'category-icon'; iconSpan.textContent = '🍽️'; tab.appendChild(iconSpan); } const nameSpan = document.createElement('span'); nameSpan.textContent = capitalizeFirstLetter(category.category_name); tab.appendChild(nameSpan); tab.dataset.categoryId = category.id; tab.onclick = () => filterByCategory(category.id); categoryRow.appendChild(tab); }); categoryTabs.appendChild(categoryRow); // Setup "All" button functionality allTab.onclick = () => { toggleCategoriesExpand(sortedCategories); filterByCategory(null); }; } // Filter items by category async function filterByCategory(categoryId) { currentCategory = categoryId; // Update active tab - restore normal colors on all, apply active color on selected document.querySelectorAll('.category-tab').forEach(tab => { tab.classList.remove('active'); const catId = tab.dataset.categoryId; const color = categoryColorMap[catId]; if (color) { tab.style.background = color.bg; tab.style.borderColor = color.border; tab.style.color = '#333'; } else { tab.style.background = ''; tab.style.borderColor = ''; tab.style.color = ''; } }); const clickedTab = event.target.closest('.category-tab') || event.target; clickedTab.classList.add('active'); const activeCatId = clickedTab.dataset.categoryId; const activeColor = categoryColorMap[activeCatId]; if (activeColor) { clickedTab.style.background = activeColor.active; clickedTab.style.borderColor = activeColor.active; clickedTab.style.color = 'white'; } else { clickedTab.style.background = '#3498db'; clickedTab.style.borderColor = '#3498db'; clickedTab.style.color = 'white'; } if (!categoryId) { // Show all items displayItems(allItems); } else { // Filter items by category const filteredItems = allItems.filter(item => item.item_category == categoryId); displayItems(filteredItems); } } // Display items in list or grid view function displayItems(items) { const itemsList = document.getElementById('itemsList'); const itemsGrid = document.getElementById('itemsGrid'); itemsList.innerHTML = ''; itemsGrid.innerHTML = ''; // Sort: accompaniment items (cat_accomp_status=1) go to the bottom const sortedItems = [...items].sort((a, b) => { const aIsAccomp = parseInt(a.cat_accomp_status) === 1 ? 1 : 0; const bIsAccomp = parseInt(b.cat_accomp_status) === 1 ? 1 : 0; return aIsAccomp - bIsAccomp; }); if (sortedItems.length === 0) { const noItems = '
No items found
'; itemsList.innerHTML = noItems; itemsGrid.innerHTML = noItems; return; } sortedItems.forEach(item => { // List view const listCard = createListCard(item); itemsList.appendChild(listCard); // Grid view const gridCard = createGridCard(item); itemsGrid.appendChild(gridCard); }); // Show appropriate view if (currentView === 'list') { itemsList.style.display = 'block'; itemsGrid.style.display = 'none'; } else { itemsList.style.display = 'none'; itemsGrid.style.display = 'grid'; } } // Build an for an item's picture (retail mode only). The selling page lives at // pms/pos/v2/, item images at pms/uploads/items/. Returns '' when not retail or no image. // Hovering the thumbnail shows an enlarged floating preview (see showItemZoom). function itemImageHtml(item, style) { if (typeof IS_SUPERMARKET === 'undefined' || !IS_SUPERMARKET) return ''; const img = item.inv_item_image; if (!img) return ''; const src = '../../uploads/items/' + encodeURIComponent(img); return ``; } // Floating enlarged preview shown while hovering an item image. Uses a single shared // element appended to with pointer-events:none so clicks still hit the card. function ensureItemZoomEl() { let z = document.getElementById('itemImageZoom'); if (!z) { z = document.createElement('div'); z.id = 'itemImageZoom'; z.style.cssText = 'position:fixed; z-index:99999; pointer-events:none; display:none; ' + 'border:3px solid #fff; border-radius:10px; box-shadow:0 8px 30px rgba(0,0,0,0.4); background:#fff;'; z.innerHTML = ''; document.body.appendChild(z); } return z; } function showItemZoom(e, src) { const z = ensureItemZoomEl(); z.querySelector('img').src = src; z.style.display = 'block'; moveItemZoom(e); } function moveItemZoom(e) { const z = document.getElementById('itemImageZoom'); if (!z || z.style.display === 'none') return; const pad = 18, w = 286, h = 286; let x = e.clientX + pad; let y = e.clientY + pad; if (x + w > window.innerWidth) x = e.clientX - w - pad; // flip left near right edge if (y + h > window.innerHeight) y = window.innerHeight - h - pad; if (x < 0) x = pad; if (y < 0) y = pad; z.style.left = x + 'px'; z.style.top = y + 'px'; } function hideItemZoom() { const z = document.getElementById('itemImageZoom'); if (z) z.style.display = 'none'; } // Create list view card function createListCard(item) { const card = document.createElement('div'); card.className = 'item-card-list'; card.setAttribute('data-item-id', item.id); // lets adjustLocalAvailability patch this card card.onclick = () => addToCart(item); // Apply category color const catColor = categoryColorMap[item.item_category]; if (catColor) { card.style.borderLeft = `4px solid ${catColor.active}`; card.style.background = catColor.bg; } const barcodeDisplay = (typeof IS_SUPERMARKET !== 'undefined' && IS_SUPERMARKET && item.bar_code) ? `${item.bar_code}` : ''; // Available quantity column (supermarket/retail mode) let qtyColumn = ''; if (typeof IS_SUPERMARKET !== 'undefined' && IS_SUPERMARKET) { const av = formatAvQty(item.available_qty); const lowClass = (av !== '—' && parseFloat(item.available_qty) <= 0) ? ' item-card-qty--out' : ''; qtyColumn = `
Available Qty ${av}
`; } const thumbHtml = itemImageHtml(item, 'width:64px;height:64px;object-fit:cover;border-radius:6px;flex:0 0 auto;'); card.innerHTML = `
${thumbHtml}
${item.item_name}
${item.category_name || ''} ${barcodeDisplay}
${qtyColumn}
${formatCurrency(item.item_price)}
`; return card; } // Format an available-quantity value: blank/null -> em dash, otherwise a // trimmed number (no trailing zeros, e.g. 5, 12.5). function formatAvQty(value) { if (value === null || value === undefined || value === '') return '—'; const n = parseFloat(value); if (isNaN(n)) return '—'; return (Math.round(n * 100) / 100).toString(); } /** * Instantly adjust an item's Available Qty after a stock change — no network round-trip * and no full re-render (it patches just the one card's cell). Built for a busy * supermarket with many concurrent cashiers, where a per-click /get_all_items fetch * would be the bottleneck. * deltaQty > 0 -> units sold (reduce available) * deltaQty < 0 -> units restored (increase available) * The server still enforces real stock on add (api/check_stock.php), so a figure that is * momentarily stale due to another cashier's concurrent sale can never cause overselling; * it reconciles on the next settle/refresh. */ // Reduce one item's available_qty (in memory) by `delta` and patch its visible list card. function patchItemAvailability(it, delta) { if (!it || !delta) return; if (it.available_qty === null || it.available_qty === undefined || it.available_qty === '') return; const v = parseFloat(it.available_qty); if (isNaN(v)) return; it.available_qty = v - delta; // keep the in-memory catalog correct for re-renders/search // Patch the visible list card's cell only (no re-render → no scroll jump / flicker) const card = document.querySelector('.item-card-list[data-item-id="' + it.id + '"]'); if (!card) return; const valEl = card.querySelector('.item-card-qty-value'); if (valEl) valEl.textContent = formatAvQty(it.available_qty); const qtyBox = card.querySelector('.item-card-qty'); if (qtyBox) qtyBox.classList.toggle('item-card-qty--out', parseFloat(it.available_qty) <= 0); } function adjustLocalAvailability(itemId, deltaQty) { if (typeof IS_SUPERMARKET === 'undefined' || !IS_SUPERMARKET) return; if (!deltaQty) return; if (typeof allItems === 'undefined' || !allItems) return; const it = allItems.find(i => String(i.id) === String(itemId)); if (!it) return; // 1) The sold/changed item itself. patchItemAvailability(it, deltaQty); // 2) Propagate across sibling UOMs that draw from the SAME base inventory stock // (e.g. Yoghurt Tins & Boxes). Selling `deltaQty` units consumes // deltaQty * stock_input_qty base units; each sibling's availability is // base_stock / its own stock_input_qty, so it changes by baseDelta / sibling_qty. const baseNo = parseInt(it.stock_item_no); const itInputQty = parseFloat(it.stock_input_qty); if (!baseNo || !(itInputQty > 0)) return; const baseDelta = deltaQty * itInputQty; allItems.forEach(sib => { if (sib === it) return; if (parseInt(sib.stock_item_no) !== baseNo) return; const sibInputQty = parseFloat(sib.stock_input_qty); if (!(sibInputQty > 0)) return; patchItemAvailability(sib, baseDelta / sibInputQty); }); } // Create grid view card function createGridCard(item) { const card = document.createElement('div'); card.className = 'item-card-grid'; card.onclick = () => addToCart(item); // Apply category color const catColor = categoryColorMap[item.item_category]; if (catColor) { card.style.background = catColor.bg; card.style.borderColor = catColor.border; } const gridImgHtml = itemImageHtml(item, 'width:100%;height:110px;object-fit:cover;border-radius:6px;margin-bottom:6px;display:block;'); card.innerHTML = ` ${gridImgHtml}
${item.item_name}
${formatCurrency(item.item_price)}
`; return card; } // Search items function searchItems() { const searchTerm = document.getElementById('itemSearch').value.toLowerCase(); if (!currentPOS || !allItems.length) { return; } // In accompaniment mode, only search within accompaniment items let searchPool = allItems; if (accompMode) { searchPool = allItems.filter(item => parseInt(item.cat_accomp_status) === 1); } const filtered = searchPool.filter(item => item.item_name.toLowerCase().includes(searchTerm) || (item.category_name && item.category_name.toLowerCase().includes(searchTerm)) || (item.bar_code && item.bar_code.toLowerCase().includes(searchTerm)) ); displayItems(filtered); } // Check if current POS is unclosed (yesterday not closed) function isPOSUnclosed(posId) { // window.unclosedPOSList is set by selling.php from pending_checks.php if (window.unclosedPOSList && window.unclosedPOSList.length > 0) { return window.unclosedPOSList.includes(String(posId)); } return false; } // Add item to cart - now opens modal first function addToCart(item) { // Check if current POS is unclosed - block adding new items if (isPOSUnclosed(currentPOS)) { showNotification('Cannot add items: Yesterday\'s orders for this POS have not been closed. Please close the day first.', 'error'); return; } // Check if there are incomplete reservations - block adding new items if (window.hasIncompleteReservations) { showNotification('Cannot add items: There are incomplete reservations that need to be completed first.', 'error'); return; } // Supermarket mode: quick-add with quantity 1 (skip modal and accompaniment logic) if (typeof IS_SUPERMARKET !== 'undefined' && IS_SUPERMARKET) { quickAddToCart(item); return; } // If in accompaniment mode, handle as accompaniment selection if (accompMode) { addAccompanimentToCart(item); return; } // Prevent selling an accompaniment item (cat_accomp_status=1) outside accompaniment mode const catAccompStatus = parseInt(item.cat_accomp_status) || 0; if (catAccompStatus === 1) { // Check if there is a "sold with accompaniments" item in the cart const hasEligibleParent = cart.some(ci => parseInt(ci.cat_accomp_status) === 2); if (!hasEligibleParent) { showNotification('Cannot sell an accompaniment item on its own. Please add a main item that is sold with accompaniments first.', 'warning'); return; } } openAddItemModal(item); } // Update cart display function updateCartDisplay() { const cartItems = document.getElementById('cartItems'); const cartEmpty = document.getElementById('cartEmpty'); const clearCartBtn = document.getElementById('clearCartBtn'); const cartSummary = document.getElementById('cartSummary'); const cartActions = document.getElementById('cartActions'); // Always show cart actions (so Options button is always available for Posting Date) cartActions.style.display = 'flex'; // Get the action buttons that should be hidden when cart is empty const saveOrderBtn = cartActions.querySelector('.btn-save-order'); const printBillBtn = cartActions.querySelector('.btn-print-bill'); const settleBtn = cartActions.querySelector('.btn-settle'); if (cart.length === 0) { // Clear the cart items HTML cartItems.innerHTML = `
🛒

Cart is empty

Add items to start an order

`; if (clearCartBtn) clearCartBtn.style.display = 'none'; cartSummary.style.display = 'none'; // Hide order-related buttons but keep Options visible if (saveOrderBtn) saveOrderBtn.style.display = 'none'; if (printBillBtn) printBillBtn.style.display = 'none'; if (settleBtn) settleBtn.style.display = 'none'; return; } cartEmpty.style.display = 'none'; if (clearCartBtn) clearCartBtn.style.display = 'block'; cartSummary.style.display = 'block'; // Show all action buttons when cart has items if (saveOrderBtn) saveOrderBtn.style.display = 'flex'; if (printBillBtn) printBillBtn.style.display = 'flex'; if (settleBtn) settleBtn.style.display = 'flex'; // Build cart items HTML let cartHTML = ''; // Keep the cartEmpty div cartHTML += ` `; // Group items by waiter for saved items, unsaved items go to a separate group const itemsByWaiter = {}; const unsavedItems = []; cart.forEach((item, index) => { item._cartIndex = index; // Store original cart index for reference if (item.isSaved) { // Use waiter_id as key, or 'unknown' if no waiter_id const key = item.waiter_id || 'unknown'; if (!itemsByWaiter[key]) { itemsByWaiter[key] = { waiter_name: item.waiter_name || 'Unknown', items: [] }; } itemsByWaiter[key].items.push(item); } else { unsavedItems.push(item); } }); // Start notepad list cartHTML += '
'; // Render unsaved items first (new items being added) if (unsavedItems.length > 0) { cartHTML += `
New Items (Not Saved)
`; unsavedItems.forEach(item => { const index = item._cartIndex; const itemTotal = (item.price * item.quantity) - item.discount; const notesDisplay = item.notes ? `(${item.notes})` : ''; const isSelected = selectedCartIndex === index; const inlineControls = (typeof IS_SUPERMARKET !== 'undefined' && IS_SUPERMARKET) ? `
` : `
`; cartHTML += `
${item.quantity}x ${item.name} ${notesDisplay} ${formatAmount(itemTotal)}
${inlineControls}
`; }); cartHTML += '
'; } // Render saved items grouped by waiter, then by KOT // First, create a combined grouping: waiter + KOT const kotGroups = []; Object.keys(itemsByWaiter).forEach(waiterId => { const waiterGroup = itemsByWaiter[waiterId]; // Group items by KOT number within each waiter const itemsByKot = {}; waiterGroup.items.forEach(item => { const kotKey = item.kot_no || 'no_kot'; if (!itemsByKot[kotKey]) { itemsByKot[kotKey] = []; } itemsByKot[kotKey].push(item); }); // Add each KOT group with waiter info Object.keys(itemsByKot).forEach(kotNo => { kotGroups.push({ kotNo: kotNo, waiterName: waiterGroup.waiter_name, items: itemsByKot[kotNo] }); }); }); // Render each KOT group with waiter name kotGroups.forEach(group => { let kotLabel = 'Pending KOT'; if (group.kotNo !== 'no_kot') { const kotTime = group.items[0]?.kot_time; const timeStr = kotTime ? ` @ ${new Date(kotTime).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'})}` : ''; kotLabel = `KOT #${group.kotNo}${timeStr}`; } cartHTML += `
👤 ${group.waiterName} ${kotLabel}
`; group.items.forEach(item => { const index = item._cartIndex; const itemTotal = (item.price * item.quantity) - item.discount; const notesDisplay = item.notes ? `(${item.notes})` : ''; const isSelected = selectedCartIndex === index; // Detect accompaniment items (total_amount=0 and from accompaniment category) const isAccompItem = (parseFloat(item.total_amount) === 0 && parseInt(item.cat_accomp_status) === 1); const accompClass = isAccompItem ? ' accomp-item' : ''; // Hide X button if item has been printed on KOT or Bill const isPrinted = (item.print_status && item.print_status != '0') || (item.bill_print_status && item.bill_print_status != '0'); const removeBtn = isPrinted ? '' : ``; const savedInlineControls = (typeof IS_SUPERMARKET !== 'undefined' && IS_SUPERMARKET) ? `
` : `
`; cartHTML += `
${item.quantity}x ${item.name}${isAccompItem ? ' (acc)' : ''} ${notesDisplay} ${formatAmount(itemTotal)} ${removeBtn}
${savedInlineControls}
`; }); cartHTML += '
'; }); cartHTML += '
'; cartItems.innerHTML = cartHTML; // Calculate totals const subtotal = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0); const totalDiscount = cart.reduce((sum, item) => sum + item.discount, 0); const total = subtotal - totalDiscount; document.getElementById('subtotal').textContent = formatAmount(subtotal); document.getElementById('discount').textContent = formatAmount(totalDiscount); document.getElementById('total').textContent = formatAmount(total); // Show/hide subtotal and discount rows based on whether discount exists if (totalDiscount > 0) { document.getElementById('subtotalRow').style.display = 'flex'; document.getElementById('discountRow').style.display = 'flex'; } else { document.getElementById('subtotalRow').style.display = 'none'; document.getElementById('discountRow').style.display = 'none'; } } // Cart manipulation functions function increaseQuantity(index) { cart[index].quantity++; // If this was a saved item, mark it as unsaved and track original quantity if (cart[index].isSaved) { if (!cart[index].originalQuantity) { cart[index].originalQuantity = cart[index].quantity - 1; } cart[index].isSaved = false; } updateCartDisplay(); } function decreaseQuantity(index) { if (cart[index].quantity > 1) { cart[index].quantity--; // If this was a saved item, mark it as unsaved and track original quantity if (cart[index].isSaved) { if (!cart[index].originalQuantity) { cart[index].originalQuantity = cart[index].quantity + 1; } cart[index].isSaved = false; cart[index].quantityReduced = true; // Flag that quantity was reduced } updateCartDisplay(); } } async function removeFromCart(index) { const item = cart[index]; if (!item) { console.error('Item not found at index:', index); showNotification('Error: Item not found', 'error'); return; } // Check permission to remove items from cart (only for saved items) if (item.isSaved && !hasPermission('remove_cart_items')) { await customAlert('You do not have permission to remove items from the cart.'); return; } // For saved items, check print status before allowing removal if (item.isSaved) { if (item.print_status && item.print_status != '0') { showNotification('Cannot remove this item. It has already been printed on a KOT.', 'warning'); return; } if (item.bill_print_status && item.bill_print_status != '0') { showNotification('Cannot remove this item. It has already been printed on a Bill.', 'warning'); return; } } if (!(await customConfirm('Remove this item from cart?'))) { return; } // Check if this is a saved item that needs to be deleted from database if (item.isSaved) { // Check if this is an extra charge or room service (item_no = 0) const itemId = item.id; const itemNo = item.item_no; const isExtraChargeItem = ( itemId === 0 || itemId === '0' || parseInt(itemId) === 0 || itemNo === 0 || itemNo === '0' || (typeof itemId === 'string' && (itemId.startsWith('extra_charge_') || itemId.startsWith('room_service_'))) ); if (isExtraChargeItem) { // Extra charge deletion (existing logic) try { const tableNo = document.getElementById('tableNo').value; const posId = item.pos_id || currentPOS; const itemDescription = item.name || item.description; const resOrderId = item.res_order_id || null; const orderNo = item.order_no || null; const response = await fetch('api/orders.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'delete_extra_charge', table_no: tableNo, pos_id: posId, res_order_id: resOrderId, order_no: orderNo, description: itemDescription, price: item.price }) }); const result = await response.json(); if (!result.success) { showNotification('Error removing item: ' + result.message, 'error'); return; } } catch (error) { console.error('Error deleting extra charge:', error); showNotification('Error removing item: ' + error.message, 'error'); return; } } else { // Regular saved item - call remove_order_item API try { const response = await fetch('api/orders.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'remove_order_item', res_order_item_id: item.res_order_item_id }) }); const result = await response.json(); if (!result.success) { showNotification(result.message || 'Error removing item from database.', 'error'); return; } } catch (error) { console.error('Error removing order item:', error); showNotification('Error removing item: ' + error.message, 'error'); return; } } } // Remove from cart array after successful DB deletion (or for unsaved items) const removed = cart[index]; cart.splice(index, 1); selectedCartIndex = null; updateCartDisplay(); // Supermarket: removing a saved item restored its stock — instantly bump Available Qty back if (removed && removed.isSaved && typeof IS_SUPERMARKET !== 'undefined' && IS_SUPERMARKET) { adjustLocalAvailability(removed.id, -(parseFloat(removed.quantity) || 0)); } } function updateItemNotes(index, notes) { cart[index].notes = notes; persistItemNotes(cart[index]); } // Persist notes to DB for an already-saved item function persistItemNotes(item) { if (!item || !item.isSaved || !item.res_order_item_id) return; fetch('api/orders.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'update_item_notes', res_order_item_id: item.res_order_item_id, notes: item.notes || '' }) }).catch(err => console.error('Error updating notes:', err)); } async function clearCart() { if (await customConfirm('Clear all items from cart?')) { cart = []; selectedCartIndex = null; updateCartDisplay(); // Clear deposit selection when cart is cleared if (typeof clearDepositOnTableChange === 'function') { clearDepositOnTableChange(); } // Clear membership selection when cart is cleared if (typeof clearMembershipOnTableChange === 'function') { clearMembershipOnTableChange(); } // Clear loyalty selection when cart is cleared if (typeof clearLoyaltyOnTableChange === 'function') { clearLoyaltyOnTableChange(); } } } // Notepad list item selection functions function selectCartItem(index) { // If clicking on already selected item, close it if (selectedCartIndex === index) { closeItemControls(); return; } // Hide all other inline controls first document.querySelectorAll('.inline-item-controls').forEach(el => { el.style.display = 'none'; }); // Remove selection from all items document.querySelectorAll('.notepad-item').forEach(el => { el.classList.remove('selected'); }); selectedCartIndex = index; // Highlight selected item const selectedItem = document.querySelector(`.notepad-item[data-index="${index}"]`); if (selectedItem) { selectedItem.classList.add('selected'); } // Show inline controls for this item const controls = document.getElementById(`itemControls_${index}`); if (controls) { controls.style.display = 'block'; } } function closeItemControls() { selectedCartIndex = null; document.querySelectorAll('.inline-item-controls').forEach(el => { el.style.display = 'none'; }); document.querySelectorAll('.notepad-item').forEach(el => { el.classList.remove('selected'); }); } function increaseSelectedQty() { if (selectedCartIndex === null) return; cart[selectedCartIndex].quantity++; document.getElementById('selectedQtyDisplay').textContent = cart[selectedCartIndex].quantity; updateCartDisplay(); // Re-select the item after update setTimeout(() => selectCartItem(selectedCartIndex), 0); } function decreaseSelectedQty() { if (selectedCartIndex === null) return; if (cart[selectedCartIndex].quantity > 1) { cart[selectedCartIndex].quantity--; cart[selectedCartIndex].quantityReduced = true; document.getElementById('selectedQtyDisplay').textContent = cart[selectedCartIndex].quantity; updateCartDisplay(); // Re-select the item after update setTimeout(() => selectCartItem(selectedCartIndex), 0); } } function updateSelectedNotes(notes) { if (selectedCartIndex === null) return; cart[selectedCartIndex].notes = notes; persistItemNotes(cart[selectedCartIndex]); updateCartDisplay(); // Re-select the item after update setTimeout(() => selectCartItem(selectedCartIndex), 0); } // Save order (KOT) async function saveOrder() { console.log('saveOrder called'); console.log('selectedDeliveryClient at save time:', selectedDeliveryClient); if (cart.length === 0) { await customAlert('Cart is empty. Please add items first.'); return; } const tableNo = document.getElementById('tableNo').value; const tableId = document.getElementById('tableId').value; const userId = document.getElementById('userId').value; // Check for table conflict - another person has pending orders on this table try { const conflictResp = await fetch(`api/check_table_conflict.php?table_no=${encodeURIComponent(tableNo)}&user_id=${userId}`); const conflictData = await conflictResp.json(); if (conflictData.success && conflictData.conflict) { const waiterName = conflictData.waiter_name || 'another user'; if (hasPermission('table_sharing')) { // Has permission - confirm before proceeding const proceed = await customConfirm( 'This table is currently being served by \'' + waiterName + '\', do you want to proceed?' ); if (!proceed) return; } else { // No permission - block and redirect to tables await customAlert('You do not have permission to access tables assigned to other staff members. This table is currently assigned to ' + waiterName + '.'); window.location.href = 'tables.php'; return; } } } catch (conflictErr) { console.error('Error checking table conflict:', conflictErr); // Continue with save if the check fails - don't block the order } // First, handle quantity reductions const itemsWithReductions = cart.filter(item => !item.isSaved && item.quantityReduced && item.originalQuantity > item.quantity); for (const item of itemsWithReductions) { const quantityToReduce = item.originalQuantity - item.quantity; try { const response = await fetch('api/orders.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'reduce_item_quantity', table_no: tableNo, item_id: item.id, pos_id: item.pos_id, quantity: quantityToReduce }) }); const result = await response.json(); if (!result.success) { showNotification('Error reducing quantity: ' + result.message, 'error'); return; } } catch (error) { console.error('Error reducing quantity:', error); showNotification('Error reducing quantity. Please try again.', 'error'); return; } } // Prepare items to save - only unsaved items with positive quantity changes const itemsToSave = cart .filter(item => !item.isSaved && !item.quantityReduced) .map(item => { // If this item had an original quantity, only send the additional quantity if (item.originalQuantity && item.originalQuantity > 0 && item.quantity > item.originalQuantity) { return { ...item, quantity: item.quantity - item.originalQuantity }; } return item; }) .filter(item => item.quantity > 0); // Only include items with positive quantity if (itemsToSave.length === 0 && itemsWithReductions.length === 0) { await customAlert('No new items to save. All items are already saved.'); return; } // If there are no items to add, skip the save_order call if (itemsToSave.length === 0) { showNotification('Order updated successfully!', 'success'); // Mark all items as saved cart.forEach(item => { item.isSaved = true; item.originalQuantity = item.quantity; item.quantityReduced = false; }); updateCartDisplay(); return; } // Only send new items to be saved const orderData = { action: 'save_order', table_id: tableId, user_id: userId, items: itemsToSave }; // If delivery client is selected, include delivery info if (selectedDeliveryClient && selectedDeliveryClient.id) { orderData.delivery_client_id = parseInt(selectedDeliveryClient.id); orderData.order_type = 'delivery'; console.log('Saving with delivery client:', selectedDeliveryClient.id); } console.log('Full orderData being sent:', JSON.stringify(orderData)); try { const response = await fetch('api/orders.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(orderData) }); const responseText = await response.text(); console.log('API Response:', responseText); let result; try { result = JSON.parse(responseText); } catch (e) { console.error('Failed to parse response:', responseText); showNotification('Error: Invalid response from server', 'error'); return; } if (result.success) { // Store order info in cart items for KOT printing if (result.orders && result.orders.length > 0) { const orderNo = result.orders[0].order_no || result.orders[0].order_id; cart.forEach(item => { if (!item.order_no) { item.order_no = orderNo; } }); } // Mark all items as saved now and update original quantities cart.forEach(item => { item.isSaved = true; item.originalQuantity = item.quantity; // Update to current quantity item.quantityReduced = false; // Reset the reduction flag }); updateCartDisplay(); } else { showNotification('Error saving order: ' + (result.message || 'Unknown error'), 'error'); } } catch (error) { console.error('Error:', error); showNotification('Error saving order. Please try again.', 'error'); } } // Note: openSettlement() function is now in settlement.js // Load existing order if table is occupied async function loadExistingOrder() { const tableNo = document.getElementById('tableNo').value; if (!tableNo) { return; } try { // Get all pending orders for this table const response = await fetch(`api/orders.php?action=get_table_orders&table_no=${tableNo}`); const result = await response.json(); if (result.success && result.items && result.items.length > 0) { // Load existing items into cart to display them cart = result.items.map(item => { const qty = parseInt(item.quantity) || 1; // Try set_price first, then calculate from total_amount if available let price = parseFloat(item.set_price); if (isNaN(price) || price === 0) { // Fallback: calculate price from total_amount / quantity const totalAmount = parseFloat(item.total_amount); if (!isNaN(totalAmount) && totalAmount > 0 && qty > 0) { price = totalAmount / qty; } else { price = 0; } } return { id: item.item_no, res_order_item_id: item.id, // Store the res_order_item.id for bill status checks name: item.description, price: price, quantity: qty, discount: parseFloat(item.item_discount || 0), notes: item.res_order_item_notes || '', pos_id: item.pos_no, res_order_id: item.res_order_id, // Store the order ID for deletion order_no: item.order_no, // Store the order number isSaved: true, // Mark existing items as already saved originalQuantity: qty, // Store the original saved quantity waiter_id: item.waiter_id || null, waiter_name: item.waiter_name || 'Unknown', kot_no: item.kot_no || null, kot_time: item.kot_time || null, cat_accomp_status: item.cat_accomp_status || '0', max_no_of_acc: parseInt(item.max_no_of_acc) || 0, total_amount: parseFloat(item.total_amount || 0), print_status: item.print_status || '0', bill_print_status: item.bill_print_status || '0', batch_no: item.batch_no || '' // expiry-tracked items: carry batch for +qty }; }); updateCartDisplay(); } else { // No items found - clear the cart cart = []; updateCartDisplay(); } } catch (error) { console.error('Error loading existing orders:', error); } } // Print KOT function printKOT(orderId) { window.open(`print_kot.php?order_id=${orderId}`, '_blank'); } // Send / Print KOT - Main function that saves order and prints KOT let isSendingKOT = false; async function sendPrintKOT() { console.log('sendPrintKOT called'); // Prevent duplicate clicks while KOT is being processed if (isSendingKOT) { console.log('KOT already in progress, ignoring duplicate click'); return; } isSendingKOT = true; // Re-enable after processing completes (finally block below) try { await _sendPrintKOTInner(); } finally { isSendingKOT = false; } } async function _sendPrintKOTInner() { // Check permission to send/print KOT if (!hasPermission('send_print_kot')) { await customAlert('You do not have permission to Send/Print KOT.'); return; } if (cart.length === 0) { await customAlert('Cart is empty. Please add items first.'); return; } const tableNo = document.getElementById('tableNo').value; const tableId = document.getElementById('tableId').value; const userId = document.getElementById('userId').value; const posNo = currentPOS || document.getElementById('currentPosId')?.value; // First, save any unsaved items by calling saveOrder logic // Check if there are unsaved items const hasUnsavedItems = cart.some(item => !item.isSaved); const hasQuantityReductions = cart.some(item => !item.isSaved && item.quantityReduced && item.originalQuantity > item.quantity); if (hasUnsavedItems || hasQuantityReductions) { // Save the order first await saveOrder(); // Small delay to ensure order is saved before checking for KOTs await new Promise(resolve => setTimeout(resolve, 500)); } // Get the order_no from the first saved cart item let orderNo = null; for (const item of cart) { if (item.order_no) { orderNo = item.order_no; break; } } if (!orderNo) { await customAlert('No order found. Please save items first.'); return; } // Check for unprinted KOTs using the existing endpoint try { const formData = new FormData(); formData.append('table_no', tableNo); formData.append('order_no', orderNo); formData.append('pos_no', posNo); const response = await fetch('../getKot.php?pendingKOTsSinglePrintmode', { method: 'POST', body: formData }); const content = await response.json(); // Check accompaniment status if (!content.acc_status) { showNotification('Warning: Accompaniments and main items do not match', 'warning'); return; } const data = content.rows || []; const noOfKots = data.length; if (noOfKots === 0) { await customAlert('All KOT items have already been printed.'); return; } // If multiple KOTs, ask about individual KOT notice if (noOfKots > 1) { const addNotice = await customConfirm('DO YOU WANT TO ADD INDIVIDUAL KOT NOTICE?'); if (addNotice) { // OK - open all previews for manual printing (add notes one at a time) for (const row of data) { printKOTReceipt(row.order_no, row.pos_no, row.table_no, noOfKots, false); } } else { // Cancel - auto-print all KOTs automatically for (const row of data) { printKOTReceipt(row.order_no, row.pos_no, row.table_no, noOfKots, true); } } } else { // Single KOT - just print it for (const row of data) { printKOTReceipt(row.order_no, row.pos_no, row.table_no, noOfKots, false); } } // Show success toast // KOT popup handles its own print feedback // Cart reload is triggered by the print window via window.opener.loadExistingOrder() // after print_status is updated in the database } catch (error) { console.error('Error checking for unprinted KOTs:', error); showNotification('Error sending KOT. Please try again.', 'error'); } } // Print KOT Receipt - Opens the KOT print window (v2) let kotPopupWindows = {}; function printKOTReceipt(orderNo, posNo, tableNo, noOfKots, autoPrint) { // Check global AUTO_PRINT_SETTING - if Yes, always auto-print const isAutoMode = (typeof AUTO_PRINT_SETTING !== 'undefined' && AUTO_PRINT_SETTING === 'Yes'); const autoPrintParam = (isAutoMode || (noOfKots > 1 && autoPrint)) ? 'auto_print' : ''; const url = `print/kot.php?order_no=${orderNo}&table_no=${tableNo}&auto_print=${autoPrintParam}&pos_no=${posNo}`; // Use a UNIQUE window name per open so every KOT preview is a fresh window // (history.length === 1). A reused/navigated window is no longer script-closable on // mobile, which left the preview stuck on "Printing..." because window.close() was // silently ignored. A fresh window closes reliably (like the bill/receipt popups). const windowName = 'kot_' + orderNo + '_' + posNo + '_' + Date.now() + '_' + Math.floor(Math.random() * 100000); const kotWin = window.open(url, windowName, 'width=400,height=900,scrollbar=no,location=no,resizable=no,dialog=yes,alwaysontop=yes,maximize=no,left=0,top=0'); kotPopupWindows[windowName] = kotWin; if (kotWin) { try { kotWin.focus(); } catch (e) {} // On mobile the popup often cannot close itself (window.close() is blocked and // window.opener may be severed). The opener CAN always close a window it opened, // so watch the popup and close it here once it signals the print/close is done. let kotTries = 0; const kotPoll = setInterval(function () { kotTries++; try { if (!kotWin || kotWin.closed) { clearInterval(kotPoll); return; } if (kotWin.__kotDone) { kotWin.close(); clearInterval(kotPoll); return; } } catch (e) { clearInterval(kotPoll); return; } if (kotTries > 1200) clearInterval(kotPoll); // ~10 min safety stop }, 500); } } // Logout function logout() { // Guard against repeated clicks: each click otherwise fires a fresh // navigation to api/logout.php, and the requests (plus the heavy license // check on index.php) pile up behind the PHP session lock and freeze the // app. Fire once, then ignore further triggers. if (window.__loggingOut) return; window.__loggingOut = true; document.querySelectorAll('.btn-logout').forEach(function(b) { b.disabled = true; b.style.pointerEvents = 'none'; b.style.opacity = '0.6'; }); window.location.href = 'api/logout.php'; } // Add Item Modal Functions function openAddItemModal(item) { currentModalItem = item; // Set modal content document.getElementById('modalItemName').textContent = item.item_name; document.getElementById('modalItemPrice').textContent = formatCurrency(item.item_price); document.getElementById('modalQuantity').value = 1; document.getElementById('modalNotes').value = ''; // Populate notes applicable dropdown populateNotesApplicable(item); // Calculate and display total updateModalTotal(); // Show modal document.getElementById('addItemModal').classList.add('active'); } function closeAddItemModal() { document.getElementById('addItemModal').classList.remove('active'); currentModalItem = null; } /** * Populate the notes applicable checkbox list based on the item's notes_applicable field. * notes_applicable contains comma-separated IDs that correspond to pos_notes.notes_id. */ function populateNotesApplicable(item) { const section = document.getElementById('notesApplicableSection'); const list = document.getElementById('notesApplicableList'); // Clear previous checkboxes list.innerHTML = ''; // Get the notes_applicable field from the item const notesApplicable = item.notes_applicable || ''; if (!notesApplicable || notesApplicable.trim() === '' || allPosNotes.length === 0) { section.style.display = 'none'; return; } // Parse the comma-separated IDs (format: ",1,3,5," or "1,3,5") const noteIds = notesApplicable.split(',').map(id => id.trim()).filter(id => id !== ''); if (noteIds.length === 0) { section.style.display = 'none'; return; } // Filter allPosNotes to only those matching the item's applicable IDs const applicableNotes = allPosNotes.filter(note => noteIds.includes(String(note.notes_id))); if (applicableNotes.length === 0) { section.style.display = 'none'; return; } // Build checkbox list applicableNotes.forEach(note => { const label = document.createElement('label'); label.className = 'notes-applicable-item'; const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.value = note.notes_description; checkbox.className = 'notes-applicable-checkbox'; const span = document.createElement('span'); span.textContent = note.notes_description; label.appendChild(checkbox); label.appendChild(span); list.appendChild(label); }); section.style.display = 'block'; } /** * Get all selected notes from the notes applicable checkboxes. */ function getSelectedApplicableNotes() { const checkboxes = document.querySelectorAll('.notes-applicable-checkbox:checked'); return Array.from(checkboxes).map(cb => cb.value); } function increaseModalQuantity() { const quantityInput = document.getElementById('modalQuantity'); quantityInput.value = parseInt(quantityInput.value) + 1; updateModalTotal(); } function decreaseModalQuantity() { const quantityInput = document.getElementById('modalQuantity'); if (parseInt(quantityInput.value) > 1) { quantityInput.value = parseInt(quantityInput.value) - 1; updateModalTotal(); } } function updateModalTotal() { if (!currentModalItem) return; // Accompaniment items always show 0 total if (currentModalItem._isAccompaniment) { document.getElementById('modalTotal').textContent = '0.00'; return; } const quantity = parseInt(document.getElementById('modalQuantity').value); const price = parseFloat(currentModalItem.item_price); const total = quantity * price; document.getElementById('modalTotal').textContent = formatCurrency(total); } async function confirmAddItem() { if (!currentModalItem) return; // Check permission to sell items if (!hasPermission('sell_items')) { await customAlert('You do not have permission to sell items.'); return; } // Check for table conflict - another person has pending orders on this table try { const tableNo = document.getElementById('tableNo').value; const userId = document.getElementById('userId').value; if (tableNo && userId) { const conflictResp = await fetch(`api/check_table_conflict.php?table_no=${encodeURIComponent(tableNo)}&user_id=${encodeURIComponent(userId)}`); const conflictData = await conflictResp.json(); if (conflictData.success && conflictData.conflict) { const waiterName = conflictData.waiter_name || 'another user'; if (hasPermission('table_sharing')) { const proceed = await customConfirm( 'This table is currently being served by \'' + waiterName + '\', do you want to proceed?' ); if (!proceed) return; } else { await customAlert('You do not have permission to access tables assigned to other staff members. This table is currently assigned to ' + waiterName + '.'); window.location.href = 'tables.php'; return; } } } } catch (conflictErr) { console.error('Error checking table conflict:', conflictErr); } const quantity = parseInt(document.getElementById('modalQuantity').value); // Combine selected applicable notes with free-text special instructions const selectedNotes = getSelectedApplicableNotes(); const freeTextNotes = document.getElementById('modalNotes').value.trim(); const notesParts = []; if (selectedNotes.length > 0) { notesParts.push(selectedNotes.join(', ')); } if (freeTextNotes) { notesParts.push(freeTextNotes); } const notes = notesParts.join('. '); // Validate quantity if (quantity <= 0 || isNaN(quantity)) { await customAlert('Please enter a valid quantity'); return; } // Check stock availability before proceeding try { const stockCheckResponse = await fetch( `api/check_stock.php?item_id=${currentModalItem.id}&pos_id=${currentModalItem.pos_no}&quantity=${quantity}` ); const stockResult = await stockCheckResponse.json(); if (!stockResult.success) { showNotification('Error checking stock: ' + (stockResult.message || 'Unknown error'), 'error'); return; } // Check if sufficient stock is available if (!stockResult.sufficient_stock) { if (stockResult.allow_negative_stock) { // Allow selling but confirm with user let confirmMsg = ''; stockResult.insufficient_items.forEach(item => { confirmMsg += `${item.item_name} is out of stock. ${item.available} in stock.\n`; }); confirmMsg += '\nConfirm if you want to proceed with the sale?'; const proceed = await customConfirm(confirmMsg); if (!proceed) return; } else { let message = 'Insufficient stock for the following items:\n\n'; stockResult.insufficient_items.forEach(item => { message += `${item.item_name}: Required ${item.required}, Available ${item.available}\n`; }); message += '\nCannot proceed with this order.'; await customAlert(message); return; } } } catch (error) { console.error('Error checking stock:', error); showNotification('Error checking stock availability. Please try again.', 'error'); return; } // Re-check closing time setting before adding item (in case time has changed) await checkAndApplyClosingTimeBackdate(); // Check if posting to a previous date and confirm with user const postingDate = sessionStorage.getItem('dateSelected'); if (postingDate) { const today = new Date().toISOString().split('T')[0]; // Get today's date in YYYY-MM-DD format if (postingDate < today) { const confirmed = await customConfirm(`Are you sure you are posting on the previous date of '${postingDate}'? Click OK to continue.`); if (!confirmed) { return; } } } // Prepare item data for immediate save const tableId = document.getElementById('tableId').value; const userId = document.getElementById('userId').value; // Detect if this is an accompaniment item const isAccompaniment = currentModalItem._isAccompaniment === true; // For accompaniments in accomp mode, enforce max limit if (isAccompaniment && accompParentMaxAcc > 0) { const maxAllowed = accompParentQuantity * accompParentMaxAcc; const remaining = maxAllowed - accompSelectedCount; if (quantity > remaining) { showNotification(`Cannot add ${quantity} accompaniment(s). Only ${remaining} more allowed.`, 'warning'); return; } } const itemToSave = { id: currentModalItem.id, name: currentModalItem.item_name, price: isAccompaniment ? 0 : parseFloat(currentModalItem.item_price), quantity: quantity, discount: 0, notes: notes, pos_id: currentModalItem.pos_no, is_accompaniment: isAccompaniment }; // Capture modal item details before closing (needed for accomp check after save) const savedModalItem = { ...currentModalItem }; const savedQuantity = quantity; // Close modal first closeAddItemModal(); // Save directly to database try { const orderData = { action: 'save_order', table_id: tableId, user_id: userId, items: [itemToSave] }; // If delivery client is selected, include delivery info if (selectedDeliveryClient && selectedDeliveryClient.id) { orderData.delivery_client_id = parseInt(selectedDeliveryClient.id); orderData.order_type = 'delivery'; if (selectedDeliveryCourier && selectedDeliveryCourier.id) { orderData.courier_id = parseInt(selectedDeliveryCourier.id); } console.log('Adding item with delivery client:', selectedDeliveryClient.id, 'courier:', selectedDeliveryCourier?.id); } // Include posting date if a custom date was selected const postingDate = sessionStorage.getItem('dateSelected'); if (postingDate) { orderData.posting_date = postingDate; } const response = await fetch('api/orders.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(orderData) }); const result = await response.json(); if (result.success) { if (isAccompaniment) { // Update accompaniment counter accompSelectedCount += savedQuantity; updateAccompCounter(); showNotification('Accompaniment added successfully!', 'success'); // Auto-exit if max reached if (accompParentMaxAcc > 0 && accompSelectedCount >= (accompParentQuantity * accompParentMaxAcc)) { showNotification('Maximum accompaniments reached.', 'info'); exitAccompanimentMode(); } } // Update the existingOrderId so settle button works if (result.order_id) { document.getElementById('existingOrderId').value = result.order_id; } // Reload existing orders to update the display await loadExistingOrder(); // If item is from a "sold with accompaniments" category, enter accompaniment mode if (!isAccompaniment) { const catAccompStatus = parseInt(savedModalItem.cat_accomp_status) || 0; if (catAccompStatus === 2) { enterAccompanimentMode(savedModalItem, savedQuantity); } } } else { showNotification('Error saving item: ' + (result.message || 'Unknown error'), 'error'); } } catch (error) { console.error('Error:', error); showNotification('Error saving item. Please try again.', 'error'); } } // Close modal when clicking outside document.addEventListener('click', function(event) { const modal = document.getElementById('addItemModal'); if (event.target === modal) { closeAddItemModal(); } }); // ==================== ACCOMPANIMENT FUNCTIONS ==================== // Enter accompaniment selection mode after adding a "sold with accompaniments" item async function enterAccompanimentMode(parentItem, quantity) { accompMode = true; accompParentItem = parentItem; accompParentQuantity = quantity; accompParentMaxAcc = parseInt(parentItem.max_no_of_acc) || 0; accompSelectedCount = 0; // Show prompt to user await customAlert('Please select an accompaniment'); // Filter display to show only accompaniment items and categories displayAccompanimentItems(); // Show the accompaniment banner showAccompBanner(); } // Exit accompaniment mode and restore normal display function exitAccompanimentMode() { accompMode = false; accompParentItem = null; accompParentQuantity = 0; accompParentMaxAcc = 0; accompSelectedCount = 0; // Hide the banner hideAccompBanner(); // Restore normal category and item display displayCategories(categories); displayItems(allItems); // Clear search document.getElementById('itemSearch').value = ''; } // Display only accompaniment items and categories function displayAccompanimentItems() { // Filter items to only accompaniment items (cat_accomp_status=1) const accompItems = allItems.filter(item => parseInt(item.cat_accomp_status) === 1); displayItems(accompItems); // Filter and display only accompaniment categories const accompCategories = categories.filter(cat => parseInt(cat.accomp_status) === 1); displayAccompanimentCategories(accompCategories); } // Display only accompaniment categories in the category tabs function displayAccompanimentCategories(accompCategories) { const categoryTabs = document.getElementById('categoryTabs'); categoryTabs.style.display = 'block'; categoryTabs.innerHTML = ''; const categoryRow = document.createElement('div'); categoryRow.className = 'category-row'; categoryRow.id = 'categoryRow'; // "All Accompaniments" button const allTab = document.createElement('button'); allTab.className = 'category-tab active'; allTab.textContent = 'All Accompaniments'; allTab.onclick = () => { document.querySelectorAll('.category-tab').forEach(t => t.classList.remove('active')); allTab.classList.add('active'); const accompItems = allItems.filter(item => parseInt(item.cat_accomp_status) === 1); displayItems(accompItems); }; categoryRow.appendChild(allTab); // Individual accompaniment category tabs accompCategories.forEach(category => { const tab = document.createElement('div'); tab.className = 'category-tab category-tab-accompaniment'; if (category.category_image && category.category_image.trim() !== '') { const img = document.createElement('img'); let imagePath = category.category_image; if (imagePath.startsWith('posimages/')) { imagePath = '../' + imagePath; } img.src = imagePath; img.alt = category.category_name; img.className = 'category-image'; tab.appendChild(img); } else { const iconSpan = document.createElement('span'); iconSpan.className = 'category-icon'; iconSpan.textContent = '🍽️'; tab.appendChild(iconSpan); } const nameSpan = document.createElement('span'); nameSpan.textContent = capitalizeFirstLetter(category.category_name); tab.appendChild(nameSpan); tab.dataset.categoryId = category.id; tab.onclick = () => { document.querySelectorAll('.category-tab').forEach(t => t.classList.remove('active')); tab.classList.add('active'); const filtered = allItems.filter(item => item.item_category == category.id && parseInt(item.cat_accomp_status) === 1 ); displayItems(filtered); }; categoryRow.appendChild(tab); }); categoryTabs.appendChild(categoryRow); } // Handle adding an accompaniment item while in accompaniment mode async function addAccompanimentToCart(item) { // Only allow items from accompaniment categories if (parseInt(item.cat_accomp_status) !== 1) { await customAlert('Please select an item from an accompaniment category.'); return; } // Check max accompaniment limit if (accompParentMaxAcc > 0) { const maxAllowed = accompParentQuantity * accompParentMaxAcc; if (accompSelectedCount >= maxAllowed) { await customAlert('Maximum accompaniments reached (' + maxAllowed + ' for ' + accompParentQuantity + ' x ' + accompParentItem.item_name + ').'); exitAccompanimentMode(); return; } } // Open the add-item modal in accompaniment mode openAccompanimentModal(item); } // Open modal for accompaniment item (price shown as 0) function openAccompanimentModal(item) { currentModalItem = { ...item, _isAccompaniment: true }; document.getElementById('modalItemName').textContent = item.item_name + ' (Accompaniment)'; document.getElementById('modalItemPrice').textContent = '0.00'; document.getElementById('modalQuantity').value = 1; document.getElementById('modalNotes').value = ''; // Populate notes applicable dropdown populateNotesApplicable(item); // Limit max quantity to remaining accompaniments const qtyInput = document.getElementById('modalQuantity'); if (accompParentMaxAcc > 0) { const remaining = (accompParentQuantity * accompParentMaxAcc) - accompSelectedCount; qtyInput.max = remaining; } else { qtyInput.removeAttribute('max'); } document.getElementById('modalTotal').textContent = '0.00'; document.getElementById('addItemModal').classList.add('active'); } // Show the accompaniment mode banner function showAccompBanner() { const banner = document.getElementById('accompBanner'); if (banner) { banner.style.display = 'flex'; document.getElementById('accompParentName').textContent = accompParentItem.item_name; updateAccompCounter(); } } // Hide the accompaniment mode banner function hideAccompBanner() { const banner = document.getElementById('accompBanner'); if (banner) { banner.style.display = 'none'; } } // Update the accompaniment counter display in the banner function updateAccompCounter() { const countEl = document.getElementById('accompCount'); const maxEl = document.getElementById('accompMax'); if (countEl) countEl.textContent = accompSelectedCount; if (maxEl) { maxEl.textContent = accompParentMaxAcc > 0 ? (accompParentQuantity * accompParentMaxAcc) : 'unlimited'; } } // ==================== END ACCOMPANIMENT FUNCTIONS ==================== // Toggle POS Selector collapse function togglePOSSelector() { const collapse = document.getElementById('posSelectorCollapse'); if (collapse.style.display === 'none' || collapse.style.display === '') { // Show the collapse const posListJson = document.getElementById('userPosList').value; const posList = JSON.parse(posListJson); const container = document.getElementById('posButtonsContainer'); container.innerHTML = ''; posList.forEach(pos => { const posButton = document.createElement('button'); posButton.className = 'pos-button'; if (pos.pos_no == currentPOS) { posButton.classList.add('active'); } posButton.textContent = pos.description; posButton.onclick = () => selectPOS(pos.pos_no, pos.description); container.appendChild(posButton); }); collapse.style.display = 'block'; } else { // Hide the collapse collapse.style.display = 'none'; } } function selectPOS(posId, posName) { // Supermarket mode: skip table-in-POS check, directly switch POS if (typeof IS_SUPERMARKET !== 'undefined' && IS_SUPERMARKET) { applyPOSSelection(posId, posName); return; } const tableNo = document.getElementById('tableNo').value; // Check if the current table exists in the selected POS fetch(`api/orders.php?action=check_table_in_pos&table_no=${encodeURIComponent(tableNo)}&pos_no=${encodeURIComponent(posId)}`) .then(response => response.json()) .then(async data => { if (data.success && data.table_exists_in_pos) { // Table exists in this POS, proceed with POS change applyPOSSelection(posId, posName); } else { // Table doesn't exist in this POS, go to tables page filtered to the selected POS window.location.href = 'tables.php?pos=' + encodeURIComponent(posId); } }) .catch(error => { console.error('Error checking table in POS:', error); // On error, allow the change but warn the user applyPOSSelection(posId, posName); }); } function applyPOSSelection(posId, posName) { // Exit accompaniment mode when switching POS if (accompMode) { exitAccompanimentMode(); } currentPOS = posId; document.getElementById('currentPosId').value = posId; // Update active state on the always-visible POS tab buttons const allTabButtons = document.querySelectorAll('.pos-tab-button'); allTabButtons.forEach(btn => { if (btn.dataset.posId == posId) { btn.classList.add('active'); } else { btn.classList.remove('active'); } }); // Also update old-style pos-button if present (for compatibility) const allButtons = document.querySelectorAll('.pos-button'); allButtons.forEach(btn => { if (btn.textContent === posName) { btn.classList.add('active'); } else { btn.classList.remove('active'); } }); // Collapse the old POS selector if open const collapse = document.getElementById('posSelectorCollapse'); if (collapse) { collapse.style.display = 'none'; } loadPOSData(posId); // Show warning if this POS is unclosed if (isPOSUnclosed(posId)) { showNotification('Warning: Yesterday\'s orders for this POS have not been closed. Adding new items is disabled. You can still settle existing orders.', 'warning'); } // Check if this POS has membership packages and show/hide membership button checkPOSMembershipAccess(posId); checkLoyaltyAccess(); } // Toggle categories expand/collapse function toggleCategoriesExpand(categoriesList) { const categoryTabs = document.getElementById('categoryTabs'); let collapse = document.getElementById('categoriesCollapse'); // Create collapse section if it doesn't exist if (!collapse) { collapse = document.createElement('div'); collapse.className = 'categories-collapse'; collapse.id = 'categoriesCollapse'; collapse.style.display = 'none'; categoryTabs.appendChild(collapse); } if (collapse.style.display === 'none' || collapse.style.display === '') { // Show all categories in a grid layout collapse.innerHTML = ''; // Add header with count const header = document.createElement('div'); header.style.cssText = 'display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;padding-bottom:8px;border-bottom:1px solid #e0e0e0;'; header.innerHTML = 'All Categories (' + categoriesList.length + ')' + ''; collapse.appendChild(header); const categoriesGrid = document.createElement('div'); categoriesGrid.className = 'categories-grid'; // Add all categories categoriesList.forEach(category => { const categoryBtn = document.createElement('button'); categoryBtn.className = 'category-button'; // Highlight if this is the currently active category if (currentCategory && currentCategory == category.id) { categoryBtn.classList.add('active'); } // Apply category color const catColor = categoryColorMap[category.id]; if (catColor) { if (categoryBtn.classList.contains('active')) { categoryBtn.style.background = catColor.active; categoryBtn.style.borderColor = catColor.active; categoryBtn.style.color = 'white'; } else { categoryBtn.style.background = catColor.bg; categoryBtn.style.borderColor = catColor.border; } } // Add category image or default icon if (category.category_image && category.category_image.trim() !== '') { const img = document.createElement('img'); // Fix image path - go up one level from v2 to pos directory let imagePath = category.category_image; if (imagePath.startsWith('posimages/')) { imagePath = '../' + imagePath; } img.src = imagePath; img.alt = category.category_name; img.className = 'category-image'; categoryBtn.appendChild(img); } else { // Use default icon if no image const iconSpan = document.createElement('span'); iconSpan.className = 'category-icon'; iconSpan.textContent = '🍽️'; categoryBtn.appendChild(iconSpan); } const nameSpan = document.createElement('span'); nameSpan.textContent = capitalizeFirstLetter(category.category_name); categoryBtn.appendChild(nameSpan); categoryBtn.onclick = () => { filterByCategory(category.id); // Update active state in main row too updateCategoryActiveState(category.id); // Collapse after selection collapse.style.display = 'none'; }; categoriesGrid.appendChild(categoryBtn); }); collapse.appendChild(categoriesGrid); collapse.style.display = 'block'; } else { // Hide the collapse collapse.style.display = 'none'; } } function updateCategoryActiveState(categoryId) { // Update active state in category tabs with colors document.querySelectorAll('.category-tab').forEach(tab => { const catId = tab.dataset.categoryId; const color = categoryColorMap[catId]; if (tab.dataset.categoryId == categoryId) { tab.classList.add('active'); if (color) { tab.style.background = color.active; tab.style.borderColor = color.active; tab.style.color = 'white'; } } else { tab.classList.remove('active'); if (color) { tab.style.background = color.bg; tab.style.borderColor = color.border; tab.style.color = '#333'; } else { tab.style.background = ''; tab.style.borderColor = ''; tab.style.color = ''; } } }); } // ============ Discount Functions ============ let currentDiscountItems = []; async function makeDiscount() { const tableNo = document.getElementById('tableNo').value; const posId = currentPOS; if (!posId) { await customAlert('Please select a POS first.'); return; } // Check if there are any items in the cart for the current POS that haven't been saved const unsavedItems = cart.filter(item => !item.isSaved && item.pos_id == posId); if (unsavedItems.length > 0) { await customAlert('Please save the order first before applying discount.'); return; } // Check if there's a saved order for the current POS const hasSavedItemsForCurrentPOS = cart.some(item => item.isSaved && item.pos_id == posId); if (!hasSavedItemsForCurrentPOS) { await customAlert('No saved order found for the current POS. Please save items first.'); return; } try { // Load discount types const response = await fetch(`api/get_discount_types.php?table_no=${tableNo}&pos_no=${posId}`); const discountTypes = await response.json(); if (discountTypes.success === false) { showNotification('Error loading discount types: ' + discountTypes.message, 'error'); return; } // Populate discount type dropdown const discountTypeSelect = document.getElementById('discountType'); discountTypeSelect.innerHTML = ''; discountTypes.forEach(type => { const option = document.createElement('option'); option.value = type.id; option.textContent = type.discount_name; option.dataset.percentage = type.percentage || 0; option.dataset.orderAmount = type.order_amount || 0; option.dataset.discountName = type.discount_name; discountTypeSelect.appendChild(option); }); // Reset form resetDiscountFields(); // Check if any discounts exist on items in cart const hasDiscount = cart.some(item => item.discount > 0); const removeDiscountBtn = document.getElementById('removeDiscountBtn'); if (removeDiscountBtn) { removeDiscountBtn.style.display = hasDiscount ? 'inline-block' : 'none'; } // Show discount modal document.getElementById('discountModal').style.display = 'flex'; // Add change listener to discount type discountTypeSelect.onchange = function() { const selectedOption = this.options[this.selectedIndex]; const discountName = selectedOption.dataset.discountName; const percentage = parseFloat(selectedOption.dataset.percentage); const orderAmount = parseFloat(selectedOption.dataset.orderAmount); if (discountName === 'Others') { // Enable custom discount document.getElementById('discountValue').readOnly = false; document.getElementById('discountInPercentage').disabled = false; document.getElementById('discountInAmount').disabled = false; document.getElementById('discountInAmount').checked = true; document.getElementById('discountValue').value = '0'; document.getElementById('itemDiscountSection').style.display = 'block'; document.getElementById('discountValueGroup').style.display = 'none'; // Hide initially for "Others" document.getElementById('discountValue').max = '100'; } else { // Predefined discount document.getElementById('itemDiscountSection').style.display = 'none'; document.getElementById('discountValue').readOnly = true; document.getElementById('discountInPercentage').disabled = true; document.getElementById('discountInAmount').disabled = true; document.getElementById('discountInPercentage').checked = true; document.getElementById('discountValueGroup').style.display = 'block'; // Show for predefined document.getElementById('discountValue').value = percentage.toFixed(2); } }; } catch (error) { console.error('Error loading discount types:', error); showNotification('Error loading discount types: ' + error.message, 'error'); } } function resetDiscountFields() { document.getElementById('discountType').value = ''; document.getElementById('discountValue').value = ''; document.getElementById('discountValue').readOnly = true; document.getElementById('discountInPercentage').disabled = true; document.getElementById('discountInAmount').disabled = true; document.getElementById('discountInPercentage').checked = false; document.getElementById('discountInAmount').checked = false; document.getElementById('discountReason').value = ''; document.getElementById('itemDiscountSection').style.display = 'none'; currentDiscountItems = []; } function closeDiscountModal() { document.getElementById('discountModal').style.display = 'none'; resetDiscountFields(); } async function setDiscount() { // Check permission to apply discounts if (!hasPermission('discount')) { await customAlert('You do not have permission to apply discounts.'); closeDiscountModal(); return; } const discountType = document.getElementById('discountType').value; const discountValue = parseFloat(document.getElementById('discountValue').value); const discountReason = document.getElementById('discountReason').value; const discountIn = document.querySelector('input[name="discountIn"]:checked'); const posId = currentPOS; const tableNo = document.getElementById('tableNo').value; const userId = document.getElementById('userId').value; // Validation if (!discountType) { await customAlert('Please select a discount type.'); return; } if (!discountValue || discountValue <= 0) { await customAlert('Please enter a valid discount value.'); return; } if (!discountIn) { await customAlert('Please select discount method (Percentage or Amount).'); return; } // Confirm discount const discountDisplay = (discountIn && discountIn.value === 'discountInPercentage') ? `${discountValue}%` : formatCurrency(discountValue); if (!(await customConfirm(`Are you sure you want to apply a discount of ${discountDisplay}?`))) { return; } try { const formData = new FormData(); formData.append('pos_no', posId); formData.append('table_no', tableNo); formData.append('discountType', discountType); formData.append('discountValue', discountValue); formData.append('discountReason', discountReason); formData.append('discountIn', discountIn.value); formData.append('issued_by', userId); if (currentDiscountItems.length > 0) { formData.append('discountItems', JSON.stringify(currentDiscountItems)); } const response = await fetch('api/set_discount.php', { method: 'POST', body: formData }); const responseText = await response.text(); console.log('Response:', responseText); let result; try { result = JSON.parse(responseText); } catch (e) { console.error('Invalid JSON response:', responseText); showNotification('Server error. Check console for details.', 'error'); return; } if (result.success) { showNotification('Discount applied successfully!', 'success'); closeDiscountModal(); // Reload order to reflect discount await loadExistingOrder(); } else { showNotification('Error applying discount: ' + result.message, 'error'); } } catch (error) { console.error('Error applying discount:', error); showNotification('Error applying discount: ' + error.message, 'error'); } } // Remove discount from order async function removeDiscount() { const tableNo = document.getElementById('tableNo').value; const posId = currentPOS; if (!(await customConfirm('Are you sure you want to remove all discounts from this table?'))) { return; } try { const response = await fetch('api/remove_discount.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ table_no: tableNo, pos_no: posId }) }); const result = await response.json(); if (result.success) { showNotification('Discount removed successfully!', 'success'); closeDiscountModal(); // Reload order to reflect changes await loadExistingOrder(); } else { showNotification('Error removing discount: ' + result.message, 'error'); } } catch (error) { console.error('Error removing discount:', error); showNotification('Error removing discount: ' + error.message, 'error'); } } async function openItemDiscount() { const posId = currentPOS; const tableNo = document.getElementById('tableNo').value; try { const response = await fetch(`api/set_discount.php?get_items=1&pos_no=${posId}&table_no=${tableNo}`); const items = await response.json(); if (!items || items.length === 0) { await customAlert('No items found in the order.'); return; } // Populate item discount table const tbody = document.getElementById('itemDiscountTableBody'); tbody.innerHTML = ''; items.forEach(item => { const row = document.createElement('tr'); // Calculate total amount: price * quantity const totalAmount = (parseFloat(item.set_price) || 0) * (parseFloat(item.quantity) || 0); const itemName = item.description || item.item_description || item.item_name || 'Item'; row.innerHTML = ` ${itemName} ${formatCurrency(totalAmount)} `; tbody.appendChild(row); }); // Show item discount modal document.getElementById('itemDiscountModal').style.display = 'flex'; } catch (error) { console.error('Error loading order items:', error); showNotification('Error loading order items: ' + error.message, 'error'); } } function closeItemDiscountModal() { document.getElementById('itemDiscountModal').style.display = 'none'; } async function confirmItemDiscounts() { currentDiscountItems = []; // Collect checked items with discount values document.querySelectorAll('.item-discount-check:checked').forEach(checkbox => { const itemId = checkbox.dataset.id; const discountInput = document.querySelector(`.item-discount-value[data-id="${itemId}"]`); const discountValue = parseFloat(discountInput.value) || 0; currentDiscountItems.push({ id: itemId, item_discount: discountValue }); }); // Calculate total discount const totalDiscount = currentDiscountItems.reduce((sum, item) => sum + item.item_discount, 0); document.getElementById('discountValue').value = totalDiscount.toFixed(2); closeItemDiscountModal(); await customAlert(`Item discounts configured. Total: ${formatCurrency(totalDiscount)}`); } // Add event listeners for discount method radio buttons document.addEventListener('DOMContentLoaded', function() { const percentageRadio = document.getElementById('discountInPercentage'); const amountRadio = document.getElementById('discountInAmount'); const discountValueInput = document.getElementById('discountValue'); const discountValueGroup = document.getElementById('discountValueGroup'); if (percentageRadio) { percentageRadio.addEventListener('change', function() { if (this.checked) { discountValueInput.max = '100'; discountValueGroup.style.display = 'block'; // Show percentage field document.getElementById('itemDiscountSection').style.display = 'none'; discountValueInput.value = '0'; discountValueInput.readOnly = false; // Allow input for percentage } }); } if (amountRadio) { amountRadio.addEventListener('change', function() { if (this.checked) { discountValueInput.max = ''; discountValueGroup.style.display = 'none'; // Hide percentage field const discountType = document.getElementById('discountType').value; const selectedOption = document.querySelector(`#discountType option[value="${discountType}"]`); if (selectedOption && selectedOption.dataset.discountName === 'Others') { document.getElementById('itemDiscountSection').style.display = 'block'; } } }); } }); // Print Bill function let isPrintingBill = false; let billPopupWindow = null; async function printBill() { // If a bill popup is already open, close and reopen to bring it to front // (window.focus() does not work in phpdesktop-chromium) if (billPopupWindow && !billPopupWindow.closed) { billPopupWindow.close(); billPopupWindow = null; } // Prevent duplicate clicks while bill is being processed if (isPrintingBill) { console.log('Bill print already in progress, ignoring duplicate click'); return; } isPrintingBill = true; try { await _printBillInner(); } finally { isPrintingBill = false; } } async function _printBillInner() { // Check permission to print bill if (!hasPermission('print_bill')) { await customAlert('You do not have permission to Print Bill.'); return; } const tableNo = document.getElementById('tableNo').value; const defaultPosNo = currentPOS || document.getElementById('currentPosId')?.value; if (!tableNo) { await customAlert('No table selected.'); return; } // Check multiple_bill_print permission // If user doesn't have this permission, check if any item has been printed on a bill if (!hasPermission('multiple_bill_print')) { try { const checkFormData = new FormData(); checkFormData.append('table_no', tableNo); const checkResponse = await fetch('../getKot.php?checkPrintedItemsOnBill', { method: 'POST', body: checkFormData }); const checkResult = await checkResponse.json(); // If success is true, it means items have already been printed on a bill if (checkResult.success) { await customAlert('You do not have permission to print a bill more than once. Some items on this table have already been printed on a bill.'); return; } } catch (error) { console.error('Error checking bill print status:', error); // Continue if the check fails - don't block printing } } // Collect all unique POS/order combinations from cart items // Group orders by POS: { pos_no: [order_no1, order_no2, ...] } const posOrderMap = {}; let hasAnyOrder = false; for (const item of cart) { if (item.order_no && item.isSaved) { const itemPosNo = item.pos_id || defaultPosNo; if (!posOrderMap[itemPosNo]) { posOrderMap[itemPosNo] = new Set(); } posOrderMap[itemPosNo].add(item.order_no); hasAnyOrder = true; } } if (!hasAnyOrder) { await customAlert('No order found. Please save items first.'); return; } // Get first order_no and pos_no for legacy API calls const firstPosNo = Object.keys(posOrderMap)[0]; const firstOrderNo = [...posOrderMap[firstPosNo]][0]; // Step 1: Check bill criteria (all items have KOTs) try { // Build rows data similar to the original const rows = cart.filter(item => item.order_no && item.isSaved).map(item => ({ order_no: item.order_no, pos_no: item.pos_id || defaultPosNo })); const formData = new FormData(); formData.append('rows', JSON.stringify(rows)); const checkResponse = await fetch('../getKot.php?checkBillCriteria', { method: 'POST', body: formData }); const checkResult = await checkResponse.text(); const canPrint = parseInt(checkResult) === 1; if (!canPrint) { showNotification('Cannot print bill since some items on the order don\'t have KOT(s)', 'warning'); return; } // Step 2: Check accompaniments const accResponse = await fetch(`../getKot.php?hasExtraAccomompanments&table_no=${tableNo}`); const accResult = await accResponse.json(); if (!accResult.success) { // Check if zero priced items are allowed const settingsResponse = await fetch('../getKot.php?getZeroPricedSetting'); let allowZeroPriced = false; try { const settingsResult = await settingsResponse.json(); allowZeroPriced = settingsResult.zero_priced === 'Yes'; } catch (e) { // If endpoint doesn't exist, proceed anyway allowZeroPriced = true; } if (!allowZeroPriced) { showNotification('Warning: Accompaniments and main items do not match', 'warning'); return; } } // Step 3: Get correct bill amount and print const billFormData = new FormData(); billFormData.append('bill_no', firstOrderNo); billFormData.append('pos_no', firstPosNo); billFormData.append('tableNo', tableNo); const billResponse = await fetch('../CorrectAmountBill.php', { method: 'POST', body: billFormData }); const billText = await billResponse.text(); let billData; try { billData = JSON.parse(billText); } catch (e) { showNotification('Error: Cannot print bill, problem detected.', 'warning'); return; } if (billData) { const amount = Number(billData.amount); if (amount > 0) { // Build URL with all POS/order combinations // Format: print/bill.php?pos1=order1,order2&pos2=order3&table_no=X const urlParams = []; for (const [posNo, orderSet] of Object.entries(posOrderMap)) { const orders = [...orderSet].join(','); urlParams.push(`${posNo}=${orders}`); } urlParams.push(`table_no=${tableNo}`); // Check global AUTO_PRINT_SETTING - if Yes, add auto_print parameter const isAutoMode = (typeof AUTO_PRINT_SETTING !== 'undefined' && AUTO_PRINT_SETTING === 'Yes'); if (isAutoMode) { urlParams.push('auto_print=auto_print'); } // Add deposit data if a deposit is selected const depositData = typeof getSelectedDeposit === 'function' ? getSelectedDeposit() : null; if (depositData) { urlParams.push(`deposit_id=${depositData.id}`); urlParams.push(`deposit_amount=${depositData.deposit}`); urlParams.push(`deposit_client=${encodeURIComponent(depositData.client_name)}`); } // Add redeemable data if a redeemable receipt is selected const redeemableData = typeof getSelectedRedeemable === 'function' ? getSelectedRedeemable() : null; if (redeemableData) { urlParams.push(`redeemable_receipt=${encodeURIComponent(redeemableData.receipt_no)}`); urlParams.push(`redeemable_balance=${redeemableData.balance}`); } const billUrl = `print/bill.php?${urlParams.join('&')}`; // Use a named window so duplicate clicks reuse the same popup const billWindowName = 'bill_' + tableNo + '_' + firstPosNo; billPopupWindow = window.open(billUrl, billWindowName, 'width=400,height=900,scrollbar=no,location=no,resizable=no,dialog=yes,alwaysontop=yes,maximize=no,left=0,top=0'); if (billPopupWindow) billPopupWindow.focus(); } else { showNotification('Cannot print bill with zero amount', 'warning'); } } else { showNotification('Error: Cannot print bill, problem detected.', 'warning'); } } catch (error) { console.error('Error printing bill:', error); showNotification('Error printing bill. Please try again.', 'error'); } } // Options Dialog functions function showOptionsDialog() { // Apply permission restrictions to options buttons before showing applyOptionsPermissions(); document.getElementById('optionsModal').style.display = 'flex'; } function closeOptionsDialog() { document.getElementById('optionsModal').style.display = 'none'; } // Options menu item functions (placeholders) async function showOrderList() { closeOptionsDialog(); document.getElementById('orderListModal').style.display = 'flex'; refreshGuestAppOrderCount(); await loadOrderList(); } function closeOrderListModal() { document.getElementById('orderListModal').style.display = 'none'; // Reset to current orders view currentOrderListView = 'current'; } let currentOrderListView = 'current'; function switchOrderListView(view) { currentOrderListView = view; const btnCurrent = document.getElementById('btnCurrentOrders'); const btnOnline = document.getElementById('btnOnlineOrders'); if (btnCurrent) btnCurrent.classList.remove('active', 'online'); if (btnOnline) btnOnline.classList.remove('active', 'online'); // Guest App view is hidden in retail mode — fall back to current orders. if (view === 'online' && btnOnline) { btnOnline.classList.add('active', 'online'); loadOnlineOrderList(); } else { if (btnCurrent) btnCurrent.classList.add('active'); loadOrderList(); } } function refreshCurrentOrderListView() { if (currentOrderListView === 'online') { loadOnlineOrderList(); } else { loadOrderList(); } } async function loadOnlineOrderList() { const tbody = document.getElementById('orderListTableBody'); tbody.innerHTML = 'Loading guest app orders...'; try { const userId = document.getElementById('userId').value; const response = await fetch(`api/get_online_order_list.php?user_id=${userId}`); const data = await response.json(); if (!data.success) { tbody.innerHTML = `${data.message}`; updateGuestAppOrderCount(0); return; } // Update counter badge const orderCount = data.orders ? data.orders.length : 0; updateGuestAppOrderCount(orderCount); if (!data.orders || data.orders.length === 0) { tbody.innerHTML = 'No guest app orders found'; return; } tbody.innerHTML = ''; data.orders.forEach(order => { const row = document.createElement('tr'); row.classList.add('order-online-new'); const description = order.first_item_description || '-'; const truncatedDesc = description.length > 30 ? description.substring(0, 30) + '...' : description; const orderNo = order.order_no || '-'; const waiterName = order.waiter_name || '-'; const amount = formatCurrency(order.order_amount); const datetime = order.order_datetime ? formatOrderDateTime(order.order_datetime) : '-'; // Build table display - show room number with "Assign Table" hint let tableDisplay = order.table_no || '-'; if (!order.table_no || order.table_no === '-' || order.table_no.startsWith('RM:')) { tableDisplay = `${order.table_no || '-'}
Assign Table`; } // Build waiter display - show "Assign Waiter" hint let waiterDisplay = waiterName; if (!order.waiter_name || order.waiter_name === '' || waiterName === '-') { waiterDisplay = `Assign Waiter`; } // Build action buttons - Process (disabled), Edit, Void const canVoid = hasPermission('remove_items'); const voidButtonHtml = canVoid ? `` : ''; const escapedRoomNo = (order.room_no || '').replace(/'/g, "\\'"); const actionHtml = ` ${voidButtonHtml} `; row.innerHTML = ` ${order.pos_name || order.pos_no} ${orderNo} ${tableDisplay} ${waiterDisplay} ${truncatedDesc} ${amount} ${datetime} ${actionHtml} `; tbody.appendChild(row); }); setupOrderListSearch(); } catch (error) { console.error('Error loading online order list:', error); tbody.innerHTML = 'Error loading guest app orders'; } } function updateGuestAppOrderCount(count) { const badge = document.getElementById('guestAppOrderCount'); if (badge) { if (count > 0) { badge.textContent = count; badge.style.display = 'inline'; } else { badge.style.display = 'none'; } } } async function refreshGuestAppOrderCount() { try { const userId = document.getElementById('userId').value; const response = await fetch(`api/get_online_order_list.php?user_id=${userId}`); const data = await response.json(); const count = (data.success && data.orders) ? data.orders.length : 0; updateGuestAppOrderCount(count); } catch (e) { // Silently fail } } async function processOnlineOrder(tableNo, posNo, waiterId) { // Check if waiter or table is not assigned if (!waiterId || waiterId === 0 || !tableNo || tableNo === '-' || tableNo.startsWith('RM:') || tableNo === 'General') { await customConfirm('This guest app order does not have a waiter or table assigned yet.\n\nPlease click the Edit button to assign a waiter and table first.'); return; } // If waiter and table are assigned, process normally processOrder(tableNo, posNo); } // Track if current edit is for a new online order let editingOnlineOrder = null; async function editOnlineOrder(cloudOrderId, posNo, roomNo) { editingOnlineOrder = { cloudOrderId, posNo, roomNo }; // Reuse the edit order dialog document.getElementById('editOrderId').value = ''; document.getElementById('editOrderNo').value = 'New Guest App Order'; document.getElementById('editOrderAmount').value = ''; // Load tables for the specific POS only await loadTablesForEdit(posNo, ''); // Enable table dropdown and add onchange handler for filtered waiters const tableSelect = document.getElementById('editTableNo'); if (tableSelect) { tableSelect.disabled = false; tableSelect.title = ''; tableSelect.style.opacity = ''; tableSelect.style.cursor = ''; tableSelect.onchange = onEditTableChanged; } // Disable waiter dropdown until a table is selected const waiterSelect = document.getElementById('editWaiter'); if (waiterSelect) { waiterSelect.innerHTML = ''; waiterSelect.disabled = true; waiterSelect.style.opacity = '0.6'; waiterSelect.style.cursor = 'not-allowed'; } document.getElementById('editOrderModal').style.display = 'flex'; } // Waiter ID to pre-select after loading filtered waiters (used when editing existing orders) let editPreselectWaiterId = null; async function onEditTableChanged() { const tableSelect = document.getElementById('editTableNo'); const waiterSelect = document.getElementById('editWaiter'); const selectedTable = tableSelect.value; if (!selectedTable) { // No table selected - disable waiter dropdown waiterSelect.innerHTML = ''; waiterSelect.disabled = true; waiterSelect.style.opacity = '0.6'; waiterSelect.style.cursor = 'not-allowed'; return; } // Show loading state on waiter dropdown waiterSelect.innerHTML = ''; waiterSelect.disabled = true; try { const response = await fetch(`api/get_waiters_for_table.php?table_no=${encodeURIComponent(selectedTable)}`); const data = await response.json(); waiterSelect.innerHTML = ''; if (data.success && data.waiters && data.waiters.length > 0) { data.waiters.forEach(waiter => { const option = document.createElement('option'); option.value = waiter.id; option.textContent = waiter.personnel_name; // Pre-select the current waiter if editing an existing order if (editPreselectWaiterId && waiter.id == editPreselectWaiterId) { option.selected = true; } waiterSelect.appendChild(option); }); waiterSelect.disabled = false; waiterSelect.style.opacity = ''; waiterSelect.style.cursor = ''; // Clear preselect after use editPreselectWaiterId = null; } else { waiterSelect.innerHTML = ''; waiterSelect.disabled = true; waiterSelect.style.opacity = '0.6'; waiterSelect.style.cursor = 'not-allowed'; editPreselectWaiterId = null; } } catch (error) { console.error('Error loading waiters for table:', error); waiterSelect.innerHTML = ''; waiterSelect.disabled = true; waiterSelect.style.opacity = '0.6'; waiterSelect.style.cursor = 'not-allowed'; editPreselectWaiterId = null; } } async function voidOnlineOrder(cloudOrderId, posNo) { if (!hasPermission('remove_items')) { await customAlert('You do not have permission to void orders.'); return; } if (!(await customConfirm('Are you sure you want to void this guest app order? This action cannot be undone.'))) { return; } try { const response = await fetch('api/void_online_order.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ cloud_order_id: cloudOrderId, pos_no: posNo }) }); const result = await response.json(); if (result.success) { showNotification('Guest app order voided successfully', 'success'); loadOnlineOrderList(); } else { showNotification('Error voiding order: ' + result.message, 'error'); } } catch (error) { console.error('Error voiding online order:', error); showNotification('Error voiding guest app order: ' + error.message, 'error'); } } function openOnlineOrdersHistory() { document.getElementById('onlineHistoryModal').style.display = 'flex'; loadOnlineOrdersHistory(); } function closeOnlineHistoryModal() { document.getElementById('onlineHistoryModal').style.display = 'none'; } async function loadOnlineOrdersHistory() { const tbody = document.getElementById('onlineHistoryTableBody'); tbody.innerHTML = 'Loading...'; try { const userId = document.getElementById('userId').value; const response = await fetch(`api/get_online_orders_history.php?user_id=${userId}`); const data = await response.json(); if (!data.success) { tbody.innerHTML = `${data.message}`; return; } if (!data.orders || data.orders.length === 0) { tbody.innerHTML = 'No guest app orders found for today'; return; } tbody.innerHTML = ''; data.orders.forEach(order => { const row = document.createElement('tr'); const items = order.items || '-'; const truncatedItems = items.length > 35 ? items.substring(0, 35) + '...' : items; const amount = formatCurrency(order.order_amount); const datetime = order.order_date ? formatOrderDateTime(order.order_date) : '-'; // Status badge styling let statusClass = ''; switch (order.status) { case 'Settled': statusClass = 'background: #27ae60; color: #fff;'; break; case 'Pending': statusClass = 'background: #f39c12; color: #fff;'; break; case 'New': statusClass = 'background: #e67e22; color: #fff;'; break; case 'Voided': statusClass = 'background: #e74c3c; color: #fff;'; break; default: statusClass = 'background: #95a5a6; color: #fff;'; } row.innerHTML = ` ${order.pos_name || order.pos_no} RM:${order.room_no || '-'} ${order.order_no || '-'} ${order.table_no || '-'} ${order.waiter_name || '-'} ${truncatedItems} ${amount} ${datetime} ${order.status} `; tbody.appendChild(row); }); } catch (error) { console.error('Error loading online orders history:', error); tbody.innerHTML = 'Error loading history'; } } function filterOnlineHistory() { const searchVal = document.getElementById('onlineHistorySearch').value.toLowerCase(); const tbody = document.getElementById('onlineHistoryTableBody'); const rows = tbody.querySelectorAll('tr'); rows.forEach(row => { const text = row.textContent.toLowerCase(); row.style.display = text.includes(searchVal) ? '' : 'none'; }); } async function loadOrderList() { const tbody = document.getElementById('orderListTableBody'); tbody.innerHTML = 'Loading orders...'; try { const posId = currentPOS; const userId = document.getElementById('userId').value; const response = await fetch(`api/get_order_list.php?pos_no=${posId}&user_id=${userId}`); const data = await response.json(); if (!data.success) { tbody.innerHTML = `${data.message}`; return; } if (!data.orders || data.orders.length === 0) { tbody.innerHTML = 'No pending orders found'; return; } // Render orders tbody.innerHTML = ''; data.orders.forEach(order => { const row = document.createElement('tr'); // Calculate order age for color coding const orderDate = new Date(order.order_datetime); const now = new Date(); const hoursOld = Math.abs(now - orderDate) / 36e5; if (hoursOld >= 8) { row.classList.add('order-very-old'); } else if (hoursOld >= 1) { row.classList.add('order-old'); } // Truncate description if too long const description = order.first_item_description || '-'; const truncatedDesc = description.length > 30 ? description.substring(0, 30) + '...' : description; // Check if user has remove_items permission for Void button const canVoid = hasPermission('remove_items'); const voidButtonHtml = canVoid ? `` : ''; row.innerHTML = ` ${order.pos_name || order.pos_no} ${order.order_no} ${order.table_no} ${order.waiter_name || '-'} ${truncatedDesc} ${formatCurrency(order.order_amount)} ${formatOrderDateTime(order.order_datetime)} ${voidButtonHtml} `; tbody.appendChild(row); }); // Add search functionality setupOrderListSearch(); } catch (error) { console.error('Error loading order list:', error); tbody.innerHTML = 'Error loading orders'; } } function formatOrderTime(datetime) { const date = new Date(datetime); const now = new Date(); const diffMs = now - date; const diffMins = Math.floor(diffMs / 60000); const diffHours = Math.floor(diffMins / 60); if (diffMins < 60) { return `${diffMins}m ago`; } else if (diffHours < 24) { return `${diffHours}h ago`; } else { return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}); } } function formatOrderDateTime(datetime) { const date = new Date(datetime); const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); const hours = String(date.getHours()).padStart(2, '0'); const minutes = String(date.getMinutes()).padStart(2, '0'); return `${year}-${month}-${day} ${hours}:${minutes}`; } async function processOrder(tableNo, posNo) { try { // Get the table ID based on table number and POS const response = await fetch(`api/get_table_id.php?table_no=${tableNo}&pos_no=${posNo}`); const result = await response.json(); if (result.success && result.table_id) { // Close the order list modal closeOrderListModal(); // Reload the page with the new table window.location.href = `selling.php?table=${result.table_id}`; } else { showNotification('Error loading table: ' + (result.message || 'Table not found'), 'error'); } } catch (error) { console.error('Error processing order:', error); showNotification('Error loading table', 'error'); } } function setupOrderListSearch() { const searchInput = document.getElementById('orderListSearch'); searchInput.addEventListener('input', function() { const searchTerm = this.value.toLowerCase(); const rows = document.querySelectorAll('#orderListTableBody tr'); rows.forEach(row => { const text = row.textContent.toLowerCase(); row.style.display = text.includes(searchTerm) ? '' : 'none'; }); }); } async function viewOrder(tableNo, posNo, orderId, orderNo, amount, waiterId, waiterName) { // Open edit dialog document.getElementById('editOrderId').value = orderId; document.getElementById('editOrderNo').value = orderNo; document.getElementById('editOrderAmount').value = parseFloat(amount).toFixed(2); // Load tables for this order's POS await loadTablesForEdit(posNo, tableNo); const tableSelect = document.getElementById('editTableNo'); const waiterSelect = document.getElementById('editWaiter'); // Apply permission restrictions to Table Number dropdown if (tableSelect) { if (!hasPermission('transfer_order_to_table')) { tableSelect.disabled = true; tableSelect.title = 'You do not have permission to transfer orders to another table'; tableSelect.style.opacity = '0.6'; tableSelect.style.cursor = 'not-allowed'; } else { tableSelect.disabled = false; tableSelect.title = ''; tableSelect.style.opacity = ''; tableSelect.style.cursor = ''; } // Attach table change handler to filter waiters tableSelect.onchange = onEditTableChanged; } // Set the waiter to pre-select, then load filtered waiters for the current table editPreselectWaiterId = waiterId; if (tableSelect && tableSelect.value) { // Table is already selected - load filtered waiters immediately await onEditTableChanged(); } else { // No table selected yet - disable waiter dropdown if (waiterSelect) { waiterSelect.innerHTML = ''; waiterSelect.disabled = true; waiterSelect.style.opacity = '0.6'; waiterSelect.style.cursor = 'not-allowed'; } } // Apply permission restrictions to Waiter dropdown (after waiters are loaded) if (waiterSelect && !waiterSelect.disabled) { if (!hasPermission('transfer_waiter')) { waiterSelect.disabled = true; waiterSelect.title = 'You do not have permission to transfer orders to another waiter'; waiterSelect.style.opacity = '0.6'; waiterSelect.style.cursor = 'not-allowed'; } } // Show edit modal document.getElementById('editOrderModal').style.display = 'flex'; } function closeEditOrderModal() { document.getElementById('editOrderModal').style.display = 'none'; editingOnlineOrder = null; editPreselectWaiterId = null; // Reset table onchange handler const tableSelect = document.getElementById('editTableNo'); if (tableSelect) { tableSelect.onchange = null; } } async function loadTablesForEdit(posNo, currentTableNo) { try { // Always filter tables by POS const url = posNo ? `api/get_tables.php?pos_no=${posNo}` : `api/get_tables.php?all_tables=1`; const response = await fetch(url); const data = await response.json(); const select = document.getElementById('editTableNo'); select.innerHTML = ''; if (data.success && data.tables) { data.tables.forEach(table => { const option = document.createElement('option'); option.value = table.table_no; // Highlight occupied tables const occupiedIndicator = table.is_occupied == 1 ? ' 🔴' : ''; option.textContent = table.table_no + occupiedIndicator; if (table.is_occupied == 1) { option.style.color = '#d9534f'; option.style.fontWeight = 'bold'; } if (table.table_no === currentTableNo) { option.selected = true; } select.appendChild(option); }); } else { console.error('Tables API error:', data.message || 'Unknown error'); } } catch (error) { console.error('Error loading tables:', error); } } async function loadWaitersForEdit(currentWaiterId) { try { const response = await fetch('api/get_waiters.php'); const data = await response.json(); console.log('Waiters API response:', data); const select = document.getElementById('editWaiter'); select.innerHTML = ''; if (data.success && data.waiters) { data.waiters.forEach(waiter => { const option = document.createElement('option'); option.value = waiter.id; option.textContent = waiter.personnel_name; if (waiter.id == currentWaiterId) { option.selected = true; } select.appendChild(option); }); } else { console.error('Waiters API error:', data.message || 'Unknown error'); } } catch (error) { console.error('Error loading waiters:', error); } } async function saveOrderEdit() { const orderId = document.getElementById('editOrderId').value; const tableNo = document.getElementById('editTableNo').value; const waiterId = document.getElementById('editWaiter').value; if (!tableNo) { await customAlert('Please select a table'); return; } if (!waiterId) { await customAlert('Please select a waiter'); return; } try { // Check if this is a new online order assignment if (editingOnlineOrder) { const response = await fetch('api/assign_online_order.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ cloud_order_id: editingOnlineOrder.cloudOrderId, pos_no: editingOnlineOrder.posNo, table_no: tableNo, waiter_id: parseInt(waiterId) }) }); const result = await response.json(); editingOnlineOrder = null; if (result.success) { closeEditOrderModal(); showNotification('Guest app order assigned successfully. It now appears under Current Orders.', 'success'); // Switch to Current Orders view and update the guest app count refreshGuestAppOrderCount(); switchOrderListView('current'); } else { showNotification('Error assigning order: ' + result.message, 'error'); } return; } const response = await fetch('api/update_order_details.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ order_id: orderId, table_no: tableNo, waiter_id: waiterId }) }); const result = await response.json(); if (result.success) { showNotification('Order updated successfully', 'success'); closeEditOrderModal(); await loadOrderList(); // Reload the order list } else { showNotification('Error updating order: ' + result.message, 'error'); } } catch (error) { console.error('Error updating order:', error); showNotification('Error updating order: ' + error.message, 'error'); } } async function voidOrder(orderId) { // Check remove_items permission if (!hasPermission('remove_items')) { await customAlert('You do not have permission to void orders.'); return; } // Prompt for void reason using custom dialog const voidReason = await customPrompt('Please enter the reason for voiding this order:', 'Enter cancellation reason...'); // If user cancels the prompt or enters empty reason, abort if (voidReason === null) { return; // User cancelled } if (!voidReason.trim()) { await customAlert('A reason is required to void an order.'); return; } if (!(await customConfirm('Are you sure you want to void this order? This action cannot be undone.'))) { return; } try { const response = await fetch('api/void_order.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ order_id: orderId, void_reason: voidReason.trim() }) }); const result = await response.json(); if (result.success) { showNotification('Order voided successfully', 'success'); await loadOrderList(); // Reload the order list } else { await customAlert('Error voiding order: ' + result.message); } } catch (error) { console.error('Error voiding order:', error); await customAlert('Error voiding order: ' + error.message); } } function showDelivery() { closeOptionsDialog(); // Ensure "Assign Order" button is shown (not "Select Client") when opening from Options document.getElementById('deliveryAssignBtn').style.display = 'inline-block'; document.getElementById('deliverySelectClientBtn').style.display = 'none'; deliveryModeFromHeader = false; // Clear flag since opening from Options document.getElementById('deliveryModal').style.display = 'flex'; loadDeliveryClients(); } async function showRoomService() { closeOptionsDialog(); if (cart.length === 0) { await customAlert('Please add items to the cart first before adding room service.'); return; } // Check if an order exists (must be saved first) const existingOrderId = document.getElementById('existingOrderId').value; if (!existingOrderId) { await customAlert('Please save the order first before adding room service.'); return; } // Confirm with user if (!(await customConfirm('Are you sure you want to add Room Service to this order?'))) { return; } try { // Get room charge configuration const response = await fetch('api/get_room_charge.php'); const data = await response.json(); if (data.error) { showNotification('Error loading room charge: ' + data.error, 'error'); return; } // Calculate the current bill amount (subtotal before room service) const billAmount = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0); let chargeAmount = 0; // Check charge type and calculate accordingly if (data.charge_type === 'Percentage') { // Ensure percentage doesn't exceed 100 let percentage = parseFloat(data.default_rate); percentage = percentage > 100 ? 100 : percentage; chargeAmount = (percentage / 100) * billAmount; } else { // Fixed amount chargeAmount = parseFloat(data.default_rate); } // Get necessary data for saving const tableId = document.getElementById('tableId').value; const userId = document.getElementById('userId').value; // Create room service item const roomServiceItem = { id: 0, // Use item_no 0 for room service name: 'Room Service', description: 'Room Service', price: chargeAmount, quantity: 1, notes: '', discount: 0, pos_id: currentPOS }; // Save room service item to database immediately const orderData = { action: 'save_order', table_id: tableId, user_id: userId, items: [roomServiceItem] }; const saveResponse = await fetch('api/orders.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(orderData) }); const saveResult = await saveResponse.json(); if (!saveResult.success) { showNotification('Error saving room service: ' + (saveResult.message || 'Unknown error'), 'error'); return; } // Add room service to cart as a saved item const cartItem = { id: 'room_service_' + Date.now(), item_no: 0, name: 'Room Service', description: 'Room Service', price: chargeAmount, quantity: 1, notes: '', discount: 0, pos_id: currentPOS, isSaved: true }; cart.push(cartItem); updateCartDisplay(); showNotification('Room Service charge of ' + formatAmount(chargeAmount) + ' has been added and saved to the order.', 'success'); } catch (error) { console.error('Error adding room service:', error); showNotification('Error adding room service: ' + error.message, 'error'); } } // Store POS orders data for extra charge calculation let extraChargePOSOrders = []; async function showExtraCharge() { closeOptionsDialog(); // Check if cart has items if (cart.length === 0) { await customAlert('Please add items to the cart first before adding extra charge.'); return; } // Check if an order exists (must be saved first) const existingOrderId = document.getElementById('existingOrderId').value; if (!existingOrderId) { await customAlert('Please save the order first before adding extra charge.'); return; } // Reset form document.getElementById('extraChargePOS').value = ''; document.querySelectorAll('input[name="extra_charge_type"]').forEach(radio => { radio.checked = false; }); document.getElementById('extraChargePercentageGroup').style.display = 'none'; document.getElementById('extraChargeAmountGroup').style.display = 'none'; document.getElementById('extraChargePercentage').value = ''; document.getElementById('extraChargeAmount').value = ''; document.getElementById('extraChargeDescription').value = ''; // Load POS with orders on this table await loadExtraChargePOSOptions(); // Show modal document.getElementById('extraChargeModal').style.display = 'flex'; } async function loadExtraChargePOSOptions() { const tableNo = document.getElementById('tableNo').value; const posSelect = document.getElementById('extraChargePOS'); // Reset dropdown posSelect.innerHTML = ''; extraChargePOSOrders = []; try { const response = await fetch(`api/orders.php?action=get_table_pos_orders&table_no=${tableNo}`); const result = await response.json(); if (result.success && result.pos_orders && result.pos_orders.length > 0) { extraChargePOSOrders = result.pos_orders; result.pos_orders.forEach(posOrder => { const option = document.createElement('option'); option.value = posOrder.pos_no; option.textContent = `${posOrder.pos_desc} (Order: ${formatCurrency(posOrder.order_amount)})`; option.dataset.resOrderId = posOrder.res_order_id; option.dataset.orderNo = posOrder.order_no; option.dataset.orderAmount = posOrder.order_amount; posSelect.appendChild(option); }); } else { await customAlert('No orders found on this table. Please save an order first.'); closeExtraChargeModal(); } } catch (error) { console.error('Error loading POS options:', error); showNotification('Error loading POS options: ' + error.message, 'error'); } } function onExtraChargePOSChange() { // Reset the percentage and amount fields when POS changes document.getElementById('extraChargePercentage').value = ''; document.getElementById('extraChargeAmount').value = ''; } function closeExtraChargeModal() { document.getElementById('extraChargeModal').style.display = 'none'; extraChargePOSOrders = []; } function updateExtraChargeType() { const selectedType = document.querySelector('input[name="extra_charge_type"]:checked'); if (!selectedType) return; const percentageGroup = document.getElementById('extraChargePercentageGroup'); const amountGroup = document.getElementById('extraChargeAmountGroup'); if (selectedType.value === 'percentage') { percentageGroup.style.display = 'block'; amountGroup.style.display = 'block'; document.getElementById('extraChargeAmount').readOnly = true; document.getElementById('extraChargeAmount').value = ''; } else if (selectedType.value === 'amount') { percentageGroup.style.display = 'none'; amountGroup.style.display = 'block'; document.getElementById('extraChargeAmount').readOnly = false; document.getElementById('extraChargeAmount').value = ''; } } function calculateExtraChargeAmount() { const percentage = parseFloat(document.getElementById('extraChargePercentage').value) || 0; if (percentage <= 0) { document.getElementById('extraChargeAmount').value = ''; return; } // Get the selected POS order amount const posSelect = document.getElementById('extraChargePOS'); const selectedOption = posSelect.options[posSelect.selectedIndex]; if (!selectedOption || !selectedOption.dataset.orderAmount) { document.getElementById('extraChargeAmount').value = ''; return; } const billAmount = parseFloat(selectedOption.dataset.orderAmount) || 0; // Calculate percentage amount const chargeAmount = (percentage / 100) * billAmount; document.getElementById('extraChargeAmount').value = chargeAmount.toFixed(2); } async function saveExtraCharge() { // Validate POS selection const posSelect = document.getElementById('extraChargePOS'); const selectedPOS = posSelect.value; if (!selectedPOS) { await customAlert('Please select a Point of Sale.'); return; } const selectedType = document.querySelector('input[name="extra_charge_type"]:checked'); if (!selectedType) { await customAlert('Please select a charge type (Fixed Amount or Percentage).'); return; } const chargeAmount = parseFloat(document.getElementById('extraChargeAmount').value) || 0; const description = document.getElementById('extraChargeDescription').value.trim(); if (chargeAmount <= 0) { await customAlert('Please enter a valid charge amount.'); return; } if (!description) { await customAlert('Please enter a description for this charge.'); return; } // Get the selected POS details const selectedOption = posSelect.options[posSelect.selectedIndex]; const resOrderId = selectedOption.dataset.resOrderId; const orderNo = selectedOption.dataset.orderNo; const posDesc = selectedOption.textContent.split(' (')[0]; // Get just the POS name // Confirm with user if (!(await customConfirm(`Are you sure you want to add an extra charge of ${formatAmount(chargeAmount)} to ${posDesc}?`))) { return; } try { // Get necessary data for saving const tableId = document.getElementById('tableId').value; const userId = document.getElementById('userId').value; // Create extra charge item with selected POS const extraChargeItem = { id: 0, // Use item_no 0 for extra charges name: description, description: description, price: chargeAmount, quantity: 1, notes: '', discount: 0, pos_id: selectedPOS }; // Save extra charge item to database immediately const orderData = { action: 'save_order', table_id: tableId, user_id: userId, items: [extraChargeItem] }; const saveResponse = await fetch('api/orders.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(orderData) }); const saveResult = await saveResponse.json(); if (!saveResult.success) { showNotification('Error saving extra charge: ' + (saveResult.message || 'Unknown error'), 'error'); return; } // Add extra charge to cart as a saved item const cartItem = { id: 'extra_charge_' + Date.now(), item_no: 0, name: description, description: description, price: chargeAmount, quantity: 1, notes: '', discount: 0, pos_id: selectedPOS, res_order_id: resOrderId, order_no: orderNo, isSaved: true }; cart.push(cartItem); updateCartDisplay(); closeExtraChargeModal(); showNotification(`Extra charge "${description}" of ${formatAmount(chargeAmount)} has been added and saved to the order.`, 'success'); } catch (error) { console.error('Error adding extra charge:', error); showNotification('Error adding extra charge: ' + error.message, 'error'); } } // Split Bill data storage let splitBillItems = []; let availableTablesData = []; async function showSplitBill() { closeOptionsDialog(); // Check permission to transfer orders between tables if (!hasPermission('transfer_order_to_table')) { await customAlert('You do not have permission to split bills / transfer orders to other tables.'); return; } // Check if cart has items if (cart.length === 0) { await customAlert('No items to split. Please add items first.'); return; } // Check if an order exists const existingOrderId = document.getElementById('existingOrderId').value; if (!existingOrderId) { await customAlert('Please save the order first before splitting the bill.'); return; } // Reset form document.getElementById('splitTargetTable').value = ''; document.getElementById('splitSelectAll').checked = false; // Set current table display const currentTable = document.getElementById('tableNo').value; document.getElementById('splitCurrentTable').textContent = currentTable; // Load available tables and items await Promise.all([ loadAvailableTables(), loadSplitBillItems() ]); // Show modal document.getElementById('splitBillModal').style.display = 'flex'; } function closeSplitBillModal() { document.getElementById('splitBillModal').style.display = 'none'; document.getElementById('splitTableOptions').style.display = 'none'; splitBillItems = []; } // Close table dropdown when clicking outside document.addEventListener('click', function(e) { const dropdown = document.getElementById('splitTableDropdown'); if (dropdown && !dropdown.contains(e.target)) { document.getElementById('splitTableOptions').style.display = 'none'; } }); async function loadAvailableTables() { const tableNo = document.getElementById('tableNo').value; const tbody = document.getElementById('splitTableOptionsBody'); // Reset selection and search document.getElementById('splitTargetTable').value = ''; document.getElementById('splitTableSelectedText').textContent = '-- Select Target Table --'; document.getElementById('splitTableSearch').value = ''; tbody.innerHTML = 'Loading...'; availableTablesData = []; try { const response = await fetch(`api/orders.php?action=get_available_tables¤t_table=${tableNo}`); const result = await response.json(); if (result.success && result.tables && result.tables.length > 0) { availableTablesData = result.tables; renderAvailableTables(availableTablesData); } else { tbody.innerHTML = 'No tables available'; } } catch (error) { console.error('Error loading tables:', error); tbody.innerHTML = 'Error loading tables'; } } function renderAvailableTables(tables) { const tbody = document.getElementById('splitTableOptionsBody'); tbody.innerHTML = ''; if (tables.length === 0) { tbody.innerHTML = 'No matching tables'; return; } tables.forEach(table => { const row = document.createElement('tr'); row.className = 'table-dropdown-row'; row.onclick = () => selectTargetTable(table.table_no, table.waiter_name, table.total_amount, table.is_occupied); row.innerHTML = ` ${table.table_no} ${table.waiter_name || '-'} ${table.is_occupied ? table.total_amount : '-'} `; tbody.appendChild(row); }); } function filterSplitTables() { const searchTerm = document.getElementById('splitTableSearch').value.toLowerCase().trim(); if (!searchTerm) { renderAvailableTables(availableTablesData); return; } const filteredTables = availableTablesData.filter(table => { const tableNo = table.table_no.toString().toLowerCase(); const waiterName = (table.waiter_name || '').toLowerCase(); return tableNo.includes(searchTerm) || waiterName.includes(searchTerm); }); renderAvailableTables(filteredTables); } function toggleTableDropdown() { const options = document.getElementById('splitTableOptions'); const isOpening = options.style.display === 'none'; options.style.display = isOpening ? 'block' : 'none'; // Focus search input when opening if (isOpening) { setTimeout(() => document.getElementById('splitTableSearch').focus(), 100); } } function selectTargetTable(tableNo, waiterName, totalAmount, isOccupied) { document.getElementById('splitTargetTable').value = tableNo; // Format display text let displayText = `${tableNo}`; if (isOccupied && (waiterName || parseFloat(totalAmount.replace(/,/g, '')) > 0)) { if (waiterName) { displayText += ` - ${waiterName}`; } displayText += ` (${totalAmount})`; } document.getElementById('splitTableSelectedText').textContent = displayText; // Hide dropdown and clear search document.getElementById('splitTableOptions').style.display = 'none'; document.getElementById('splitTableSearch').value = ''; } async function loadSplitBillItems() { const tableNo = document.getElementById('tableNo').value; const tbody = document.getElementById('splitBillItemsBody'); tbody.innerHTML = 'Loading items...'; try { const response = await fetch(`api/orders.php?action=get_split_bill_items&table_no=${tableNo}`); const result = await response.json(); if (result.success && result.items && result.items.length > 0) { splitBillItems = result.items; displaySplitBillItems(); } else { tbody.innerHTML = 'No items found on this table.'; } } catch (error) { console.error('Error loading split bill items:', error); tbody.innerHTML = 'Error loading items.'; } } function displaySplitBillItems() { const tbody = document.getElementById('splitBillItemsBody'); let html = ''; splitBillItems.forEach((item, index) => { const itemAmount = item.price * item.quantity; html += `
${item.description}
${item.pos_desc}
${item.quantity} 0.00 `; }); tbody.innerHTML = html; updateSplitTotalAmount(); } function toggleSplitSelectAll() { const selectAll = document.getElementById('splitSelectAll').checked; const checkboxes = document.querySelectorAll('.split-item-checkbox'); checkboxes.forEach((checkbox, index) => { checkbox.checked = selectAll; updateSplitItemSelection(index); }); } function updateSplitItemSelection(index) { const checkbox = document.querySelector(`.split-item-checkbox[data-index="${index}"]`); const qtyInput = document.getElementById(`splitQty_${index}`); const item = splitBillItems[index]; if (checkbox.checked) { qtyInput.disabled = false; qtyInput.value = item.quantity; // Default to full quantity } else { qtyInput.disabled = true; qtyInput.value = 0; } updateSplitQuantity(index); } function updateSplitQuantity(index) { const qtyInput = document.getElementById(`splitQty_${index}`); const amountCell = document.getElementById(`splitAmount_${index}`); const item = splitBillItems[index]; let qty = parseInt(qtyInput.value) || 0; // Ensure quantity doesn't exceed available if (qty > item.quantity) { qty = item.quantity; qtyInput.value = qty; } // Ensure quantity is not negative if (qty < 0) { qty = 0; qtyInput.value = qty; } const amount = item.price * qty; amountCell.textContent = formatAmount(amount); updateSplitTotalAmount(); } function updateSplitTotalAmount() { let total = 0; splitBillItems.forEach((item, index) => { const qtyInput = document.getElementById(`splitQty_${index}`); if (qtyInput) { const qty = parseInt(qtyInput.value) || 0; total += item.price * qty; } }); document.getElementById('splitTotalAmount').textContent = formatAmount(total); } async function executeSplitBill() { const targetTable = document.getElementById('splitTargetTable').value; if (!targetTable) { await customAlert('Please select a target table to transfer items to.'); return; } // Collect items to transfer const itemsToTransfer = []; splitBillItems.forEach((item, index) => { const checkbox = document.querySelector(`.split-item-checkbox[data-index="${index}"]`); const qtyInput = document.getElementById(`splitQty_${index}`); if (checkbox && checkbox.checked) { const transferQty = parseInt(qtyInput.value) || 0; if (transferQty > 0) { itemsToTransfer.push({ id: item.id, res_order_id: item.res_order_id, item_no: item.item_no, description: item.description, pos_no: item.pos_no, transfer_qty: transferQty, original_qty: item.quantity, price: item.price }); } } }); if (itemsToTransfer.length === 0) { await customAlert('Please select at least one item and specify the quantity to transfer.'); return; } // Calculate total to transfer const totalToTransfer = itemsToTransfer.reduce((sum, item) => sum + (item.price * item.transfer_qty), 0); // Confirm with user const targetTableName = document.getElementById('splitTableSelectedText').textContent; if (!(await customConfirm(`Transfer ${itemsToTransfer.length} item(s) totaling ${formatAmount(totalToTransfer)} to Table ${targetTableName}?`))) { return; } try { const sourceTable = document.getElementById('tableNo').value; const response = await fetch('api/orders.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'transfer_items', source_table: sourceTable, target_table: targetTable, items: itemsToTransfer }) }); const result = await response.json(); if (result.success) { showNotification('Items transferred successfully!', 'success'); closeSplitBillModal(); // Reload the current table's order to reflect changes await loadExistingOrder(); } else { showNotification('Error transferring items: ' + result.message, 'error'); } } catch (error) { console.error('Error executing split bill:', error); showNotification('Error transferring items: ' + error.message, 'error'); } } async function showKOTProgress() { closeOptionsDialog(); await customAlert('View KOT Progress - To be implemented'); // TODO: Implement KOT Progress functionality } // ========== Delete Items Functions ========== let deleteItemsData = []; let selectedDeleteItems = []; async function showDeleteItems() { closeOptionsDialog(); // Check permission to remove items if (!hasPermission('remove_items')) { await customAlert('You do not have permission to remove items.'); return; } // Check if there are items in the cart const savedItems = cart.filter(item => item.isSaved); if (savedItems.length === 0) { await customAlert('No items to remove. Please add items to the order first.'); return; } // Load items for deletion loadDeleteItems(); // Show modal document.getElementById('deleteItemsModal').style.display = 'flex'; } function closeDeleteItemsModal() { document.getElementById('deleteItemsModal').style.display = 'none'; selectedDeleteItems = []; document.getElementById('selectAllDeleteItems').checked = false; } async function loadDeleteItems() { const tableBody = document.getElementById('deleteItemsTableBody'); tableBody.innerHTML = 'Loading items...'; const tableNo = document.getElementById('tableNo').value; const currentPosId = document.getElementById('currentPosId').value; try { // Fetch items from the order using kotAction endpoint const response = await fetch(`../kotAction.php?remove_item_from_order&table_no=${tableNo}&pos_no=${currentPosId}&order_no=0`); const text = await response.text(); let data; try { if (text.trim().startsWith('<')) { const jsonMatch = text.match(/\[[\s\S]*\]|\{[\s\S]*\}/); if (jsonMatch) { data = JSON.parse(jsonMatch[0]); } else { throw new Error('Server returned an error'); } } else { data = JSON.parse(text); } } catch (parseError) { console.error('Response was not valid JSON:', text.substring(0, 500)); throw new Error('Invalid response from server'); } deleteItemsData = Array.isArray(data) ? data : (data.rows || []); if (deleteItemsData.length === 0) { tableBody.innerHTML = 'No items found in this order.'; return; } // Build table rows with checkboxes let html = ''; deleteItemsData.forEach((item, index) => { const description = item.description || '-'; const qty = parseFloat(item.quantity) || 0; const unitCost = parseFloat(item.unit_cost) || parseFloat(item.set_price) || 0; const amount = parseFloat(item.total_amount) || (unitCost * qty); html += ` ${description} ${qty} ${formatCurrency(unitCost)} ${formatCurrency(amount)} `; }); tableBody.innerHTML = html; selectedDeleteItems = []; } catch (error) { console.error('Error loading delete items:', error); tableBody.innerHTML = `Error loading items: ${error.message}`; } } function toggleSelectAllDeleteItems() { const selectAll = document.getElementById('selectAllDeleteItems').checked; const checkboxes = document.querySelectorAll('.delete-item-checkbox'); checkboxes.forEach(checkbox => { checkbox.checked = selectAll; const itemId = parseInt(checkbox.dataset.id); if (selectAll) { if (!selectedDeleteItems.includes(itemId)) { selectedDeleteItems.push(itemId); } } }); if (!selectAll) { selectedDeleteItems = []; } // Update row highlighting updateDeleteItemsHighlight(); } function toggleDeleteItemSelection(itemId) { const index = selectedDeleteItems.indexOf(itemId); if (index > -1) { selectedDeleteItems.splice(index, 1); } else { selectedDeleteItems.push(itemId); } // Update select all checkbox const checkboxes = document.querySelectorAll('.delete-item-checkbox'); const allChecked = Array.from(checkboxes).every(cb => cb.checked); document.getElementById('selectAllDeleteItems').checked = allChecked; // Update row highlighting updateDeleteItemsHighlight(); } function updateDeleteItemsHighlight() { const rows = document.querySelectorAll('#deleteItemsTableBody tr'); rows.forEach(row => { const itemId = parseInt(row.dataset.id); if (selectedDeleteItems.includes(itemId)) { row.classList.add('selected'); } else { row.classList.remove('selected'); } }); } async function openDeleteReasonModal() { if (selectedDeleteItems.length === 0) { await customAlert('Please select at least one item to remove.'); return; } // Clear previous reason document.getElementById('deleteReasonText').value = ''; // Show reason modal document.getElementById('deleteReasonModal').style.display = 'flex'; } function closeDeleteReasonModal() { document.getElementById('deleteReasonModal').style.display = 'none'; } async function confirmDeleteItems() { const reason = document.getElementById('deleteReasonText').value.trim(); if (!reason) { await customAlert('Please enter a reason for removing the items.'); return; } if (selectedDeleteItems.length === 0) { await customAlert('No items selected for removal.'); return; } const currentPosId = document.getElementById('currentPosId').value; const userId = document.getElementById('userId')?.value || '1'; // Build comma-separated list of item IDs const strId = selectedDeleteItems.join(','); // Get order_no from one of the selected items const selectedItem = deleteItemsData.find(item => selectedDeleteItems.includes(parseInt(item.id))); const orderNo = selectedItem ? selectedItem.order_no : ''; // Get selected date if any const selectedDate = sessionStorage.getItem('dateSelected') || ''; try { // Call RemoveItem endpoint const formData = new FormData(); formData.append('str_id', strId); formData.append('pos_no', currentPosId); formData.append('reason', reason); formData.append('cancelled_by', userId); formData.append('order_no', orderNo); formData.append('selectedDate', selectedDate); const response = await fetch('../RemoveItem.php', { method: 'POST', body: formData }); const text = await response.text(); console.log('RemoveItem response:', text); // Close modals closeDeleteReasonModal(); closeDeleteItemsModal(); // Show success message showNotification('Items have been removed successfully.', 'success'); // Clear cart first, then reload to reflect changes cart = []; updateCartDisplay(); // Reload existing orders (if any remain) await loadExistingOrder(); } catch (error) { console.error('Error removing items:', error); showNotification('Error removing items. Please try again.', 'error'); } } function showPostingDate() { closeOptionsDialog(); // Check if there are items in the cart (if items exist, disable date selection) const hasItems = cart.length > 0 && cart.some(item => item.isSaved); // Reset form state document.getElementById('postToday').checked = true; document.getElementById('postSelectDate').checked = false; document.getElementById('dateSelectRow').style.display = 'none'; document.getElementById('dateSelectPost').value = new Date().toISOString().split('T')[0]; // Check if a date was previously selected in sessionStorage const savedDate = sessionStorage.getItem('dateSelected'); const isAutoBackdated = sessionStorage.getItem('autoBackdated') === 'true'; if (savedDate) { document.getElementById('postSelectDate').checked = true; document.getElementById('postToday').checked = false; document.getElementById('dateSelectRow').style.display = 'block'; document.getElementById('dateSelectPost').value = savedDate; document.getElementById('selectedDateDisplay').style.display = 'block'; // Show auto-backdated indicator if applicable if (isAutoBackdated) { document.getElementById('selectedDateText').textContent = savedDate + ' (Auto - Closing Time)'; } else { document.getElementById('selectedDateText').textContent = savedDate; } } else { document.getElementById('selectedDateDisplay').style.display = 'none'; } // If there are saved items, show warning and disable date change if (hasItems) { document.getElementById('postToday').disabled = true; document.getElementById('postSelectDate').disabled = true; document.getElementById('dateSelectPost').disabled = true; } else { document.getElementById('postToday').disabled = false; document.getElementById('postSelectDate').disabled = false; document.getElementById('dateSelectPost').disabled = false; } document.getElementById('postingDateModal').style.display = 'flex'; } function closePostingDateModal() { document.getElementById('postingDateModal').style.display = 'none'; } async function confirmPostingDate() { const isSelectDate = document.getElementById('postSelectDate').checked; if (isSelectDate) { const selectedDate = document.getElementById('dateSelectPost').value; if (!selectedDate) { await customAlert('Please select a date'); return; } // Check if cost of sales for the date was not posted try { const response = await fetch(`../getPos.php?check_cost_of_sale_posting&date=${selectedDate}`); const result = await response.json(); if (result.success) { if (await customConfirm('Are you sure you want to use this date: ' + selectedDate + '?')) { sessionStorage.setItem('dateSelected', selectedDate); sessionStorage.removeItem('autoBackdated'); // Clear auto-backdated flag since user manually selected document.getElementById('selectedDateDisplay').style.display = 'block'; document.getElementById('selectedDateText').textContent = selectedDate; closePostingDateModal(); showNotification('Posting date set to: ' + selectedDate, 'success'); } } else { showNotification('Warning: ' + result.msg, 'warning'); document.getElementById('dateSelectPost').value = new Date().toISOString().split('T')[0]; } } catch (error) { console.error('Error checking date:', error); showNotification('Error verifying date. Please try again.', 'error'); } } else { // Using today's date (system date) sessionStorage.removeItem('dateSelected'); sessionStorage.removeItem('autoBackdated'); // Clear auto-backdated flag document.getElementById('selectedDateDisplay').style.display = 'none'; closePostingDateModal(); showNotification('Posting date set to system date (today)', 'success'); } } // Event listeners for posting date radio buttons document.addEventListener('DOMContentLoaded', function() { const postToday = document.getElementById('postToday'); const postSelectDate = document.getElementById('postSelectDate'); const dateSelectRow = document.getElementById('dateSelectRow'); if (postToday) { postToday.addEventListener('change', function() { if (this.checked) { dateSelectRow.style.display = 'none'; } }); } if (postSelectDate) { postSelectDate.addEventListener('change', function() { if (this.checked) { dateSelectRow.style.display = 'block'; } }); } }); async function showSalesReport() { closeOptionsDialog(); // Get current POS info const posNo = document.getElementById('currentPosId').value; const userId = document.getElementById('userId').value; // Build the report URL using v2 sales report let reportUrl = `sales-report.php?pos_no=${posNo}`; // If user doesn't have combined_cashier permission, filter to only show their own sales if (!hasPermission('combined_cashier')) { reportUrl += `&filter_cashier=${userId}`; } const newWindow = window.open(reportUrl, 'Sales Report', 'width=520,height=800,scrollbars=1,resizable=1'); if (newWindow === null || typeof newWindow === 'undefined') { await customAlert('Please disable your pop-up blocker to view the Sales Report.'); } else { newWindow.focus(); } } function showReturns() { closeOptionsDialog(); // Reset the form document.getElementById('returnsPosSelect').value = ''; document.getElementById('returnsOrderNo').value = ''; document.getElementById('returnsItemSelect').innerHTML = ''; document.getElementById('returnsUnitsSold').value = ''; document.getElementById('returnsUnitsToReturn').value = ''; document.getElementById('returnsReason').value = ''; document.getElementById('returnsWarningMessage').style.display = 'none'; // Pre-select current POS if available const currentPosId = document.getElementById('currentPosId')?.value; if (currentPosId) { document.getElementById('returnsPosSelect').value = currentPosId; } // Show the modal document.getElementById('returnsModal').style.display = 'flex'; } function closeReturnsModal() { document.getElementById('returnsModal').style.display = 'none'; } function onReturnsPosChange() { // Clear item select when POS changes document.getElementById('returnsItemSelect').innerHTML = ''; document.getElementById('returnsUnitsSold').value = ''; document.getElementById('returnsUnitsToReturn').value = ''; document.getElementById('returnsWarningMessage').style.display = 'none'; // Reload items if order no is already entered const orderNo = document.getElementById('returnsOrderNo').value; if (orderNo) { loadReturnsOrderItems(); } } async function loadReturnsOrderItems() { const posNo = document.getElementById('returnsPosSelect').value; const orderNo = document.getElementById('returnsOrderNo').value; if (!posNo) { showReturnsWarning('Please select a P.O.S. first'); return; } if (!orderNo) { return; } try { // First check if order is on a closed date const checkResponse = await fetch(`../reverse_order.php?check_order_posting&pos_no=${posNo}&order_no=${orderNo}`); const checkText = await checkResponse.text(); // Try to parse JSON (might have PHP warnings) let checkData; try { const jsonMatch = checkText.match(/\{.*\}/s); if (jsonMatch) { checkData = JSON.parse(jsonMatch[0]); } } catch (e) { console.error('Error parsing check response:', e); } if (checkData && !checkData.success) { showReturnsWarning('Order is on a date that was already closed'); } else { document.getElementById('returnsWarningMessage').style.display = 'none'; } // Load items for the order const response = await fetch(`../reverse_order.php?get_items&pos_no=${posNo}&order_no=${orderNo}`); const text = await response.text(); // Parse JSON (might have PHP warnings) let items; try { const jsonMatch = text.match(/\[.*\]/s); if (jsonMatch) { items = JSON.parse(jsonMatch[0]); } else { items = []; } } catch (e) { console.error('Error parsing items response:', e); items = []; } // Populate the item select const itemSelect = document.getElementById('returnsItemSelect'); itemSelect.innerHTML = ''; if (items.length === 0) { showReturnsWarning('No settled items found for this order. Only settled orders (not yet posted to accounts) can be returned.'); return; } items.forEach(item => { const option = document.createElement('option'); option.value = item.id; option.textContent = `${item.description} (Qty: ${item.quantity})`; option.dataset.quantity = item.quantity; itemSelect.appendChild(option); }); } catch (error) { console.error('Error loading order items:', error); showReturnsWarning('Error loading order items. Please try again.'); } } function onReturnsItemChange() { const itemSelect = document.getElementById('returnsItemSelect'); const selectedOption = itemSelect.options[itemSelect.selectedIndex]; if (selectedOption && selectedOption.value) { const quantity = selectedOption.dataset.quantity || 0; document.getElementById('returnsUnitsSold').value = quantity; document.getElementById('returnsUnitsToReturn').value = ''; document.getElementById('returnsUnitsToReturn').max = quantity; } else { document.getElementById('returnsUnitsSold').value = ''; document.getElementById('returnsUnitsToReturn').value = ''; } } function validateReturnsUnits() { const unitsSold = parseInt(document.getElementById('returnsUnitsSold').value) || 0; const unitsToReturn = parseInt(document.getElementById('returnsUnitsToReturn').value) || 0; if (unitsToReturn > unitsSold) { showReturnsWarning('Units to return cannot exceed units sold'); document.getElementById('returnsUnitsToReturn').value = unitsSold; return false; } if (unitsToReturn <= 0) { showReturnsWarning('Units to return must be greater than 0'); return false; } document.getElementById('returnsWarningMessage').style.display = 'none'; return true; } function showReturnsWarning(message) { const warningDiv = document.getElementById('returnsWarningMessage'); warningDiv.textContent = message; warningDiv.style.display = 'block'; } async function processReturn() { const posNo = document.getElementById('returnsPosSelect').value; const orderNo = document.getElementById('returnsOrderNo').value; const itemId = document.getElementById('returnsItemSelect').value; const unitsSold = parseInt(document.getElementById('returnsUnitsSold').value) || 0; const unitsToReturn = parseInt(document.getElementById('returnsUnitsToReturn').value) || 0; const reason = document.getElementById('returnsReason').value.trim(); // Validation if (!posNo) { showReturnsWarning('Please select a P.O.S.'); return; } if (!orderNo) { showReturnsWarning('Please enter an order number'); return; } if (!itemId) { showReturnsWarning('Please select an item'); return; } if (!unitsToReturn || unitsToReturn <= 0) { showReturnsWarning('Please enter valid units to return'); return; } if (unitsToReturn > unitsSold) { showReturnsWarning('Units to return cannot exceed units sold'); return; } if (!reason) { showReturnsWarning('Please enter a reason for the return'); return; } // Get current user ID const userId = document.getElementById('userId')?.value || ''; // Get selected date (posting date) const selectedDate = sessionStorage.getItem('dateSelected') || new Date().toISOString().split('T')[0]; // Confirm the action if (!(await customConfirm(`Are you sure you want to return ${unitsToReturn} unit(s) of the selected item?`))) { return; } try { const formData = new FormData(); formData.append('pos_no', posNo); formData.append('order_no', orderNo); formData.append('res_order_item_id', itemId); formData.append('units_sold', unitsSold); formData.append('units_to_return', unitsToReturn); formData.append('reason', reason); formData.append('cancelled_by', userId); formData.append('selected_date', selectedDate); const response = await fetch('../reverse_order.php?reverse_order', { method: 'POST', body: formData }); const text = await response.text(); // Parse JSON (might have PHP warnings) let result; try { const jsonMatch = text.match(/\{.*\}/s); if (jsonMatch) { result = JSON.parse(jsonMatch[0]); } else { throw new Error('Invalid response'); } } catch (e) { console.error('Error parsing response:', e, text); showNotification('Error processing return. Please try again.', 'error'); return; } if (result.success) { showNotification(result.message || 'Return processed successfully', 'success'); closeReturnsModal(); // Reload the current order if we're viewing it loadExistingOrder(); } else { showReturnsWarning(result.message || 'Error processing return'); } } catch (error) { console.error('Error processing return:', error); showReturnsWarning('Error processing return. Please try again.'); } } async function showKOTReport() { closeOptionsDialog(); // Open the KOT Report in a new window const reportUrl = '../kot-report-print.php'; const newWindow = window.open(reportUrl, 'K.O.T Printout', 'width=400,height=900,scrollbar=no,location=no,resizable=no,dialog=yes,alwaysontop=yes,maximize=no,left=0,top=0'); if (newWindow === null || typeof newWindow === 'undefined') { await customAlert('Please disable your pop-up blocker to view the KOT Report.'); } else { newWindow.focus(); } } async function showCloseDay() { closeOptionsDialog(); // Get the currently selected POS (from the global currentPOS variable) const posNo = currentPOS || document.getElementById('currentPosId')?.value; // Get POS name from the userPosList let posName = 'POS'; try { const posList = JSON.parse(document.getElementById('userPosList')?.value || '[]'); const selectedPos = posList.find(p => p.pos_no == posNo); if (selectedPos) { posName = selectedPos.description; } } catch (e) { console.error('Error parsing POS list:', e); } if (!posNo) { await customAlert('No POS selected'); return; } // Store the POS number in the modal for use by confirmCloseDay document.getElementById('closeDayModal').dataset.posNo = posNo; // Set the POS name in the modal document.getElementById('closeDayPosName').textContent = posName; // Reset the modal state document.getElementById('closeDayProgress').style.display = 'none'; document.getElementById('closeDayResult').style.display = 'none'; document.getElementById('closeDayResult').innerHTML = ''; document.getElementById('closeDayResult').className = 'close-day-result'; document.getElementById('closeDayFooter').style.display = 'flex'; document.getElementById('closeDayConfirmBtn').disabled = false; // Show the modal document.getElementById('closeDayModal').style.display = 'flex'; } function closeCloseDayModal() { document.getElementById('closeDayModal').style.display = 'none'; } async function confirmCloseDay() { // Get POS number from the modal's data attribute (set when modal was opened) const posNo = document.getElementById('closeDayModal').dataset.posNo; if (!posNo) { await customAlert('No POS selected'); return; } // Disable the confirm button and show progress document.getElementById('closeDayConfirmBtn').disabled = true; document.getElementById('closeDayProgress').style.display = 'flex'; try { const response = await fetch(`../close-day.php?pos_no=${posNo}&_=${Date.now()}`); const text = await response.text(); // Hide progress document.getElementById('closeDayProgress').style.display = 'none'; // Parse JSON response let result; try { // Try direct JSON parse first (clean response) result = JSON.parse(text); } catch (e) { // Fallback: extract JSON from response that might contain PHP warnings try { const jsonMatch = text.match(/\{.*\}/s); if (jsonMatch) { result = JSON.parse(jsonMatch[0]); } else { throw new Error('No JSON found in response'); } } catch (e2) { console.error('Error parsing close day response:', text); showCloseDayError('Error processing close day. Server response: ' + text.substring(0, 200)); return; } } console.log('Close day response:', JSON.stringify(result, null, 2)); if (result.success) { const datesPosted = result.dates_posted || 0; if (datesPosted > 0) { showCloseDaySuccess(`Day closed successfully! ${datesPosted} date(s) posted to accounts.`); } else { showCloseDaySuccess(`Close day completed. No new sales to post.`); } } else { showCloseDayError(result.msg || 'Error closing day'); } } catch (error) { console.error('Error closing day:', error); document.getElementById('closeDayProgress').style.display = 'none'; showCloseDayError('Error closing day. Please check console for details.'); } } function showCloseDaySuccess(message) { const resultDiv = document.getElementById('closeDayResult'); resultDiv.innerHTML = `

${message}

`; resultDiv.className = 'close-day-result close-day-success'; resultDiv.style.display = 'block'; // Hide the footer buttons since operation is complete document.getElementById('closeDayFooter').innerHTML = ` `; } function showCloseDayError(message) { const resultDiv = document.getElementById('closeDayResult'); resultDiv.innerHTML = `

${message}

`; resultDiv.className = 'close-day-result close-day-error'; resultDiv.style.display = 'block'; // Re-enable the confirm button document.getElementById('closeDayConfirmBtn').disabled = false; } // ========== KOT Progress Functions ========== let kotProgressData = []; let selectedKOTRow = null; function showKOTProgress() { closeOptionsDialog(); // Reset the date to today document.getElementById('kotProgressDate').value = new Date().toISOString().split('T')[0]; // Get current POS and set it as default const currentPosId = document.getElementById('currentPosId').value; const kotPOSSelect = document.getElementById('kotProgressPOS'); if (kotPOSSelect && currentPosId) { kotPOSSelect.value = currentPosId; } // Load KOT data loadKOTProgress(); // Show modal document.getElementById('kotProgressModal').style.display = 'flex'; } function closeKOTProgressModal() { document.getElementById('kotProgressModal').style.display = 'none'; selectedKOTRow = null; } async function loadKOTProgress() { const tableBody = document.getElementById('kotProgressTableBody'); tableBody.innerHTML = 'Loading KOT data...'; const searchDate = document.getElementById('kotProgressDate').value; const posNo = document.getElementById('kotProgressPOS').value; try { // Build URL - getKot.php is in the parent pos folder // Use the current POS if no specific POS is selected const currentPosId = document.getElementById('currentPosId').value; const effectivePosNo = posNo || currentPosId; let url = `../getKot.php?pos_no=${effectivePosNo}&search_date=${searchDate}`; const response = await fetch(url); const text = await response.text(); // Try to parse as JSON, handle potential PHP errors let data; try { // If response starts with HTML tags, it's likely a PHP error if (text.trim().startsWith('<')) { console.error('PHP Error in response:', text.substring(0, 500)); // Try to extract JSON from the response (sometimes PHP warnings are followed by JSON) const jsonMatch = text.match(/\{[\s\S]*\}|\[[\s\S]*\]/); if (jsonMatch) { data = JSON.parse(jsonMatch[0]); } else { throw new Error('Server returned an error page'); } } else { data = JSON.parse(text); } } catch (parseError) { console.error('Response was not valid JSON:', text.substring(0, 500)); throw new Error('Invalid response from server'); } // Handle both array and object with rows property kotProgressData = Array.isArray(data) ? data : (data.rows || []); if (kotProgressData.length === 0) { tableBody.innerHTML = 'No KOT records found for the selected criteria.'; return; } // Build table rows let html = ''; kotProgressData.forEach((kot, index) => { const orderTime = kot.order_time || '-'; const orderNo = kot.order_no || '-'; const waiter = kot.waiter || '-'; // Status radio buttons (read-only) const newChecked = kot.new_order == '1' ? 'checked' : ''; const seenChecked = kot.seen == '1' ? 'checked' : ''; const processingChecked = kot.processing == '1' ? 'checked' : ''; const readyChecked = kot.ready == '1' ? 'checked' : ''; html += ` ${orderTime} ${orderNo} ${waiter} `; }); tableBody.innerHTML = html; } catch (error) { console.error('Error loading KOT progress:', error); tableBody.innerHTML = `Error loading KOT data: ${error.message}`; } } function selectKOTRow(index) { // Remove previous selection const rows = document.querySelectorAll('#kotProgressTableBody tr'); rows.forEach(row => row.classList.remove('selected')); // Add selection to clicked row const selectedRow = document.querySelector(`#kotProgressTableBody tr[data-index="${index}"]`); if (selectedRow) { selectedRow.classList.add('selected'); } selectedKOTRow = kotProgressData[index]; } async function viewKOTDetails() { if (!selectedKOTRow) { await customAlert('Please select a KOT row first.'); return; } // Set bill number in modal header document.getElementById('kotDetailsBillNo').textContent = selectedKOTRow.order_no; // Load order details loadKOTDetails(selectedKOTRow.order_no, selectedKOTRow.pos_no); // Show details modal document.getElementById('kotDetailsModal').style.display = 'flex'; } function closeKOTDetailsModal() { document.getElementById('kotDetailsModal').style.display = 'none'; } async function loadKOTDetails(orderNo, posNo) { const tableBody = document.getElementById('kotDetailsTableBody'); tableBody.innerHTML = 'Loading order details...'; try { const response = await fetch(`../kotAction.php?order_no=${orderNo}&pos_no=${posNo}`); const text = await response.text(); // Try to parse as JSON, handle potential PHP errors let data; try { data = JSON.parse(text); } catch (parseError) { console.error('Response was not valid JSON:', text.substring(0, 200)); throw new Error('Invalid response from server'); } const items = Array.isArray(data) ? data : (data.rows || []); if (items.length === 0) { tableBody.innerHTML = 'No items found for this order.'; document.getElementById('kotDetailsTotal').textContent = '0.00'; return; } let html = ''; let total = 0; items.forEach((item, index) => { const description = item.description || '-'; const qty = parseFloat(item.quantity) || 0; const price = parseFloat(item.set_price) || 0; const amount = parseFloat(item.total_amount) || (price * qty); total += amount; html += ` ${index + 1} ${description} ${qty} ${formatCurrency(price)} ${formatCurrency(amount)} `; }); tableBody.innerHTML = html; document.getElementById('kotDetailsTotal').textContent = formatCurrency(total); } catch (error) { console.error('Error loading KOT details:', error); tableBody.innerHTML = 'Error loading order details. Please try again.'; } } // Event listeners for KOT Progress filters document.addEventListener('DOMContentLoaded', function() { const kotDateInput = document.getElementById('kotProgressDate'); const kotPOSSelect = document.getElementById('kotProgressPOS'); if (kotDateInput) { kotDateInput.addEventListener('change', function() { if (document.getElementById('kotProgressModal').style.display === 'flex') { loadKOTProgress(); } }); } if (kotPOSSelect) { kotPOSSelect.addEventListener('change', function() { if (document.getElementById('kotProgressModal').style.display === 'flex') { loadKOTProgress(); } }); } }); // ========== Delivery Functions ========== let deliveryClients = []; let couriers = []; let selectedClientForOrder = null; async function loadDeliveryClients() { try { const response = await fetch('../delivery.php'); const data = await response.json(); // Load couriers to map courier names const courierResponse = await fetch('../courier.php'); const courierData = await courierResponse.json(); // Create courier map const courierMap = {}; courierData.forEach(courier => { courierMap[courier.id] = courier.name; }); // Add courier names to clients deliveryClients = data.map(client => ({ ...client, courier_name: courierMap[client.courier] || '' })); displayDeliveryClients(deliveryClients); } catch (error) { console.error('Error loading delivery clients:', error); showNotification('Error loading delivery clients: ' + error.message, 'error'); } } function displayDeliveryClients(clients) { const tbody = document.getElementById('deliveryClientsTableBody'); if (!clients || clients.length === 0) { tbody.innerHTML = ` No delivery clients found. Click "New Client" to add one. `; return; } let html = ''; clients.forEach(client => { html += ` ${client.client_name || ''} ${client.contact || ''} ${client.location || ''} ${client.email || ''} `; }); tbody.innerHTML = html; } function selectDeliveryClient(clientId) { selectedClientForOrder = clientId; } function toggleAllClientsSelection() { // Not needed for radio buttons, but kept for compatibility } // Search delivery clients document.addEventListener('DOMContentLoaded', function() { const searchInput = document.getElementById('searchDelivery'); if (searchInput) { searchInput.addEventListener('input', function(e) { const searchTerm = e.target.value.toLowerCase(); const filtered = deliveryClients.filter(client => (client.client_name || '').toLowerCase().includes(searchTerm) || (client.contact || '').toLowerCase().includes(searchTerm) || (client.location || '').toLowerCase().includes(searchTerm) ); displayDeliveryClients(filtered); }); } }); async function assignClientOrder() { if (!selectedClientForOrder) { await customAlert('Please select a client to assign the order.'); return; } if (cart.length === 0) { await customAlert('Cart is empty. Please add items first.'); return; } // Load couriers and show selection dialog await loadCouriers(); if (couriers.length === 0) { await customAlert('No couriers available. Please add a courier first.'); return; } // Populate courier dropdown in selection modal const courierSelect = document.getElementById('assignCourierSelect'); courierSelect.innerHTML = ''; couriers.forEach(courier => { const option = document.createElement('option'); option.value = courier.id; option.textContent = courier.name; courierSelect.appendChild(option); }); // Show courier selection modal document.getElementById('courierSelectionModal').style.display = 'flex'; } function closeCourierSelectionModal() { document.getElementById('courierSelectionModal').style.display = 'none'; } async function confirmCourierSelection() { const selectedCourierId = document.getElementById('assignCourierSelect').value; if (!selectedCourierId) { await customAlert('Please select a courier'); return; } // Get the current table number from the hidden input const tableNo = document.getElementById('tableNo').value; if (!tableNo) { await customAlert('No table selected. Please load a table first.'); return; } const client = deliveryClients.find(c => c.id == selectedClientForOrder); if (!client) { await customAlert('Client not found'); return; } // Update client object with selected courier const clientWithCourier = { ...client, courier: selectedCourierId }; try { const formData = new FormData(); formData.append('assign_order', '1'); formData.append('rowData', JSON.stringify(clientWithCourier)); formData.append('table_no', tableNo); const response = await fetch('../delivery.php', { method: 'POST', body: formData }); const result = await response.text(); await customAlert(result); closeCourierSelectionModal(); closeDeliveryModal(); // Clear the cart and reload to show it's now a delivery order location.reload(); } catch (error) { console.error('Error assigning order:', error); showNotification('Error assigning order to client: ' + error.message, 'error'); } } async function newDeliveryClient() { // Reset form document.getElementById('clientFormId').value = ''; document.getElementById('clientName').value = ''; document.getElementById('clientContact').value = ''; document.getElementById('clientLocation').value = ''; document.getElementById('clientEmail').value = ''; document.getElementById('clientFormTitle').textContent = '➕ Add Delivery Client'; // Show modal document.getElementById('clientFormModal').style.display = 'flex'; } function closeClientFormModal() { document.getElementById('clientFormModal').style.display = 'none'; } async function submitClientForm() { const clientId = document.getElementById('clientFormId').value; const clientName = document.getElementById('clientName').value.trim(); const contact = document.getElementById('clientContact').value.trim(); const location = document.getElementById('clientLocation').value.trim(); const email = document.getElementById('clientEmail').value.trim(); if (!clientName || !contact || !location) { await customAlert('Please fill in all required fields'); return; } try { const formData = new FormData(); if (clientId) { formData.append('update_client', '1'); formData.append('id', clientId); } else { formData.append('new_client', '1'); } formData.append('client_name', clientName); formData.append('contact', contact); formData.append('location', location); formData.append('email', email || '_'); formData.append('courier', '0'); // Default value since courier is selected during assignment const response = await fetch('../delivery.php', { method: 'POST', body: formData }); const result = await response.json(); if (result && result.isError) { showNotification('Error: ' + result.msg, 'error'); } else { showNotification(clientId ? 'Client updated successfully!' : 'Client saved successfully!', 'success'); closeClientFormModal(); loadDeliveryClients(); } } catch (error) { console.error('Error saving client:', error); showNotification(clientId ? 'Client updated successfully!' : 'Client saved successfully!', 'success'); closeClientFormModal(); loadDeliveryClients(); } } async function editDeliveryClient(clientId) { const client = deliveryClients.find(c => c.id == clientId); if (!client) return; // Populate form with client data document.getElementById('clientFormId').value = client.id; document.getElementById('clientName').value = client.client_name || ''; document.getElementById('clientContact').value = client.contact || ''; document.getElementById('clientLocation').value = client.location || ''; document.getElementById('clientEmail').value = client.email && client.email !== '_' ? client.email : ''; document.getElementById('clientFormTitle').textContent = '✏️ Edit Delivery Client'; // Show modal document.getElementById('clientFormModal').style.display = 'flex'; } async function deleteDeliveryClient(clientId) { if (!(await customConfirm('Are you sure you want to delete this client?'))) return; try { const formData = new FormData(); formData.append('delete_client', '1'); formData.append('id', clientId); const response = await fetch('../delivery.php', { method: 'POST', body: formData }); showNotification('Client deleted successfully!', 'success'); loadDeliveryClients(); } catch (error) { console.error('Error deleting client:', error); showNotification('Error deleting client', 'error'); } } function closeDeliveryModal() { document.getElementById('deliveryModal').style.display = 'none'; selectedClientForOrder = null; // Reset button visibility document.getElementById('deliveryAssignBtn').style.display = 'inline-block'; document.getElementById('deliverySelectClientBtn').style.display = 'none'; // If opened from header and no client was selected, revert to In Dining if (deliveryModeFromHeader && !selectedDeliveryClient) { currentOrderType = 'in_dining'; deliveryModeFromHeader = false; document.getElementById('btnDelivery').classList.remove('active'); document.getElementById('btnInDining').classList.add('active'); } } // ========== Courier Functions ========== function openCourierModal() { document.getElementById('courierModal').style.display = 'flex'; loadCouriers(); } function closeCourierModal() { document.getElementById('courierModal').style.display = 'none'; } async function loadCouriers() { try { const response = await fetch('../courier.php'); const data = await response.json(); couriers = data; displayCouriers(couriers); } catch (error) { console.error('Error loading couriers:', error); showNotification('Error loading couriers: ' + error.message, 'error'); } } function displayCouriers(courierList) { const tbody = document.getElementById('couriersTableBody'); if (!courierList || courierList.length === 0) { tbody.innerHTML = ` No couriers found. Click "New Courier" to add one. `; return; } let html = ''; courierList.forEach(courier => { html += ` ${courier.name || ''} ${courier.contact || ''} `; }); tbody.innerHTML = html; } // Search couriers document.addEventListener('DOMContentLoaded', function() { const searchInput = document.getElementById('searchCourier'); if (searchInput) { searchInput.addEventListener('input', function(e) { const searchTerm = e.target.value.toLowerCase(); const filtered = couriers.filter(courier => (courier.name || '').toLowerCase().includes(searchTerm) || (courier.contact || '').toLowerCase().includes(searchTerm) ); displayCouriers(filtered); }); } }); function newCourier() { // Reset form document.getElementById('courierFormId').value = ''; document.getElementById('courierName').value = ''; document.getElementById('courierContact').value = ''; document.getElementById('courierFormTitle').textContent = '➕ Add Courier'; // Show modal document.getElementById('courierFormModal').style.display = 'flex'; } function closeCourierFormModal() { document.getElementById('courierFormModal').style.display = 'none'; } async function submitCourierForm() { const courierId = document.getElementById('courierFormId').value; const courierName = document.getElementById('courierName').value.trim(); const contact = document.getElementById('courierContact').value.trim(); if (!courierName || !contact) { await customAlert('Please fill in all required fields'); return; } try { const formData = new FormData(); if (courierId) { formData.append('update_courier', '1'); formData.append('id', courierId); } else { formData.append('new_courier', '1'); } formData.append('name', courierName); formData.append('contact', contact); const response = await fetch('../courier.php', { method: 'POST', body: formData }); showNotification(courierId ? 'Courier updated successfully!' : 'Courier saved successfully!', 'success'); closeCourierFormModal(); loadCouriers(); } catch (error) { console.error('Error saving courier:', error); showNotification(courierId ? 'Courier updated successfully!' : 'Courier saved successfully!', 'success'); closeCourierFormModal(); loadCouriers(); } } function editCourier(courierId) { const courier = couriers.find(c => c.id == courierId); if (!courier) return; // Populate form with courier data document.getElementById('courierFormId').value = courier.id; document.getElementById('courierName').value = courier.name || ''; document.getElementById('courierContact').value = courier.contact || ''; document.getElementById('courierFormTitle').textContent = '✏️ Edit Courier'; // Show modal document.getElementById('courierFormModal').style.display = 'flex'; } async function deleteCourier(courierId) { if (!(await customConfirm('Are you sure you want to delete this courier?'))) return; try { const formData = new FormData(); formData.append('delete_courier', '1'); formData.append('id', courierId); const response = await fetch('../courier.php', { method: 'POST', body: formData }); showNotification('Courier deleted successfully!', 'success'); loadCouriers(); } catch (error) { console.error('Error deleting courier:', error); showNotification('Error deleting courier', 'error'); } } // ============ Previous Orders Functions ============ async function viewClientPreviousOrders(clientId) { const client = deliveryClients.find(c => c.id == clientId); if (!client) { await customAlert('Client not found'); return; } try { const response = await fetch(`api/get_client_previous_orders.php?client_id=${clientId}`); const text = await response.text(); let data; try { data = JSON.parse(text); } catch (parseError) { console.error('Failed to parse JSON. Response:', text); showNotification('Error loading previous orders: Invalid response from server', 'error'); return; } if (data.error) { showNotification('Error loading previous orders: ' + data.error, 'error'); return; } displayPreviousOrders(data.orders, client, data.currency); document.getElementById('previousOrdersModal').style.display = 'flex'; } catch (error) { console.error('Error loading previous orders:', error); showNotification('Error loading previous orders: ' + error.message, 'error'); } } function displayPreviousOrders(orders, client, currency = 'KES') { const content = document.getElementById('previousOrdersContent'); if (!orders || orders.length === 0) { content.innerHTML = `

No Previous Orders

Client ${client.client_name} has no previous orders.

`; return; } let html = `

Client: ${client.client_name}

Contact: ${client.contact} | Location: ${client.location}

Total Orders: ${orders.length}

`; orders.forEach((order, index) => { const orderDate = new Date(order.order_date).toLocaleString('en-US', { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); html += `
Order #${order.delivery_no || order.res_order_id} ${orderDate}
${currency} ${formatAmount(order.order_amount)} Table: ${order.table_no}
`; if (order.items && order.items.length > 0) { order.items.forEach(item => { html += ` `; }); } else { html += ` `; } html += `
Item Qty Price Amount
${item.description}
${item.res_order_item_notes && item.res_order_item_notes !== '_' ? `
Note: ${item.res_order_item_notes}
` : ''}
${item.quantity} ${currency} ${formatAmount(item.set_price)} ${currency} ${formatAmount(item.amount)}
No items found for this order
`; }); content.innerHTML = html; } function closePreviousOrdersModal() { document.getElementById('previousOrdersModal').style.display = 'none'; } // ========== Footer Notes Functions ========== function showReceiptSettings() { closeOptionsDialog(); // Load current footer messages from database loadFooterMessages(); // Show modal document.getElementById('receiptSettingsModal').style.display = 'flex'; // Add live preview listeners const receiptTextarea = document.getElementById('receiptFooterMessage'); const billTextarea = document.getElementById('billFooterMessage'); receiptTextarea.addEventListener('input', updateReceiptPreview); billTextarea.addEventListener('input', updateBillPreview); } function closeReceiptSettingsModal() { document.getElementById('receiptSettingsModal').style.display = 'none'; // Remove event listeners const receiptTextarea = document.getElementById('receiptFooterMessage'); const billTextarea = document.getElementById('billFooterMessage'); receiptTextarea.removeEventListener('input', updateReceiptPreview); billTextarea.removeEventListener('input', updateBillPreview); } function updateReceiptPreview() { const message = document.getElementById('receiptFooterMessage').value; const preview = document.getElementById('receiptMessagePreview'); preview.textContent = message || 'Thank you for your patronage!'; } function updateBillPreview() { const message = document.getElementById('billFooterMessage').value; const preview = document.getElementById('billMessagePreview'); preview.textContent = message || '(No message set)'; } async function loadFooterMessages() { try { const response = await fetch('api/get_receipt_settings.php'); const result = await response.json(); if (result.success) { // Load receipt message const receiptMessage = result.receipt_message || ''; document.getElementById('receiptFooterMessage').value = receiptMessage; document.getElementById('receiptMessagePreview').textContent = receiptMessage || 'Thank you for your patronage!'; // Load bill message const billMessage = result.bill_message || ''; document.getElementById('billFooterMessage').value = billMessage; document.getElementById('billMessagePreview').textContent = billMessage || '(No message set)'; // Load show order number setting const showOrderNo = document.getElementById('showOrderNoOnReceipt'); if (showOrderNo) { showOrderNo.checked = result.show_order_no === 1; } } } catch (error) { console.error('Error loading footer settings:', error); } } async function saveReceiptSettings() { const receiptMessage = document.getElementById('receiptFooterMessage').value.trim(); const billMessage = document.getElementById('billFooterMessage').value.trim(); const showOrderNo = document.getElementById('showOrderNoOnReceipt')?.checked ? 1 : 0; try { const response = await fetch('api/save_receipt_settings.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ receipt_message: receiptMessage, bill_message: billMessage, show_order_no: showOrderNo }) }); const result = await response.json(); if (result.success) { closeReceiptSettingsModal(); showNotification('Footer notes saved successfully!', 'success'); } else { showNotification(result.message || 'Error saving settings', 'error'); } } catch (error) { console.error('Error saving footer settings:', error); showNotification('Error saving settings. Please try again.', 'error'); } } // ========== Deposits Functions ========== // Store selected deposit data let selectedDeposit = null; function showDeposits() { closeOptionsDialog(); document.getElementById('depositsModal').style.display = 'flex'; loadReservations(); // Set up search input event const searchInput = document.getElementById('depositsSearchInput'); searchInput.value = ''; searchInput.oninput = debounce(function() { loadReservations(this.value); }, 300); // Update display if there's already a selected deposit updateSelectedDepositDisplay(); } function closeDepositsModal() { document.getElementById('depositsModal').style.display = 'none'; } async function loadReservations(searchTerm = '') { const tableBody = document.getElementById('depositsTableBody'); tableBody.innerHTML = 'Loading reservations...'; try { let url = 'api/deposits.php?action=get_reservations'; if (searchTerm) { url += '&search=' + encodeURIComponent(searchTerm); } const response = await fetch(url); const result = await response.json(); if (result.success && result.reservations.length > 0) { let html = ''; result.reservations.forEach(reservation => { const isAvailable = reservation.available_deposit > 0; const depositDisplay = formatCurrency(reservation.deposit); const availableDisplay = formatCurrency(reservation.available_deposit); html += ` ${escapeHtml(reservation.client_name)} ${reservation.res_date} ${reservation.res_time || '-'} ${depositDisplay} ${reservation.used_deposit > 0 ? `
(Available: ${availableDisplay})` : ''} `; }); tableBody.innerHTML = html; } else { tableBody.innerHTML = 'No reservations found'; } } catch (error) { console.error('Error loading reservations:', error); tableBody.innerHTML = 'Error loading reservations'; } } async function selectDeposit(id, clientName, deposit, availableDeposit) { try { // Check if the reservation has sufficient deposit const response = await fetch(`api/deposits.php?action=check_reservation&id=${id}&deposit=${deposit}`); const result = await response.json(); if (result.success) { // Store the selected deposit selectedDeposit = { id: id, client_name: clientName, deposit: deposit, available: availableDeposit }; // Update the display updateSelectedDepositDisplay(); // Close the modal closeDepositsModal(); // Show success notification showNotification(`Deposit selected: ${clientName} - ${formatCurrency(deposit)}`, 'success'); } else { showNotification(result.message || 'Cannot select this deposit - amount has been exceeded.', 'error'); } } catch (error) { console.error('Error selecting deposit:', error); showNotification('Error selecting deposit. Please try again.', 'error'); } } function updateSelectedDepositDisplay() { const displayDiv = document.getElementById('selectedDepositDisplay'); const clientSpan = document.getElementById('selectedDepositClient'); const amountSpan = document.getElementById('selectedDepositAmount'); if (selectedDeposit) { clientSpan.textContent = selectedDeposit.client_name; amountSpan.textContent = formatCurrency(selectedDeposit.deposit); displayDiv.style.display = 'block'; } else { displayDiv.style.display = 'none'; } } function clearSelectedDeposit() { selectedDeposit = null; updateSelectedDepositDisplay(); showNotification('Deposit selection cleared', 'info'); } // Get the selected deposit data (used by settlement functions) function getSelectedDeposit() { return selectedDeposit; } // Clear deposit when table changes function clearDepositOnTableChange() { if (selectedDeposit) { selectedDeposit = null; updateSelectedDepositDisplay(); } } // Helper function for debouncing function debounce(func, wait) { let timeout; return function executedFunction(...args) { const later = () => { clearTimeout(timeout); func.apply(this, args); }; clearTimeout(timeout); timeout = setTimeout(later, wait); }; } // Helper function to escape HTML function escapeHtml(text) { if (!text) return ''; const div = document.createElement('div'); div.textContent = text; return div.innerHTML; } // Helper function to format currency function formatCurrency(amount) { if (amount === null || amount === undefined) return '0.00'; const num = parseFloat(amount); if (isNaN(num)) return '0.00'; return num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); } // Parse a (possibly comma-formatted) money string back to a number. Use this whenever // reading an amount from a displayed element, since displays now include thousands commas. function parseMoney(value) { if (value === null || value === undefined) return 0; const num = parseFloat(String(value).replace(/,/g, '')); return isNaN(num) ? 0 : num; } // ========== Memberships Functions ========== // Check if POS has membership packages and show/hide button async function checkPOSMembershipAccess(posId) { const membershipBtn = document.getElementById('membershipOptionBtn'); if (!membershipBtn) return; try { const response = await fetch(`api/memberships.php?action=check_pos_membership&pos_no=${posId}`); const result = await response.json(); if (result.success && result.exists) { membershipBtn.style.display = 'block'; } else { membershipBtn.style.display = 'none'; } } catch (error) { console.error('Error checking POS membership access:', error); membershipBtn.style.display = 'none'; } } // Store selected membership data let selectedMembership = null; function showMemberships() { closeOptionsDialog(); document.getElementById('membershipsModal').style.display = 'flex'; loadMembershipPackages(); loadMemberships(); // Set up search input event const searchInput = document.getElementById('membershipsSearchInput'); searchInput.value = ''; searchInput.oninput = debounce(function() { loadMemberships(); }, 300); // Set up filter change events document.getElementById('membershipStatusFilter').onchange = function() { loadMemberships(); }; document.getElementById('membershipPackageFilter').onchange = function() { loadMemberships(); }; } function closeMembershipsModal() { document.getElementById('membershipsModal').style.display = 'none'; } async function loadMembershipPackages() { try { const response = await fetch('api/memberships.php?action=get_packages'); const result = await response.json(); if (result.success) { const select = document.getElementById('membershipPackageFilter'); // Keep the first option (All Packages) select.innerHTML = ''; result.packages.forEach(pkg => { const option = document.createElement('option'); option.value = pkg.pkg_id; option.textContent = pkg.pkg_name; select.appendChild(option); }); } } catch (error) { console.error('Error loading membership packages:', error); } } async function loadMemberships() { const tbody = document.getElementById('membershipsTableBody'); tbody.innerHTML = 'Loading memberships...'; try { const search = document.getElementById('membershipsSearchInput').value; const status = document.getElementById('membershipStatusFilter').value; const packageId = document.getElementById('membershipPackageFilter').value; let url = `api/memberships.php?action=get_memberships&status=${status}`; if (search) url += `&search=${encodeURIComponent(search)}`; if (packageId) url += `&package=${packageId}`; const response = await fetch(url); const result = await response.json(); if (result.success && result.memberships.length > 0) { tbody.innerHTML = result.memberships.map(m => { const isExpired = m.is_expired; const rowClass = isExpired ? 'style="background-color: #ffebee;"' : ''; const statusBadge = isExpired ? '(Expired)' : '(Active)'; return ` ${escapeHtml(m.client_name)} ${statusBadge} ${escapeHtml(m.pkg_name)} ${m.start_date || '-'} ${m.end_date || '-'} ${formatCurrency(m.paid)} ${formatCurrency(m.un_paid)} ${m.no_of_appearances || 0} `; }).join(''); } else { tbody.innerHTML = 'No memberships found'; } } catch (error) { console.error('Error loading memberships:', error); tbody.innerHTML = 'Error loading memberships: ' + error.message + ''; } } async function selectMembership(cltPkgId, clientName, pkgName, clientId, pkgId, isExpired) { if (isExpired) { await customAlert('This membership has expired. Please select an active membership.'); return; } try { // Verify membership is still valid const response = await fetch(`api/memberships.php?action=check_membership&clt_pkg_id=${cltPkgId}`); const result = await response.json(); if (result.success) { // Store the selected membership selectedMembership = { clt_pkg_id: cltPkgId, client_name: clientName, pkg_name: pkgName, client_id: clientId, pkg_id: pkgId }; // Update the display updateSelectedMembershipDisplay(); // Close the modal closeMembershipsModal(); showNotification('Membership selected: ' + clientName + ' - ' + pkgName, 'success'); } else { await customAlert(result.message || 'Unable to select membership'); } } catch (error) { console.error('Error selecting membership:', error); showNotification('Error selecting membership. Please try again.', 'error'); } } function updateSelectedMembershipDisplay() { const displayDiv = document.getElementById('selectedMembershipDisplay'); const clientSpan = document.getElementById('selectedMembershipClient'); const packageSpan = document.getElementById('selectedMembershipPackage'); if (selectedMembership) { clientSpan.textContent = selectedMembership.client_name; packageSpan.textContent = selectedMembership.pkg_name; displayDiv.style.display = 'block'; } else { displayDiv.style.display = 'none'; } } function clearSelectedMembership() { selectedMembership = null; updateSelectedMembershipDisplay(); showNotification('Membership selection cleared', 'info'); } // Get the selected membership data (used by settlement functions) function getSelectedMembership() { return selectedMembership; } // Clear membership when table changes function clearMembershipOnTableChange() { if (selectedMembership) { selectedMembership = null; updateSelectedMembershipDisplay(); } } // Call membership attendance function callMembershipAttendance(cltPkgId, clientName, pkgName, clientId, pkgId, isExpired) { if (isExpired) { showNotification('This membership has expired. Cannot record attendance.', 'warning'); return; } // Set up the attendance modal document.getElementById('attendanceClientName').textContent = clientName; document.getElementById('attendancePackageName').textContent = pkgName; document.getElementById('attendanceDate').value = new Date().toISOString().split('T')[0]; document.getElementById('attendanceClientId').value = clientId; document.getElementById('attendancePkgId').value = pkgId; document.getElementById('attendanceCltPkgId').value = cltPkgId; // Set avatar initials const initials = clientName.split(' ').map(w => w.charAt(0).toUpperCase()).slice(0, 2).join(''); document.getElementById('attendanceAvatar').textContent = initials; // Show the attendance modal document.getElementById('membershipAttendanceModal').style.display = 'flex'; } function closeMembershipAttendanceModal() { document.getElementById('membershipAttendanceModal').style.display = 'none'; } async function submitMembershipAttendance() { const clientId = document.getElementById('attendanceClientId').value; const pkgId = document.getElementById('attendancePkgId').value; const cltPkgId = document.getElementById('attendanceCltPkgId').value; const attDate = document.getElementById('attendanceDate').value; if (!clientId || !pkgId || !attDate) { await customAlert('Missing required information'); return; } try { const response = await fetch('api/memberships.php?action=submit_attendance', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ client_id: clientId, pkg_id: pkgId, clt_pkg_id: cltPkgId, att_date: attDate }) }); const result = await response.json(); if (result.success) { const clientName = document.getElementById('attendanceClientName').textContent; const pkgName = document.getElementById('attendancePackageName').textContent; closeMembershipAttendanceModal(); showNotification('Attendance recorded successfully', 'success'); // Print entry pass printEntryPass(clientName, pkgName, attDate); // Refresh the memberships list loadMemberships(); } else { showNotification(result.message || 'Error recording attendance', 'error'); } } catch (error) { console.error('Error submitting attendance:', error); showNotification('Error recording attendance. Please try again.', 'error'); } } // Print Health Club Entry Pass - sends to receipt printer via print-new async function printEntryPass(clientName, packageName, attendanceDate) { const businessName = typeof BUSINESS_NAME !== 'undefined' && BUSINESS_NAME ? BUSINESS_NAME : (document.querySelector('.brand-text h1')?.textContent || 'Health Club'); const businessLogo = typeof BUSINESS_LOGO !== 'undefined' && BUSINESS_LOGO ? BUSINESS_LOGO : ''; const baseUrl = window.location.origin; const logoUrl = businessLogo ? `${baseUrl}/karibu-pms/images/${businessLogo}` : ''; const now = new Date(); const time = now.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' }); const displayDate = new Date(attendanceDate).toLocaleDateString('en-GB', { weekday: 'short', day: '2-digit', month: 'short', year: 'numeric' }); const passNo = Date.now().toString().slice(-6); const passStyles = ``; // Content shared by preview (styled with CSS classes) and printer (parsed as semantic HTML) const passContent = `
${logoUrl ? `` : ''}

${businessName}

ENTRY PASS

Health Club / Fitness Center


Pass No.#${passNo}
Client${clientName}
Package${packageName}
Date${displayDate}
Time In${time}


_______________ _______________
Client Instructor

Valid for date of issue only

Please present this pass to the instructor on duty

`; const printHtml = '' + passStyles + '' + passContent + ''; // Get receipt printer for current POS via print-new const wirelessSetting = typeof WIRELESS_PRINTING_SETTING !== 'undefined' ? WIRELESS_PRINTING_SETTING : 'No'; const printNewBase = wirelessSetting === 'No' ? 'http://localhost/print-new' : '/print-new'; const posNo = currentPOS || ''; let printerId = ''; try { const routingResp = await fetch(printNewBase + '/api/printers.php?action=pos_routing&doc_type=receipt'); const routingData = await routingResp.json(); if (routingData.success && routingData.pos_routing[posNo]) { printerId = routingData.pos_routing[posNo]; } } catch (e) { console.log('Could not load receipt printer assignment:', e.message); } // Open preview window — printing only happens when user clicks Print openEntryPassPreview(passStyles, passContent, printNewBase, printerId, printHtml); } // Open entry pass in a preview window with direct printing function openEntryPassPreview(passStyles, passContent, printNewBase, printerId, printHtml) { const previewStyles = ``; const printWindow = window.open('', '', 'width=350,height=600,scrollbar=no,location=no,resizable=no'); if (!printWindow) { showNotification('Please disable your pop-up blocker to print the entry pass.', 'warning'); return; } printWindow.document.write(` Entry Pass${previewStyles} ${passContent}