// Format an amount with thousands separators + 2 decimals. // Delegates to the global formatCurrency (from selling.js) with a safe fallback. function fmtMoney(amount) { if (typeof formatCurrency === 'function') return formatCurrency(amount); const n = parseFloat(amount); if (isNaN(n)) return '0.00'; return n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); } // Custom confirm modal (reuses the modal from selling.php for PHP Desktop/CEF compatibility) function customConfirmSettlement(message) { return new Promise(resolve => { const overlay = document.getElementById('confirmOverlay'); const msgEl = document.getElementById('confirmMessage'); msgEl.textContent = message; overlay.classList.add('show'); document.getElementById('confirmBtnOk').onclick = () => { overlay.classList.remove('show'); resolve(true); }; document.getElementById('confirmBtnCancel').onclick = () => { overlay.classList.remove('show'); resolve(false); }; }); } // Settlement module let selectedPaymentMethod = null; let settlementData = null; // Payment methods needing a permission beyond 'process'. // Column names match pos_permission / pos/getPosfields.json // ('contemporary' is the legacy spelling for Complimentary). const RESTRICTED_PAYMENT_METHODS = { house: { permission: 'house_charge', label: 'House Use' }, complimentary: { permission: 'contemporary', label: 'Complimentary' } }; // Returns null when allowed, otherwise the restriction that blocked it. function paymentMethodRestriction(method) { const restriction = RESTRICTED_PAYMENT_METHODS[method]; if (!restriction) return null; if (typeof hasPermission === 'function' && !hasPermission(restriction.permission)) { return restriction; } return null; } // Complimentary / House Use write the whole bill off - a discount on top double-counts it. const NO_DISCOUNT_METHODS = { complimentary: 'Complimentary', house: 'House Use' }; // Returns null when allowed, otherwise the label of the method a discount blocked. function discountBlocksMethod(method) { if (!NO_DISCOUNT_METHODS[method]) return null; const discount = settlementData && settlementData.calculations ? parseFloat(settlementData.calculations.discount) || 0 : 0; return discount > 0 ? NO_DISCOUNT_METHODS[method] : null; } // Open settlement modal async function openSettlement() { // Check permission to settle/process payments if (typeof hasPermission === 'function' && !hasPermission('process')) { await customAlert('You do not have permission to settle payments.'); return; } if (cart.length === 0) { await customAlert('Cart is empty. Please add items first.'); return; } const existingOrderId = document.getElementById('existingOrderId').value; if (!existingOrderId) { await customAlert('Please save the order first before settling.'); return; } // Verify res_order.order_amount matches SUM(res_order_item.total_amount) for every // pending order on this table (per POS). Block settlement if any order is out of sync. // #tableId holds res_table.id (PK); the API resolves it to res_order.table_no. try { const tableIdForCheck = document.getElementById('tableId')?.value || ''; if (tableIdForCheck) { const amtResp = await fetch(`api/check_order_amounts.php?table_id=${encodeURIComponent(tableIdForCheck)}`); const amtResult = await amtResp.json(); if (amtResult.success && amtResult.has_mismatch) { const orderList = (amtResult.mismatches || []).map(m => m.order_no).join(', '); await customAlert(`There is a mismatch in order amounts for order number ${orderList}`); return; } } } catch (error) { console.error('Error checking order amounts:', error); await customAlert('Unable to verify order amounts. Please try again.'); return; } // Check if bill must be printed before settlement (Always_print_bills setting) try { const defaultPosNo = typeof currentPOS !== 'undefined' ? currentPOS : document.getElementById('currentPosId')?.value; // Build rows data with item IDs for the check // Use res_order_item_id (the actual res_order_item.id) for bill_print_status check const rows = cart.filter(item => item.order_no && item.isSaved && item.res_order_item_id).map(item => ({ order_no: item.order_no, pos_no: item.pos_id || defaultPosNo, id: item.res_order_item_id })); if (rows.length > 0) { const checkResponse = await fetch('../getKot.php?checkRecieptCriteria', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ rows: rows }) }); const checkResult = await checkResponse.text(); // Result is "1" if all bills printed, "" or "false" if not const allBillsPrinted = checkResult.trim() === '1' || checkResult.trim() === 'true'; if (!allBillsPrinted) { await customAlert('Cannot settle. Please print the bill first. The "Must Print Bill" setting is enabled for this POS.'); return; } } } catch (error) { console.error('Error checking bill print status:', error); // Continue if the check fails - don't block settlement } try { // Fetch settlement details from API const response = await fetch(`api/settlement.php?action=get_settlement_details&order_id=${existingOrderId}`); const result = await response.json(); if (result.success) { settlementData = result; displaySettlementDetails(result); document.getElementById('settlementModal').classList.add('active'); // Show/hide loyalty section if (typeof showLoyaltyInSettlement === 'function') { showLoyaltyInSettlement(); } // Supermarket/retail: default to Cash so the Amount to Receive, // Amount Tendered and Change fields are visible on open. if (typeof IS_SUPERMARKET !== 'undefined' && IS_SUPERMARKET && typeof selectPaymentMethod === 'function') { selectPaymentMethod('cash'); } // Auto-scroll the modal to the bottom so the 'Settle Payment' button // is immediately visible without manual scrolling. requestAnimationFrame(() => { const body = document.querySelector('#settlementModal .settlement-body'); if (body) body.scrollTop = body.scrollHeight; }); } else { showNotification('Error loading settlement details: ' + (result.message || 'Unknown error'), 'error'); } } catch (error) { console.error('Error:', error); showNotification('Error loading settlement details. Please try again.', 'error'); } } // Display settlement details in modal function displaySettlementDetails(data) { const calc = data.calculations; const settings = data.settings || {}; document.getElementById('settle-subtotal').textContent = fmtMoney(calc.subtotal); document.getElementById('settle-service-charge').textContent = fmtMoney(calc.service_charge); document.getElementById('settle-sc-percent').textContent = `(${calc.service_charge_percentage}%)`; document.getElementById('settle-vat').textContent = fmtMoney(calc.vat_amount); document.getElementById('settle-vat-percent').textContent = `(${calc.vat_percentage}%)`; document.getElementById('settle-discount').textContent = fmtMoney(calc.discount); document.getElementById('settle-total').textContent = fmtMoney(calc.total_amount); // Hide subtotal, VAT, and discount rows if hide_subtotal is true (VAT display = "Do not display") // Service charge is always shown if applicable const subtotalRow = document.getElementById('settle-subtotal-row'); const serviceChargeRow = document.getElementById('settle-service-charge-row'); const vatRow = document.getElementById('settle-vat-row'); const discountRow = document.getElementById('settle-discount-row'); if (settings.hide_subtotal) { if (subtotalRow) subtotalRow.style.display = 'none'; if (vatRow) vatRow.style.display = 'none'; if (discountRow) discountRow.style.display = 'none'; // Show service charge row only if there's a service charge amount if (serviceChargeRow) serviceChargeRow.style.display = calc.service_charge > 0 ? '' : 'none'; } else { if (subtotalRow) subtotalRow.style.display = ''; if (serviceChargeRow) serviceChargeRow.style.display = ''; if (vatRow) vatRow.style.display = ''; if (discountRow) discountRow.style.display = ''; } // Set amount received to total by default document.getElementById('amountReceived').value = calc.total_amount.toFixed(2); // Reset form document.getElementById('customerName').value = ''; document.getElementById('customerName').readOnly = false; document.getElementById('selectedClientId').value = ''; document.getElementById('selectedClientTin').value = ''; if (typeof selectedClient !== 'undefined') selectedClient = null; const selectedClientInfoEl = document.getElementById('selectedClientInfo'); if (selectedClientInfoEl) selectedClientInfoEl.classList.add('hidden'); const customerNameGroup = document.getElementById('customerNameGroup'); if (customerNameGroup) customerNameGroup.style.display = ''; document.getElementById('paxServed').value = '1'; document.getElementById('roomNo').value = ''; document.getElementById('eventNo').value = ''; selectedPaymentMethod = null; // Deselect all payment methods document.querySelectorAll('.payment-option').forEach(option => { option.classList.remove('selected'); }); } // Select payment method function selectPaymentMethod(method) { // Guard direct calls — the tiles for restricted methods aren't rendered, // but this function is global and reachable without them. const restriction = paymentMethodRestriction(method); if (restriction) { customAlert(`You do not have permission to post ${restriction.label} settlements.`); return; } // A discounted bill can't be written off as Complimentary / House Use. const discountBlock = discountBlocksMethod(method); if (discountBlock) { customAlert(`You cannot settle an order as a ${discountBlock} when it has a discount. Remove the discount to proceed.`); return; } selectedPaymentMethod = method; // Update UI document.querySelectorAll('.payment-option').forEach(option => { option.classList.remove('selected'); }); document.querySelector(`[data-method="${method}"]`).classList.add('selected'); // Get all form groups const roomNoGroup = document.getElementById('roomNoGroup'); const eventNoGroup = document.getElementById('eventNoGroup'); const mealPlanRoomGroup = document.getElementById('mealPlanRoomGroup'); const complimentaryReasonGroup = document.getElementById('complimentaryReasonGroup'); const houseUseAccountGroup = document.getElementById('houseUseAccountGroup'); const houseUseNoteGroup = document.getElementById('houseUseNoteGroup'); const amountReceivedGroup = document.getElementById('amountReceivedGroup'); const amountToReceiveGroup = document.getElementById('amountToReceiveGroup'); const amountTenderedGroup = document.getElementById('amountTenderedGroup'); const changeGroup = document.getElementById('changeGroup'); // Hide all conditional fields first if (roomNoGroup) roomNoGroup.classList.add('hidden'); if (eventNoGroup) eventNoGroup.classList.add('hidden'); if (mealPlanRoomGroup) mealPlanRoomGroup.classList.add('hidden'); if (complimentaryReasonGroup) complimentaryReasonGroup.classList.add('hidden'); if (houseUseAccountGroup) houseUseAccountGroup.classList.add('hidden'); if (houseUseNoteGroup) houseUseNoteGroup.classList.add('hidden'); if (amountReceivedGroup) amountReceivedGroup.classList.add('hidden'); if (amountToReceiveGroup) amountToReceiveGroup.classList.add('hidden'); if (amountTenderedGroup) amountTenderedGroup.classList.add('hidden'); if (changeGroup) changeGroup.classList.add('hidden'); // Hide Customer Name for methods that auto-fill it (room, event, mealplan, house) const customerNameGroup = document.getElementById('customerNameGroup'); if (customerNameGroup) { const hideCustomerName = ['room', 'event', 'mealplan', 'house'].includes(method); customerNameGroup.style.display = hideCustomerName ? 'none' : ''; } // Show cash-specific fields for cash payment if (method === 'cash') { if (amountToReceiveGroup) amountToReceiveGroup.classList.remove('hidden'); if (amountTenderedGroup) amountTenderedGroup.classList.remove('hidden'); if (changeGroup) changeGroup.classList.remove('hidden'); // Set amount to receive from total (display is comma-formatted — strip commas) const totalAmount = parseFloat(document.getElementById('settle-total').textContent.replace(/,/g, '')) || 0; const amountToReceiveInput = document.getElementById('amountToReceive'); const amountTenderedInput = document.getElementById('amountTendered'); const changeAmountInput = document.getElementById('changeAmount'); if (amountToReceiveInput) amountToReceiveInput.value = totalAmount.toFixed(2); if (amountTenderedInput) amountTenderedInput.value = ''; if (changeAmountInput) changeAmountInput.value = '0.00'; // Cash payment: hide room, event, complimentary, house use sections // (already hidden above, just ensuring they stay hidden) } // Show amount received for electronic (handled in modal) if (method === 'electronic') { // Electronic modal handles its own fields } // Show room field for room charge if (method === 'room') { if (roomNoGroup) roomNoGroup.classList.remove('hidden'); loadRooms(); // Load available rooms // Room charge: hide amount fields, event, meal plan, complimentary, house use sections // (already hidden above, just ensuring they stay hidden) } // Show event field for event charge if (method === 'event') { if (eventNoGroup) eventNoGroup.classList.remove('hidden'); loadEvents(); // Load ongoing events } // Show meal plan room field for meal plan if (method === 'mealplan') { if (mealPlanRoomGroup) mealPlanRoomGroup.classList.remove('hidden'); loadMealPlanRooms(); // Load meal plan rooms } // Show complimentary reason field for complimentary if (method === 'complimentary') { if (complimentaryReasonGroup) complimentaryReasonGroup.classList.remove('hidden'); } // Show house use fields for house use if (method === 'house') { if (houseUseAccountGroup) houseUseAccountGroup.classList.remove('hidden'); if (houseUseNoteGroup) houseUseNoteGroup.classList.remove('hidden'); // Clear search input and load house use accounts automatically const searchInput = document.getElementById('houseUseAccountSearch'); if (searchInput) searchInput.value = ''; // Load and display house use accounts automatically loadHouseUseAccounts().then(() => { // Show the dropdown list by default const dropdownList = document.getElementById('houseUseAccountList'); if (dropdownList) { dropdownList.style.display = 'block'; } }); } // Handle credit sale - show debtor selection modal if (method === 'credit') { openDebtorSelectionModal(); } // Handle electronic payment - show combined payment options if (method === 'electronic') { openElectronicPaymentModal(); } // Auto-scroll to payment details section setTimeout(() => { const paymentDetailsSection = document.getElementById('paymentDetailsSection'); if (paymentDetailsSection) { paymentDetailsSection.scrollIntoView({ behavior: 'smooth', block: 'start' }); } }, 100); } // Calculate change for cash payments function calculateChange() { const amountToReceive = parseFloat(document.getElementById('amountToReceive').value) || 0; const amountTendered = parseFloat(document.getElementById('amountTendered').value) || 0; const change = amountTendered - amountToReceive; document.getElementById('changeAmount').value = change.toFixed(2); } // Close settlement modal function closeSettlementModal() { document.getElementById('settlementModal').classList.remove('active'); settlementData = null; selectedPaymentMethod = null; // Clear deposit selection when settlement modal is closed if (typeof clearDepositOnTableChange === 'function') { clearDepositOnTableChange(); } } // Confirm settlement async function confirmSettlement() { if (!selectedPaymentMethod) { await customAlert('Please select a payment method.'); return; } // Re-check in case the method was set by something other than selectPaymentMethod const methodRestriction = paymentMethodRestriction(selectedPaymentMethod); if (methodRestriction) { await customAlert(`You do not have permission to post ${methodRestriction.label} settlements.`); return; } let customerName = document.getElementById('customerName').value.trim(); const paxServed = document.getElementById('paxServed').value; let amountReceived = document.getElementById('amountReceived').value; // Changed to let for cash payment reassignment const roomNo = document.getElementById('roomNo').value.trim(); const eventNo = document.getElementById('eventNo').value.trim(); const mealPlanRoomId = document.getElementById('mealPlanRoomId').value.trim(); const complimentaryReason = document.getElementById('complimentaryReason').value.trim(); const houseUseAccount = document.getElementById('houseUseAccount').value.trim(); const houseUseNote = document.getElementById('houseUseNote').value.trim(); const existingOrderId = document.getElementById('existingOrderId').value; // Customer name must come from a selected client in the dropdown (not free-typed text). // Methods that auto-fill customer name (room, event, mealplan, house, credit) are excluded. const autoFilledMethods = ['room', 'event', 'mealplan', 'house', 'credit']; if (!autoFilledMethods.includes(selectedPaymentMethod)) { const selectedClientId = document.getElementById('selectedClientId').value; if (!selectedClientId) { // No valid client selected from dropdown - clear any typed text customerName = ''; document.getElementById('customerName').value = ''; } } // Set default customer name to 'Cash' for non-debtor payments if (!customerName && selectedPaymentMethod !== 'credit' && selectedPaymentMethod !== 'room' && selectedPaymentMethod !== 'event' && selectedPaymentMethod !== 'mealplan' && selectedPaymentMethod !== 'complimentary' && selectedPaymentMethod !== 'house') { customerName = 'Cash'; } // Validate required fields based on payment method if (selectedPaymentMethod === 'room' && !roomNo) { await customAlert('Please select a room.'); return; } if (selectedPaymentMethod === 'event' && !eventNo) { await customAlert('Please enter an event number.'); return; } if (selectedPaymentMethod === 'mealplan' && !mealPlanRoomId) { await customAlert('Please select a room for meal plan.'); return; } // A discount may have been applied after the payment method tile was selected. const discountBlock = discountBlocksMethod(selectedPaymentMethod); if (discountBlock) { await customAlert(`You cannot settle an order as a ${discountBlock} when it has a discount. Remove the discount to proceed.`); return; } if (selectedPaymentMethod === 'complimentary' && !customerName) { await customAlert('Please select a customer name from the dropdown for complimentary orders.'); return; } if (selectedPaymentMethod === 'complimentary' && !complimentaryReason) { await customAlert('Please enter a reason for complimentary.'); return; } if (selectedPaymentMethod === 'house' && !houseUseAccount) { await customAlert('Please select a house use account.'); return; } if (selectedPaymentMethod === 'house' && !houseUseNote) { await customAlert('Please enter a house use note.'); return; } // Validate cash payment if (selectedPaymentMethod === 'cash') { const amountToReceive = parseFloat(document.getElementById('amountToReceive').value) || 0; const amountTenderedInput = document.getElementById('amountTendered').value.trim(); // Amount tendered is optional - if not provided, assume exact payment let amountTendered = 0; if (amountTenderedInput === '' || amountTenderedInput === null) { // If not entered, assume exact amount (no change) amountTendered = amountToReceive; } else { amountTendered = parseFloat(amountTenderedInput) || 0; // Only validate if amount was entered if (amountTendered < amountToReceive) { await customAlert('Amount tendered must be greater than or equal to amount to receive.'); return; } } // For cash, amount_received is the full amount (change is given back) amountReceived = amountToReceive; } if (selectedPaymentMethod === 'electronic' && !amountReceived) { await customAlert('Please enter the amount received.'); return; } // Validate credit sale if (selectedPaymentMethod === 'credit' && !selectedDebtor) { await customAlert('Please select a debtor for credit sale.'); return; } // Validate electronic payment if (selectedPaymentMethod === 'electronic' && !electronicPaymentData) { await customAlert('Please configure electronic payment split.'); return; } // Get customer TIN from hidden input (set when customer is selected from dropdown) const customerTinInput = document.getElementById('selectedClientTin'); const customerTin = customerTinInput ? customerTinInput.value : ''; // Get deposit data if selected (from selling.js) const depositData = typeof getSelectedDeposit === 'function' ? getSelectedDeposit() : null; // Get membership data if selected (from selling.js) const membershipData = typeof getSelectedMembership === 'function' ? getSelectedMembership() : null; // Get redeemable data if selected (from selling.js) const redeemableData = typeof getSelectedRedeemable === 'function' ? getSelectedRedeemable() : null; // Get loyalty data if selected (from selling.js) const loyaltyMember = typeof getSelectedLoyaltyMember === 'function' ? getSelectedLoyaltyMember() : null; const loyaltyRedemptionData = typeof getLoyaltyRedemption === 'function' ? getLoyaltyRedemption() : null; // Get selected client ID (from Customer Name dropdown) const selectedClientIdInput = document.getElementById('selectedClientId'); const selectedClientId = selectedClientIdInput ? selectedClientIdInput.value : ''; // Prepare settlement data const settlementPayload = { action: 'settle_order', order_id: existingOrderId, payment_method: selectedPaymentMethod, customer_name: customerName, customer_tin: customerTin, client_id: selectedClientId, pax_served: paxServed, amount_received: amountReceived, room_no: roomNo, event_no: eventNo, res_no: selectedRoomData ? selectedRoomData.res_no : null, // Reservation number (event_no) guest_res_no: selectedRoomData ? selectedRoomData.id : null, // Guest reservation ID mealplan_room_id: mealPlanRoomId, mealplan_room_data: selectedMealPlanRoomData || null, complimentary_reason: complimentaryReason, house_use_account: houseUseAccount, house_use_note: houseUseNote, debtor_id: selectedDebtor ? selectedDebtor.id : null, pos_debtor_id: selectedDebtor ? selectedDebtor.pos_debtor_id : null, debtor_type: debtorType, electronic_data: electronicPaymentData, deposit_data: depositData, membership_data: membershipData, redeemable_data: redeemableData, loyalty_member: loyaltyMember, loyalty_redemption: loyaltyRedemptionData }; // Debug log for room charges if (selectedPaymentMethod === 'room') { console.log('Room charge settlement data:', { room_no: roomNo, res_no: selectedRoomData ? selectedRoomData.res_no : null, customer_name: customerName, selectedRoomData: selectedRoomData }); // Alert to show data before redirect if (!selectedRoomData || !selectedRoomData.res_no) { showNotification('WARNING: res_no is missing!\nselectedRoomData: ' + JSON.stringify(selectedRoomData), 'warning'); } } try { const response = await fetch('api/settlement.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(settlementPayload) }); const responseText = await response.text(); let result; try { result = JSON.parse(responseText); } catch (parseError) { console.error('Failed to parse response:', responseText); showNotification('Server error: ' + responseText.substring(0, 500), 'error'); return; } if (result.success) { // Capture all settlement context BEFORE closing modal (which resets globals) const settledPaymentMethod = selectedPaymentMethod; const settleContext = { method: selectedPaymentMethod, roomNo: document.getElementById('roomNo')?.value || '', eventName: selectedEventData ? (selectedEventData.event_name || '') : '', mealPlanRoomNo: selectedMealPlanRoomData ? (selectedMealPlanRoomData.room_no || '') : '', complimentaryReason: document.getElementById('complimentaryReason')?.value || '' }; closeSettlementModal(); // Check if EFRIS is ON and receipt printing is blocked due to missing EFRIS data if (result.efris_status === 'On' && result.efris_receipt_allowed === false) { showNotification('Cannot print receipt. EFRIS is enabled but the order did not receive a QR code, FDN, or verification code. Please check your EFRIS configuration.', 'warning'); // Settlement succeeded. Supermarket/retail stays put and refreshes // the Av.Qty column; other modes return to the tables view. if (typeof IS_SUPERMARKET !== 'undefined' && IS_SUPERMARKET && typeof resetForNextSupermarketSale === 'function') { resetForNextSupermarketSale(); } else { cart = []; updateCartDisplay(); setTimeout(() => { window.location.href = 'tables.php'; }, 1500); } return; } // Calculate change for cash payments let changeAmount = 0; let amountTendered = 0; if (settledPaymentMethod === 'cash') { const amountTenderedInput = document.getElementById('amountTendered').value.trim(); amountTendered = parseFloat(amountTenderedInput) || parseFloat(amountReceived); changeAmount = amountTendered - parseFloat(amountReceived); if (changeAmount < 0) changeAmount = 0; } // Automatically print receipt for cash settlement if (settledPaymentMethod === 'cash') { printCashReceipt(result, customerName, amountReceived, amountTendered, changeAmount); } else { // For other payment methods, also print receipt automatically printReceipt(result, settleContext); } // Supermarket/retail: stay on the selling screen, refresh the Av.Qty // column and ready up for the next sale. Other modes: return to tables. if (typeof IS_SUPERMARKET !== 'undefined' && IS_SUPERMARKET && typeof resetForNextSupermarketSale === 'function') { resetForNextSupermarketSale(); } else { cart = []; updateCartDisplay(); setTimeout(() => { window.location.href = 'tables.php'; }, 1500); } } else { showNotification('Error settling payment: ' + (result.message || 'Unknown error'), 'error'); } } catch (error) { console.error('Error:', error); showNotification('Error settling payment. Please try again.', 'error'); } } // Print receipt for non-cash settlements (using v2 receipt system) function printReceipt(result, ctx) { const tableNo = document.getElementById('tableNo').value; const posNo = currentPOS || document.getElementById('currentPosId')?.value; // Get the order_no from cart items let orderNo = null; for (const item of cart) { if (item.order_no) { orderNo = item.order_no; break; } } if (!orderNo) { console.log('No order number found'); return; } const receiptNo = result.receipt_no || ''; // Check global AUTO_PRINT_SETTING - if Yes, add auto_print parameter const isAutoMode = (typeof AUTO_PRINT_SETTING !== 'undefined' && AUTO_PRINT_SETTING === 'Yes'); const autoPrintParam = isAutoMode ? '&auto_print=auto_print' : ''; // Build settlement context params for receipt customization let contextParams = ''; if (ctx && ctx.method) { contextParams += `&payment_method=${encodeURIComponent(ctx.method)}`; if (ctx.method === 'room' && ctx.roomNo) contextParams += `&room_no=${encodeURIComponent(ctx.roomNo)}`; if (ctx.method === 'event' && ctx.eventName) contextParams += `&event_name=${encodeURIComponent(ctx.eventName)}`; if (ctx.method === 'mealplan' && ctx.mealPlanRoomNo) contextParams += `&room_no=${encodeURIComponent(ctx.mealPlanRoomNo)}`; if (ctx.method === 'complimentary' && ctx.complimentaryReason) contextParams += `&comp_reason=${encodeURIComponent(ctx.complimentaryReason)}`; } // Use v2 receipt system const receiptUrl = `print/receipt.php?receipt_no=${receiptNo}&order_no=${orderNo}&pos_no=${posNo}&table_no=${tableNo}${autoPrintParam}${contextParams}`; window.open(receiptUrl, 'Receipt', 'width=400,height=700,scrollbars=yes,resizable=yes'); } // Print cash receipt (using v2 receipt system) function printCashReceipt(result, customerName, amountReceived, amountTendered, changeAmount) { const tableNo = document.getElementById('tableNo').value; const posNo = currentPOS || document.getElementById('currentPosId')?.value; // Get the order_no from cart items let orderNo = null; for (const item of cart) { if (item.order_no) { orderNo = item.order_no; break; } } if (!orderNo) { console.log('No order number found'); return; } const receiptNo = result.receipt_no || ''; // Encode customer name for URL (handle special characters) let encodedCustomerName = ''; try { encodedCustomerName = btoa(customerName || 'Cash'); } catch (e) { encodedCustomerName = btoa('Cash'); } // Check global AUTO_PRINT_SETTING - if Yes, add auto_print parameter const isAutoMode = (typeof AUTO_PRINT_SETTING !== 'undefined' && AUTO_PRINT_SETTING === 'Yes'); const autoPrintParam = isAutoMode ? '&auto_print=auto_print' : ''; // Use v2 receipt system with cash-specific parameters const receiptUrl = `print/receipt.php?receipt_no=${receiptNo}&order_no=${orderNo}&pos_no=${posNo}&table_no=${tableNo}` + `&customer_name=${encodedCustomerName}` + `&Tendered=${amountTendered}` + `&Change=${changeAmount}${autoPrintParam}`; window.open(receiptUrl, 'Receipt', 'width=400,height=700,scrollbars=yes,resizable=yes'); } // Credit Sale Functions let selectedDebtor = null; let debtorType = null; // 'staff' or 'debtor' let allDebtors = []; // Store all debtors for search // Open debtor selection modal async function openDebtorSelectionModal() { const modal = document.getElementById('debtorSelectionModal'); modal.classList.add('active'); // Reset selection selectedDebtor = null; debtorType = null; allDebtors = []; // Clear previous selections document.querySelectorAll('.debtor-type-option').forEach(option => { option.classList.remove('selected'); }); document.getElementById('debtorListContainer').style.display = 'none'; document.getElementById('debtorList').innerHTML = ''; // Clear search input const searchInput = document.getElementById('debtorSearchInput'); if (searchInput) { searchInput.value = ''; } } // Close debtor selection modal function closeDebtorModal() { document.getElementById('debtorSelectionModal').classList.remove('active'); // If no debtor was selected, deselect credit payment method if (!selectedDebtor) { selectedPaymentMethod = null; document.querySelectorAll('.payment-option').forEach(option => { option.classList.remove('selected'); }); } } // Select debtor type (staff or other debtor) async function selectDebtorType(type) { debtorType = type; // Update UI document.querySelectorAll('.debtor-type-option').forEach(option => { option.classList.remove('selected'); }); document.querySelector(`[data-debtor-type="${type}"]`).classList.add('selected'); // Fetch and display debtors await loadDebtors(type); } // Load debtors based on type async function loadDebtors(type) { try { const action = type === 'staff' ? 'getStaff' : 'getDebtors'; const response = await fetch(`api/debtors.php?action=${action}`); const debtors = await response.json(); allDebtors = debtors; displayDebtors(debtors, type); setupDebtorSearch(type); } catch (error) { console.error('Error loading debtors:', error); showNotification('Error loading debtors. Please try again.', 'error'); } } // Setup search functionality function setupDebtorSearch(type) { const searchInput = document.getElementById('debtorSearchInput'); // Remove existing event listeners by cloning and replacing const newSearchInput = searchInput.cloneNode(true); searchInput.parentNode.replaceChild(newSearchInput, searchInput); newSearchInput.addEventListener('input', function(e) { const searchTerm = e.target.value.toLowerCase().trim(); if (searchTerm === '') { displayDebtors(allDebtors, type); return; } const filteredDebtors = allDebtors.filter(debtor => { const name = (debtor.name || '').toLowerCase(); const contact = (debtor.contact || '').toLowerCase(); const email = (debtor.email || '').toLowerCase(); if (type === 'staff') { const department = (debtor.staff_department || '').toLowerCase(); return name.includes(searchTerm) || contact.includes(searchTerm) || email.includes(searchTerm) || department.includes(searchTerm); } else { const person = (debtor.debtors_person || '').toLowerCase(); return name.includes(searchTerm) || contact.includes(searchTerm) || email.includes(searchTerm) || person.includes(searchTerm); } }); displayDebtors(filteredDebtors, type); }); } // Display debtors in the list function displayDebtors(debtors, type) { const container = document.getElementById('debtorListContainer'); const list = document.getElementById('debtorList'); container.style.display = 'block'; list.innerHTML = ''; if (!debtors || debtors.length === 0) { list.innerHTML = '
Room: ${room.room_no}
Guest: ${room.guest_name || 'Unknown'}
`; roomInfoDiv.classList.remove('hidden'); // Auto-fill customer name with guest name const customerNameInput = document.getElementById('customerName'); if (!customerNameInput.value || customerNameInput.value === 'Cash') { customerNameInput.value = room.guest_name || 'Unknown Guest'; } } // Close dropdown when clicking outside document.addEventListener('click', function(event) { const roomNoGroup = document.getElementById('roomNoGroup'); const roomDropdown = document.getElementById('roomDropdown'); const eventNoGroup = document.getElementById('eventNoGroup'); const eventDropdown = document.getElementById('eventDropdown'); if (roomNoGroup && roomDropdown && !roomNoGroup.contains(event.target)) { roomDropdown.classList.add('hidden'); } if (eventNoGroup && eventDropdown && !eventNoGroup.contains(event.target)) { eventDropdown.classList.add('hidden'); } }); // Charge to Event Functions let eventsData = []; let selectedEventData = null; // Load ongoing events from the API async function loadEvents() { try { const response = await fetch('../../events/getOngoing.php?getOngoing=1', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'page=1&rows=1000' }); const responseText = await response.text(); let data; try { data = JSON.parse(responseText); } catch (parseError) { console.error('Failed to parse events data:', responseText.substring(0, 200)); throw new Error('Invalid JSON response from server'); } console.log('Events data received:', data); if (data.rows && Array.isArray(data.rows)) { eventsData = data.rows; console.log('Number of events loaded:', eventsData.length); // Check if there are no events if (eventsData.length === 0) { await customAlert('There is no ongoing events'); // Deselect event payment method selectedPaymentMethod = null; document.querySelectorAll('.payment-option').forEach(option => { option.classList.remove('selected'); }); return; } // Clear search field and show all events initially document.getElementById('eventSearch').value = ''; filterEvents(); } else { console.error('No events data received'); await customAlert('There is no ongoing events'); // Deselect event payment method selectedPaymentMethod = null; document.querySelectorAll('.payment-option').forEach(option => { option.classList.remove('selected'); }); } } catch (error) { console.error('Error loading events:', error); showNotification('Failed to load events. Please try again.', 'error'); } } // Filter events based on search input function filterEvents() { const searchInput = document.getElementById('eventSearch'); const dropdown = document.getElementById('eventDropdown'); if (!searchInput || !dropdown) { console.error('Search input or dropdown element not found!'); return; } if (eventsData.length === 0) { return; } const searchTerm = searchInput.value.toLowerCase(); // Filter events based on search term const filteredEvents = eventsData.filter(event => { const eventName = (event.event_name || '').toLowerCase(); const eventOrg = (event.event_organization || '').toLowerCase(); const eventNo = (event.event_no || '').toString().toLowerCase(); return eventName.includes(searchTerm) || eventOrg.includes(searchTerm) || eventNo.includes(searchTerm); }); // Clear dropdown dropdown.innerHTML = ''; if (filteredEvents.length === 0) { dropdown.innerHTML = 'Event: ${event.event_name || 'Unnamed Event'}
Organization: ${event.event_organization || 'No Organization'}
Participants: ${event.event_participants || 'N/A'}
`; eventInfoDiv.classList.remove('hidden'); // Auto-fill customer name with organization name const customerNameInput = document.getElementById('customerName'); if (!customerNameInput.value || customerNameInput.value === 'Cash') { customerNameInput.value = event.event_organization || 'Event'; } } // Meal Plan Room Functions let mealPlanRoomsData = []; let selectedMealPlanRoomData = null; // Load meal plan rooms from the API async function loadMealPlanRooms() { try { const response = await fetch('../../frontdesk/getChargetoRoom.php?getAccMealPlan=1', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'page=1&rows=1000' }); const responseText = await response.text(); let data; try { data = JSON.parse(responseText); } catch (jsonError) { console.error('Failed to parse meal plan rooms response:', responseText); await customAlert('Error loading meal plan rooms: Invalid response format'); return; } if (data && data.rows && Array.isArray(data.rows)) { mealPlanRoomsData = data.rows; console.log('Loaded meal plan rooms:', mealPlanRoomsData); if (mealPlanRoomsData.length === 0) { await customAlert('No rooms found. Confirm that the guest is checked in and has a meal plan.'); selectedPaymentMethod = null; document.querySelectorAll('.payment-option').forEach(option => { option.classList.remove('selected'); }); return; } // Auto-show dropdown when rooms are loaded filterMealPlanRooms(); } else { console.error('Unexpected meal plan rooms data structure:', data); await customAlert('Error loading meal plan rooms'); } } catch (error) { console.error('Error loading meal plan rooms:', error); await customAlert('Failed to load meal plan rooms'); } } // Filter meal plan rooms based on search input function filterMealPlanRooms() { const searchValue = document.getElementById('mealPlanRoomSearch').value.toLowerCase(); const dropdown = document.getElementById('mealPlanRoomDropdown'); // Clear dropdown dropdown.innerHTML = ''; // Filter rooms based on search const filteredRooms = mealPlanRoomsData.filter(room => { const roomNo = (room.room_no || '').toString().toLowerCase(); const guestName = (room.guest_name || '').toLowerCase(); const mealPlan = (room.service_name || '').toLowerCase(); return roomNo.includes(searchValue) || guestName.includes(searchValue) || mealPlan.includes(searchValue); }); if (filteredRooms.length === 0) { const noResults = document.createElement('div'); noResults.className = 'no-results'; noResults.textContent = 'No rooms found'; dropdown.appendChild(noResults); dropdown.classList.remove('hidden'); return; } // Add header row const header = document.createElement('div'); header.className = 'mealplan-room-dropdown-header'; header.innerHTML = ` Room No Guest Name Pax Meal Plan `; dropdown.appendChild(header); // Populate dropdown with filtered rooms filteredRooms.forEach(room => { const item = document.createElement('div'); item.className = 'mealplan-room-dropdown-item'; item.onclick = () => selectMealPlanRoom(room); item.innerHTML = ` Room ${room.room_no} ${room.guest_name || 'Unknown Guest'} ${room.room_pax || room.adult_no || 'N/A'} ${room.service_name || 'No Meal Plan'} `; dropdown.appendChild(item); }); dropdown.classList.remove('hidden'); } // Handle meal plan room selection function selectMealPlanRoom(room) { selectedMealPlanRoomData = room; // Set the hidden input value document.getElementById('mealPlanRoomId').value = room.id; // Set the search input to show selected room document.getElementById('mealPlanRoomSearch').value = `Room ${room.room_no} - ${room.guest_name}`; // Hide dropdown document.getElementById('mealPlanRoomDropdown').classList.add('hidden'); // Display room information const roomInfoDiv = document.getElementById('selectedMealPlanRoomInfo'); roomInfoDiv.innerHTML = `Room: ${room.room_no}
Guest: ${room.guest_name || 'Unknown Guest'}
Pax: ${room.room_pax || room.adult_no || 'N/A'}
Meal Plan: ${room.service_name || 'No Meal Plan'}
Days: ${room.no_of_days || 'N/A'}
`; roomInfoDiv.classList.remove('hidden'); // Auto-fill customer name with guest name const customerNameInput = document.getElementById('customerName'); if (!customerNameInput.value || customerNameInput.value === 'Cash') { customerNameInput.value = room.guest_name || 'Guest'; } } // House Use Functions let houseUseAccounts = []; let expenseLedgers = []; // Load House Use Accounts async function loadHouseUseAccounts() { try { const response = await fetch('api/house_use_accounts.php?get_house_use_accounts'); const data = await response.json(); if (data.error) { console.error('Error loading house use accounts:', data.error); return; } houseUseAccounts = data; renderHouseUseDropdown(houseUseAccounts); } catch (error) { console.error('Error loading house use accounts:', error); } } // Load Expense Ledgers async function loadExpenseLedgers() { try { const response = await fetch('api/house_use_accounts.php?get_expense_ledgers'); const data = await response.json(); if (data.error) { console.error('Error loading expense ledgers:', data.error); showNotification('Error loading expense ledgers: ' + data.error, 'error'); return; } expenseLedgers = data; console.log('Loaded expense ledgers:', expenseLedgers.length, 'items'); console.log('First 3 ledgers:', expenseLedgers.slice(0, 3)); } catch (error) { console.error('Error loading expense ledgers:', error); showNotification('Failed to load expense ledgers: ' + error.message, 'error'); } } // Render House Use Dropdown function renderHouseUseDropdown(accounts) { const dropdownList = document.getElementById('houseUseAccountList'); dropdownList.innerHTML = ''; if (accounts.length === 0) { dropdownList.innerHTML = '