// 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 = '
No debtors found
'; return; } debtors.forEach(debtor => { const item = document.createElement('div'); item.className = 'debtor-item'; const balance = parseFloat(debtor.balance2) || 0; const creditLimit = parseFloat(debtor.debtors_credit_limit) || 0; const totalAmount = settlementData ? settlementData.calculations.total_amount : 0; // Check if credit limit will be exceeded const newBalance = balance + totalAmount; const exceedsLimit = type === 'debtor' && creditLimit > 0 && newBalance > creditLimit; item.innerHTML = `
${debtor.name}
${type === 'staff' ? debtor.staff_department : debtor.debtors_person || ''}
Current Balance: ${fmtMoney(balance)} ${type === 'debtor' && creditLimit > 0 ? ` | Credit Limit: ${fmtMoney(creditLimit)}` : ''}
${exceedsLimit ? '
Warning: Credit limit will be exceeded!
' : ''}
`; if (exceedsLimit) { item.classList.add('exceeds-limit'); } item.addEventListener('click', () => selectDebtor(debtor, type, exceedsLimit)); list.appendChild(item); }); } // Select a debtor async function selectDebtor(debtor, type, exceedsLimit) { if (exceedsLimit) { if (!(await customConfirmSettlement('This transaction will exceed the credit limit. Do you want to continue?'))) { return; } } selectedDebtor = debtor; debtorType = type; // Update UI to show selection document.querySelectorAll('.debtor-item').forEach(item => { item.classList.remove('selected'); }); event.target.closest('.debtor-item').classList.add('selected'); // Close modal and update settlement form closeDebtorModal(); // Update customer name field document.getElementById('customerName').value = debtor.name; document.getElementById('customerName').readOnly = true; // Show confirmation and auto-settle (display is comma-formatted — strip commas) const totalAmount = parseFloat(document.getElementById('settle-total').textContent.replace(/,/g, '')) || 0; const confirmMessage = `Confirm credit sale:\n\nDebtor: ${debtor.name}\nAmount: ${fmtMoney(totalAmount)}\n\nProceed with settlement?`; if (await customConfirmSettlement(confirmMessage)) { // Auto-settle the payment confirmSettlement(); } } // Electronic Payment Functions let electronicPaymentData = null; // Open electronic payment modal async function openElectronicPaymentModal() { const modal = document.getElementById('electronicPaymentModal'); modal.classList.add('active'); // Get total amount const totalAmount = settlementData ? settlementData.calculations.total_amount : 0; document.getElementById('electronicTotalAmount').textContent = fmtMoney(totalAmount); document.getElementById('electronicPendingAmount').textContent = '0.00'; // Reset all inputs and set cash amount to total by default document.getElementById('cashAmount').value = totalAmount.toFixed(2); document.getElementById('cardAmount').value = ''; document.getElementById('mobileAmount').value = ''; document.getElementById('mobileAmount2').value = ''; document.getElementById('cardAccount').value = ''; document.getElementById('cardTransNo').value = ''; document.getElementById('mobileAccount').value = ''; document.getElementById('mobileTransNo').value = ''; document.getElementById('mobileAccount2').value = ''; document.getElementById('mobileTransNo2').value = ''; // Reset Phone Payment 2 section visibility document.getElementById('phonePayment2Section').style.display = 'none'; document.getElementById('btnAddPhonePayment2').style.display = ''; // Make cash amount readonly document.getElementById('cashAmount').readOnly = true; // Disable scroll wheel on card and mobile amount inputs const cardAmountInput = document.getElementById('cardAmount'); const mobileAmountInput = document.getElementById('mobileAmount'); const mobileAmountInput2 = document.getElementById('mobileAmount2'); // Remove existing listeners first to avoid duplicates cardAmountInput.onwheel = function(e) { e.preventDefault(); }; mobileAmountInput.onwheel = function(e) { e.preventDefault(); }; mobileAmountInput2.onwheel = function(e) { e.preventDefault(); }; // Also disable on focus to prevent scroll changes cardAmountInput.addEventListener('focus', function() { this.addEventListener('wheel', preventScroll, { passive: false }); }); cardAmountInput.addEventListener('blur', function() { this.removeEventListener('wheel', preventScroll); }); mobileAmountInput.addEventListener('focus', function() { this.addEventListener('wheel', preventScroll, { passive: false }); }); mobileAmountInput.addEventListener('blur', function() { this.removeEventListener('wheel', preventScroll); }); mobileAmountInput2.addEventListener('focus', function() { this.addEventListener('wheel', preventScroll, { passive: false }); }); mobileAmountInput2.addEventListener('blur', function() { this.removeEventListener('wheel', preventScroll); }); // Load payment accounts await loadPaymentAccounts(); } // Prevent scroll on number inputs function preventScroll(e) { e.preventDefault(); } // Close electronic payment modal function closeElectronicModal() { document.getElementById('electronicPaymentModal').classList.remove('active'); // If modal closed without confirming, deselect electronic payment method if (!electronicPaymentData) { selectedPaymentMethod = null; document.querySelectorAll('.payment-option').forEach(option => { option.classList.remove('selected'); }); } } // Load payment accounts from API async function loadPaymentAccounts() { try { // Load card accounts const cardResponse = await fetch('../../frontdesk/get_venue.php?creditaccount'); // Check if response is OK if (!cardResponse.ok) { console.error('Card account response error:', cardResponse.status); throw new Error(`HTTP error! status: ${cardResponse.status}`); } // Try to parse as JSON regardless of content-type header // (Some PHP endpoints return JSON but with text/html content-type) const cardText = await cardResponse.text(); let cardAccounts; try { cardAccounts = JSON.parse(cardText); } catch (parseError) { console.error('Card account response is not valid JSON:', cardText.substring(0, 200)); throw new Error('Failed to parse card accounts as JSON'); } const cardSelect = document.getElementById('cardAccount'); cardSelect.innerHTML = ''; if (Array.isArray(cardAccounts)) { cardAccounts.forEach(account => { const option = document.createElement('option'); option.value = account.id; option.textContent = account.name; cardSelect.appendChild(option); }); } // Load mobile money accounts const mobileResponse = await fetch('../../frontdesk/get_venue.php?momopay'); // Check if response is OK if (!mobileResponse.ok) { console.error('Mobile money response error:', mobileResponse.status); throw new Error(`HTTP error! status: ${mobileResponse.status}`); } // Try to parse as JSON regardless of content-type header const mobileText = await mobileResponse.text(); let mobileAccounts; try { mobileAccounts = JSON.parse(mobileText); } catch (parseError) { console.error('Mobile money response is not valid JSON:', mobileText.substring(0, 200)); throw new Error('Failed to parse mobile money accounts as JSON'); } const mobileSelect = document.getElementById('mobileAccount'); mobileSelect.innerHTML = ''; const mobileSelect2 = document.getElementById('mobileAccount2'); mobileSelect2.innerHTML = ''; if (Array.isArray(mobileAccounts)) { mobileAccounts.forEach(account => { const option = document.createElement('option'); option.value = account.id; option.textContent = account.name; mobileSelect.appendChild(option); const option2 = document.createElement('option'); option2.value = account.id; option2.textContent = account.name; mobileSelect2.appendChild(option2); }); } } catch (error) { console.error('Error loading payment accounts:', error); showNotification('Failed to load payment accounts. Please check the console for details.', 'error'); } } // Update pending amount as user enters split payments function updatePendingAmount() { const totalAmount = settlementData ? settlementData.calculations.total_amount : 0; const cardAmount = parseFloat(document.getElementById('cardAmount').value) || 0; const mobileAmount = parseFloat(document.getElementById('mobileAmount').value) || 0; const mobileAmount2 = parseFloat(document.getElementById('mobileAmount2').value) || 0; // Calculate remaining amount for cash (total - card - mobile - mobile2) const cashAmount = totalAmount - cardAmount - mobileAmount - mobileAmount2; // Prevent negative cash amount if (cashAmount < 0) { // If card + mobile + mobile2 exceeds total, show error document.getElementById('electronicPendingAmount').textContent = '0.00'; document.getElementById('electronicPendingAmount').style.color = '#ff6b6b'; document.getElementById('cashAmount').value = '0.00'; showNotification('Card and Mobile Money amounts cannot exceed the total amount.', 'warning'); return; } // Update cash amount automatically document.getElementById('cashAmount').value = cashAmount.toFixed(2); // Pending amount is always 0 since cash auto-adjusts const pendingAmount = 0; document.getElementById('electronicPendingAmount').textContent = fmtMoney(pendingAmount); document.getElementById('electronicPendingAmount').style.color = '#51cf66'; } // Confirm electronic payment async function confirmElectronicPayment() { const totalAmount = settlementData ? settlementData.calculations.total_amount : 0; const cashAmount = parseFloat(document.getElementById('cashAmount').value) || 0; const cardAmount = parseFloat(document.getElementById('cardAmount').value) || 0; const mobileAmount = parseFloat(document.getElementById('mobileAmount').value) || 0; const mobileAmount2 = parseFloat(document.getElementById('mobileAmount2').value) || 0; const cardAccount = document.getElementById('cardAccount').value; const cardTransNo = document.getElementById('cardTransNo').value.trim(); const mobileAccount = document.getElementById('mobileAccount').value; const mobileTransNo = document.getElementById('mobileTransNo').value.trim(); const mobileAccount2 = document.getElementById('mobileAccount2').value; const mobileTransNo2 = document.getElementById('mobileTransNo2').value.trim(); // Validate that card + mobile + mobile2 doesn't exceed total if (cardAmount + mobileAmount + mobileAmount2 > totalAmount) { showNotification('Card and Mobile Money amounts cannot exceed the total amount.', 'warning'); return; } // Validate card payment details if (cardAmount > 0 && (!cardAccount || !cardTransNo)) { await customAlert('Please select card account and enter transaction number for card payment.'); return; } // Validate mobile payment details if (mobileAmount > 0 && (!mobileAccount || !mobileTransNo)) { await customAlert('Please select mobile money account and enter transaction number for mobile payment.'); return; } // Validate mobile payment 2 details if (mobileAmount2 > 0 && (!mobileAccount2 || !mobileTransNo2)) { await customAlert('Please select mobile money account and enter transaction number for Mobile Money Payment 2.'); return; } // Store payment data electronicPaymentData = { cashAmount: cashAmount, cardAmount: cardAmount, mobileAmount: mobileAmount, cardAccount: cardAccount, cardTransNo: cardTransNo, mobileAccount: mobileAccount, mobileTransNo: mobileTransNo, mobileAmount2: mobileAmount2, mobileAccount2: mobileAccount2, mobileTransNo2: mobileTransNo2 }; // Close modal closeElectronicModal(); // Auto-settle the payment confirmSettlement(); } // Charge to Room Functions let roomsData = []; let selectedRoomData = null; // Load available rooms from the API async function loadRooms() { try { const response = await fetch('../../frontdesk/getChargetoRoom.php?toposfromfrontdesk=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 rooms data:', responseText.substring(0, 200)); throw new Error('Invalid JSON response from server'); } console.log('Rooms data received:', data); // Debug log if (data.rows && Array.isArray(data.rows)) { roomsData = data.rows; console.log('Number of rooms loaded:', roomsData.length); // Debug log // Check if there are no rooms if (roomsData.length === 0) { await customAlert('There are no checked in rooms at the moment. Confirm that the guest is checked in by the reception.'); // Deselect room payment method selectedPaymentMethod = null; document.querySelectorAll('.payment-option').forEach(option => { option.classList.remove('selected'); }); return; } // Debug: show structure of first room if (roomsData.length > 0) { console.log('First room structure:', roomsData[0]); console.log('First room res_no field:', roomsData[0].res_no); } // Clear search field and show all rooms initially document.getElementById('roomSearch').value = ''; filterRooms(); } else { console.error('No rooms data received'); await customAlert('There are no checked in rooms at the moment. Confirm that the guest is checked in by the reception.'); // Deselect room payment method selectedPaymentMethod = null; document.querySelectorAll('.payment-option').forEach(option => { option.classList.remove('selected'); }); } } catch (error) { console.error('Error loading rooms:', error); showNotification('Failed to load rooms. Please try again.', 'error'); } } // Filter rooms based on search input function filterRooms() { const searchInput = document.getElementById('roomSearch'); const dropdown = document.getElementById('roomDropdown'); if (!searchInput || !dropdown) { console.error('Search input or dropdown element not found!'); return; } if (roomsData.length === 0) { return; } const searchTerm = searchInput.value.toLowerCase(); // Filter rooms based on search term const filteredRooms = roomsData.filter(room => { const roomNo = (room.room_no || '').toString().toLowerCase(); const guestName = (room.guest_name || '').toLowerCase(); return roomNo.includes(searchTerm) || guestName.includes(searchTerm); }); // Clear dropdown dropdown.innerHTML = ''; if (filteredRooms.length === 0) { dropdown.innerHTML = '
No rooms found
'; dropdown.classList.remove('hidden'); return; } // Add header row const header = document.createElement('div'); header.className = 'room-dropdown-header'; header.innerHTML = ` Room Number Guest Name `; dropdown.appendChild(header); // Populate dropdown with filtered rooms filteredRooms.forEach(room => { const item = document.createElement('div'); item.className = 'room-dropdown-item'; item.onclick = () => selectRoom(room); item.innerHTML = ` Room ${room.room_no} ${room.guest_name || 'Unknown Guest'} `; dropdown.appendChild(item); }); dropdown.classList.remove('hidden'); } // Handle room selection function selectRoom(room) { selectedRoomData = room; // Set the hidden input value document.getElementById('roomNo').value = room.room_no; // Set the search input to show selected room document.getElementById('roomSearch').value = `Room ${room.room_no} - ${room.guest_name}`; // Hide dropdown document.getElementById('roomDropdown').classList.add('hidden'); // Display room information (simplified) const roomInfoDiv = document.getElementById('selectedRoomInfo'); roomInfoDiv.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 = '
No events found
'; dropdown.classList.remove('hidden'); return; } // Add header row const header = document.createElement('div'); header.className = 'event-dropdown-header'; header.innerHTML = ` Event Name Organization Pax `; dropdown.appendChild(header); // Populate dropdown with filtered events filteredEvents.forEach(event => { const item = document.createElement('div'); item.className = 'event-dropdown-item'; item.onclick = () => selectEvent(event); item.innerHTML = ` ${event.event_name || 'Unnamed Event'} ${event.event_organization || 'No Organization'} ${event.event_participants || 'N/A'} `; dropdown.appendChild(item); }); dropdown.classList.remove('hidden'); } // Handle event selection function selectEvent(event) { selectedEventData = event; // Set the hidden input value document.getElementById('eventNo').value = event.event_no; // Set the search input to show selected event document.getElementById('eventSearch').value = `${event.event_name} - ${event.event_organization}`; // Hide dropdown document.getElementById('eventDropdown').classList.add('hidden'); // Display event information const eventInfoDiv = document.getElementById('selectedEventInfo'); eventInfoDiv.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 = ''; return; } // Create table structure for dropdown const table = document.createElement('table'); table.className = 'dropdown-table'; table.innerHTML = ` Name House Charge Ledger `; const tbody = table.querySelector('tbody'); accounts.forEach(account => { const row = document.createElement('tr'); row.className = 'dropdown-item-row'; row.onclick = () => selectHouseUseAccount(account); row.innerHTML = ` ${account.user_name} ${account.ledger_name || 'N/A'} `; tbody.appendChild(row); }); dropdownList.appendChild(table); } // Show House Use Dropdown function showHouseUseDropdown() { const dropdownList = document.getElementById('houseUseAccountList'); dropdownList.style.display = 'block'; // Load accounts if not already loaded if (houseUseAccounts.length === 0) { loadHouseUseAccounts(); } } // Filter House Use Accounts function filterHouseUseAccounts() { const searchInput = document.getElementById('houseUseAccountSearch'); const searchTerm = searchInput.value.toLowerCase(); const filtered = houseUseAccounts.filter(account => { return account.user_name.toLowerCase().includes(searchTerm) || (account.ledger_name && account.ledger_name.toLowerCase().includes(searchTerm)); }); renderHouseUseDropdown(filtered); showHouseUseDropdown(); } // Select House Use Account function selectHouseUseAccount(account) { document.getElementById('houseUseAccount').value = account.id; document.getElementById('houseUseAccountSearch').value = account.user_name; document.getElementById('houseUseAccountList').style.display = 'none'; } // Hide dropdown when clicking outside document.addEventListener('click', function(event) { const container = document.querySelector('.searchable-dropdown-container'); const dropdownList = document.getElementById('houseUseAccountList'); if (container && dropdownList && !container.contains(event.target)) { dropdownList.style.display = 'none'; } }); // Toggle House Use Management Modal async function toggleHouseUseManagement() { if (typeof hasPermission === 'function' && !hasPermission('house_use_perm')) { await customAlert('You do not have permission to manage house use accounts.'); return; } const modal = document.getElementById('houseUseManagementModal'); if (!modal) return; modal.style.display = 'flex'; // Load ledgers if not already loaded if (expenseLedgers.length === 0) { await loadExpenseLedgers(); } // Load and display accounts await loadHouseUseAccountsForManagement(); } // Close House Use Management function closeHouseUseManagement() { const modal = document.getElementById('houseUseManagementModal'); if (modal) modal.style.display = 'none'; // Reload the dropdown with updated data loadHouseUseAccounts(); } // Load House Use Accounts for Management Table async function loadHouseUseAccountsForManagement() { try { const response = await fetch('api/house_use_accounts.php?get_house_use_accounts'); const data = await response.json(); if (data.error) { showNotification('Error loading accounts: ' + data.error, 'error'); return; } renderHouseUseManagementTable(data); } catch (error) { console.error('Error loading house use accounts for management:', error); showNotification('Failed to load house use accounts', 'error'); } } // Render House Use Management Table function renderHouseUseManagementTable(accounts) { const tbody = document.getElementById('houseUseTableBody'); tbody.innerHTML = ''; console.log('Rendering', accounts.length, 'accounts'); console.log('Sample account:', accounts[0]); accounts.forEach(account => { const row = createHouseUseRow(account); tbody.appendChild(row); }); } // Create House Use Row function createHouseUseRow(account = null) { const row = document.createElement('tr'); row.dataset.id = account ? account.id : 'new'; row.dataset.mode = account ? 'existing' : 'new'; if (account) { console.log('Creating row for account:', account.user_name, 'ledger_id:', account.ledger_id, 'ledger_name:', account.ledger_name); } const checkboxCell = document.createElement('td'); checkboxCell.innerHTML = ``; const nameCell = document.createElement('td'); nameCell.innerHTML = ``; const ledgerCell = document.createElement('td'); // Create searchable ledger dropdown const ledgerContainer = document.createElement('div'); ledgerContainer.className = 'ledger-search-container'; ledgerContainer.style.position = 'relative'; const ledgerInput = document.createElement('input'); ledgerInput.type = 'text'; ledgerInput.className = 'house-use-input ledger-search-input'; ledgerInput.placeholder = 'Search ledger...'; ledgerInput.autocomplete = 'off'; // Set initial value if account exists const selectedLedger = account ? expenseLedgers.find(l => l.id == account.ledger_id) : null; if (selectedLedger) { ledgerInput.value = selectedLedger.name; ledgerInput.dataset.ledgerId = selectedLedger.id; } // Create dropdown list const ledgerDropdown = document.createElement('div'); ledgerDropdown.className = 'ledger-dropdown-list'; ledgerDropdown.style.display = 'none'; // Focus event - show dropdown ledgerInput.addEventListener('focus', function() { populateLedgerDropdown(ledgerDropdown, expenseLedgers, ledgerInput); ledgerDropdown.style.display = 'block'; }); // Input event - filter ledgers ledgerInput.addEventListener('input', function() { const searchTerm = this.value.toLowerCase(); const filtered = expenseLedgers.filter(ledger => ledger.name.toLowerCase().includes(searchTerm) ); populateLedgerDropdown(ledgerDropdown, filtered, ledgerInput); ledgerDropdown.style.display = 'block'; }); ledgerContainer.appendChild(ledgerInput); ledgerContainer.appendChild(ledgerDropdown); ledgerCell.appendChild(ledgerContainer); row.appendChild(checkboxCell); row.appendChild(nameCell); row.appendChild(ledgerCell); return row; } // Populate Ledger Dropdown for a row function populateLedgerDropdown(dropdown, ledgers, inputElement) { dropdown.innerHTML = ''; if (ledgers.length === 0) { dropdown.innerHTML = '
No ledgers found
'; return; } ledgers.forEach(ledger => { const item = document.createElement('div'); item.className = 'ledger-dropdown-item'; item.textContent = ledger.name; item.dataset.ledgerId = ledger.id; item.addEventListener('click', function() { inputElement.value = ledger.name; inputElement.dataset.ledgerId = ledger.id; dropdown.style.display = 'none'; }); dropdown.appendChild(item); }); } // Hide ledger dropdown when clicking outside document.addEventListener('click', function(event) { const ledgerContainers = document.querySelectorAll('.ledger-search-container'); ledgerContainers.forEach(container => { if (!container.contains(event.target)) { const dropdown = container.querySelector('.ledger-dropdown-list'); if (dropdown) { dropdown.style.display = 'none'; } } }); }); // Add New House Use Row function addNewHouseUseRow() { const tbody = document.getElementById('houseUseTableBody'); const newRow = createHouseUseRow(); tbody.insertBefore(newRow, tbody.firstChild); } // Save House Use Changes async function saveHouseUseChanges() { const tbody = document.getElementById('houseUseTableBody'); const rows = tbody.querySelectorAll('tr'); const savePromises = []; for (let row of rows) { const id = row.dataset.id; const mode = row.dataset.mode; const nameInput = row.querySelector('.house-use-input'); const ledgerInput = row.querySelector('.ledger-search-input'); const name = nameInput ? nameInput.value.trim() : ''; const ledgerId = ledgerInput ? ledgerInput.dataset.ledgerId : ''; if (!name || !ledgerId) { continue; // Skip empty rows } const formData = new FormData(); formData.append('user_name', name); formData.append('ledger_id', ledgerId); if (mode === 'new') { formData.append('isNewRecord', 'true'); } else { formData.append('id', id); } savePromises.push( fetch('api/house_use_accounts.php?update_house_use_account', { method: 'POST', body: formData }) ); } try { await Promise.all(savePromises); await customAlert('Changes saved successfully'); await loadHouseUseAccountsForManagement(); } catch (error) { console.error('Error saving changes:', error); showNotification('Failed to save changes', 'error'); } } // Delete Selected House Use Accounts async function deleteSelectedHouseUse() { const tbody = document.getElementById('houseUseTableBody'); const checkboxes = tbody.querySelectorAll('.row-checkbox:checked'); if (checkboxes.length === 0) { await customAlert('Please select at least one account to delete'); return; } if (!(await customConfirmSettlement(`Are you sure you want to delete ${checkboxes.length} account(s)?`))) { return; } const deletePromises = []; checkboxes.forEach(checkbox => { const row = checkbox.closest('tr'); const id = row.dataset.id; if (id !== 'new') { const formData = new FormData(); formData.append('id', id); deletePromises.push( fetch('api/house_use_accounts.php?destroy_house_use_account', { method: 'POST', body: formData }) ); } else { // Just remove the new row from DOM row.remove(); } }); try { await Promise.all(deletePromises); showNotification('Accounts deleted successfully', 'success'); await loadHouseUseAccountsForManagement(); } catch (error) { console.error('Error deleting accounts:', error); showNotification('Failed to delete accounts', 'error'); } }