/** * Ayula Store POS System * Main JavaScript file for transaction page functionality */ $(document).ready(function() { // Initialize globals initializeGlobals(); // Setup event handlers setupEventHandlers(); // Initialize UI components initializeUI(); // Check and update the "Clear All" button state on page load updateClearCartButtonInitialState(); // Make sure cart functionality is properly initialized ensureCartFunctionalityInitialized(); }); /** * Make sure cart functionality is properly initialized * This acts as a safety measure to ensure critical functions are available */ function ensureCartFunctionalityInitialized() { // Check if key functions exist, if not define them if (typeof setupQuantityControls !== 'function') { console.log('Initializing missing cart functions...'); // Define quantity controls if missing window.setupQuantityControls = function() { // Remove any existing event handlers to prevent duplicates $('.quantity-btn.increment, .quantity-btn.decrement').off('click'); // Setup increment button $('.quantity-btn.increment').on('click', function() { const quantityField = $(this).siblings('.quantity-field'); const currentValue = parseInt(quantityField.val()) || 0; const maxStock = parseInt(quantityField.data('max-stock')) || 99; // Only increment if below max stock if (currentValue < maxStock) { quantityField.val(currentValue + 1); } }); // Setup decrement button $('.quantity-btn.decrement').on('click', function() { const quantityField = $(this).siblings('.quantity-field'); const currentValue = parseInt(quantityField.val()) || 0; // Only decrement if above 1 if (currentValue > 1) { quantityField.val(currentValue - 1); } }); // Handle manual input validation $('.quantity-field').on('change', function() { let value = parseInt($(this).val()) || 0; const maxStock = parseInt($(this).data('max-stock')) || 99; // Ensure value is between 1 and max stock if (value < 1) value = 1; if (value > maxStock) value = maxStock; $(this).val(value); }); // Enable form submission with enter key $('.quantity-field').on('keydown', function(e) { if (e.keyCode === 13) { e.preventDefault(); $(this).closest('form').submit(); } }); }; // Define cart deletion confirmation if missing window.setupCartDeletionConfirmation = function() { // Remove any existing event handlers to prevent duplicates $('.delete-cart-item').off('click'); // Setup delete button click event $('.delete-cart-item').on('click', function(e) { e.preventDefault(); const itemIndex = $(this).data('index'); // Set the confirmation button's href $('#confirm-delete-btn').attr('href', 'index.php?remove_item=' + itemIndex); // Show the confirmation modal if (typeof bootstrap !== 'undefined' && $('#deleteConfirmModal').length) { const deleteModal = new bootstrap.Modal(document.getElementById('deleteConfirmModal')); deleteModal.show(); } else { // Fallback if Bootstrap modal isn't available if (confirm('Apakah Anda yakin ingin menghapus item ini dari keranjang Anda?')) { window.location.href = 'index.php?remove_item=' + itemIndex; } } }); }; // Initialize these functions right away setupQuantityControls(); setupCartDeletionConfirmation(); console.log('Cart functions initialized'); } } /** * Initialize global variables and state */ function initializeGlobals() { // Variables to track selected products window.selectedProducts = []; window.multiSelectToolbar = $('.multi-select-toolbar'); // Store product stock information window.productStock = {}; $('.productset').each(function() { const productId = $(this).data('product-id'); const stockText = $(this).find('.productsetimg h6').text(); const stockValue = parseInt(stockText.replace('Stok: ', '')) || 0; window.productStock[productId] = stockValue; }); } /** * Check and update the "Clear All" button state on page load */ function updateClearCartButtonInitialState() { const cartItemsCount = $('.product-lists').length; console.log('Initial cart items count:', cartItemsCount); // Get the clear cart button const clearCartBtn = $('#clear-cart-btn'); if (cartItemsCount > 0) { // Enable the clear cart button clearCartBtn.attr('href', 'javascript:void(0);') .removeClass('disabled') .css({ 'opacity': '1', 'cursor': 'pointer' }) .off('click') .on('click', function(e) { e.preventDefault(); if (typeof bootstrap !== 'undefined' && $('#clearCartModal').length) { try { const clearModal = new bootstrap.Modal(document.getElementById('clearCartModal')); clearModal.show(); } catch (error) { console.log('Modal error, using fallback:', error); if (confirm('Apakah Anda yakin ingin menghapus semua item dari keranjang Anda?')) { window.location.href = 'index.php?clear_cart=1'; } } } else { if (confirm('Apakah Anda yakin ingin menghapus semua item dari keranjang Anda?')) { window.location.href = 'index.php?clear_cart=1'; } } }); console.log('Clear cart button initially enabled'); } else { // Disable the clear cart button clearCartBtn.attr('href', '#') .addClass('disabled') .css({ 'opacity': '0.5', 'cursor': 'not-allowed' }) .off('click'); console.log('Clear cart button initially disabled'); } } /** * Setup all event handlers for the page */ function setupEventHandlers() { // Product card selection setupProductSelection(); // Toolbar actions setupToolbarActions(); // Setup modal buttons properly setupModalButtons(); } /** * Setup modal buttons for all modals */ function setupModalButtons() { // Delete confirmation modal $('#deleteConfirmModal').on('show.bs.modal', function (event) { // Make sure the confirm delete button is functional $('#confirm-delete-btn').off('click').on('click', function(e) { // Use the href attribute for navigation const href = $(this).attr('href'); if (href) { window.location.href = href; } }); }); // Clear cart modal $('#clearCartModal').on('show.bs.modal', function (event) { // Make sure cancel button closes the modal $('#cancel-clear-cart').off('click').on('click', function() { const clearModal = bootstrap.Modal.getInstance(document.getElementById('clearCartModal')); if (clearModal) { clearModal.hide(); } }); // Make sure confirm button navigates to clear cart action $('#confirm-clear-cart').off('click').on('click', function() { window.location.href = 'index.php?clear_cart=1'; }); }); } /** * Initialize UI components */ function initializeUI() { // Hide all check marks initially $('.check-product i').hide(); // Trigger toggle button click to activate it when page loads setTimeout(function() { $("#toggle_btn").trigger('click'); }, 100); // Focus search field when search icon is clicked $('.responsive-search').on('click', function() { setTimeout(function() { $('input[name="search"]').focus(); }, 100); }); // Focus the page header search field on click $('.product-search-form input[name="search"]').on('click', function() { $(this).focus(); }); // Enable live search functionality setupLiveSearch(); // Enable AJAX category navigation setupCategoryNavigation(); // Initialize cash payment functionality setupCashPayment(); } /** * Setup product selection functionality */ function setupProductSelection() { // Click on product card to toggle selection $('.productset').on('click', function(e) { // Only handle clicks on the card itself, not buttons or links inside if ($(e.target).closest('button, a, form').length === 0) { const productId = $(this).data('product-id'); const checkbox = $(this).find('.product-checkbox'); const isChecked = checkbox.prop('checked'); console.log('Clicked product ID:', productId); // Toggle checkbox checkbox.prop('checked', !isChecked); if (!isChecked) { // Add to selected list and highlight window.selectedProducts.push(productId); $(this).addClass('selected'); $(this).find('.check-product i').show(); } else { // Remove from selected list and unhighlight window.selectedProducts = window.selectedProducts.filter(id => id !== productId); $(this).removeClass('selected'); $(this).find('.check-product i').hide(); } console.log('Selected products:', window.selectedProducts); updateToolbar(); } }); } /** * Setup toolbar action buttons */ function setupToolbarActions() { // Cancel selection button $('#cancel-selection').on('click', function() { // Uncheck all checkboxes and hide check marks $('.product-checkbox').prop('checked', false); $('.productset').removeClass('selected'); $('.check-product i').hide(); window.selectedProducts = []; updateToolbar(); }); // Add selected products to cart $('#add-selected-to-cart').on('click', function() { if (window.selectedProducts.length > 0) { console.log('Adding products to cart:', window.selectedProducts); // Create a form to submit selected products const form = $('