JezK
Edit File: pause-management.js
jQuery(document).ready(function($) { let selectedDates = []; let maxDates = 0; let preferredDays = []; // Initialize datepicker with basic options first $("#pause-datepicker").datepicker({ dateFormat: "yy-mm-dd", minDate: 1, defaultDate: null, beforeShowDay: function(date) { const day = date.getDay(); const isAvailable = preferredDays.includes(day); return [isAvailable, '', '']; } }); // Open modal when Pause button is clicked $(".pause-tiffin-btn").click(function() { const orderId = $(this).data('order-id'); const startDate = $(this).data('start-date'); const preferredDaysStr = $(this).data('preferred-days'); maxDates = parseInt($(this).data('remaining')); try { preferredDays = convertPreferredDays(preferredDaysStr); if (preferredDays.length === 0) { alert('No valid delivery days found. Please check the preferred days format.'); return; } $("#selected-order-id").val(orderId); // Reset and reinitialize the datepicker try { $("#pause-datepicker").multiDatesPicker('destroy'); } catch(e) { console.log('Datepicker not initialized yet'); } // Get available dates based on preferred days and remaining tiffins const availableDates = getNextAvailableDates(maxDates, preferredDays); // Set up basic datepicker first $("#pause-datepicker").datepicker({ dateFormat: "yy-mm-dd", minDate: 1, maxDate: availableDates[availableDates.length - 1], defaultDate: null, beforeShowDay: function(date) { const day = date.getDay(); const dateString = $.datepicker.formatDate('yy-mm-dd', date); const isAvailable = preferredDays.includes(day); return [isAvailable, isAvailable ? 'available-date' : '', '']; } }); // Then add multiDatesPicker functionality $("#pause-datepicker").multiDatesPicker({ maxPicks: maxDates, defaultDate: null }); // Add custom styling for available dates $("<style>") .prop("type", "text/css") .html(` .available-date a.ui-state-default { background-color: #e8f5e9 !important; border-color: #81c784 !important; } .available-date a.ui-state-default:hover { background-color: #c8e6c9 !important; } .available-date a.ui-state-active { background-color: #4caf50 !important; color: white !important; } .pause-type-options { margin: 15px 0; padding: 10px; background: #f9f9f9; border: 1px solid #ddd; border-radius: 4px; } .pause-type-options label { display: block; margin: 5px 0; } .pause-type-description { font-size: 12px; color: #666; margin-left: 20px; } `) .appendTo("head"); $("#pause-modal").show(); } catch (error) { console.error('Error processing preferred days:', error); alert('There was an error processing the delivery days. Please contact support.'); } }); // Close modal when clicking the close button $(".close").click(function() { $("#pause-modal").hide(); }); // Close modal when clicking outside $(window).click(function(event) { if ($(event.target).is("#pause-modal")) { $("#pause-modal").hide(); } }); // Save pause dates $("#save-pause-dates").click(function() { selectedDates = $("#pause-datepicker").multiDatesPicker('getDates'); if (selectedDates.length === 0) { alert('Please select at least one date to pause.'); return; } if (selectedDates.length > maxDates) { alert(`You can only select up to ${maxDates} dates.`); return; } const orderId = $("#selected-order-id").val(); const pauseType = $('input[name="pause_type"]:checked').val(); const button = $(this); // Disable button to prevent double-clicks button.prop('disabled', true); // Add this before the AJAX call console.log('Selected pause type:', pauseType); $.ajax({ url: pauseManagement.ajaxurl, type: 'POST', data: { action: 'save_pause_dates', order_id: orderId, dates: selectedDates, pause_type: pauseType, nonce: pauseManagement.nonce }, success: function(response) { console.log('AJAX Response:', response); if (response.success) { // Display the message from the server alert(response.data.message || 'Operation completed successfully'); location.reload(); } else { alert(response.data || 'Error saving pause dates'); button.prop('disabled', false); } }, error: function(xhr, status, error) { console.error('Ajax error:', error); alert('Error connecting to server'); button.prop('disabled', false); } }); }); // Resume tiffin button click handler $(document).on('click', '.resume-tiffin-btn', function(e) { e.preventDefault(); if (!confirm('Are you sure you want to resume this tiffin?')) { return; } const orderId = $(this).data('order-id'); const button = $(this); // Disable button to prevent double-clicks button.prop('disabled', true); $.ajax({ url: pauseManagement.ajaxurl, type: 'POST', data: { action: 'resume_tiffin', order_id: orderId, nonce: pauseManagement.nonce }, success: function(response) { if (response.success) { location.reload(); } else { alert(response.data || 'Error resuming tiffin'); button.prop('disabled', false); } }, error: function(xhr, status, error) { console.error('Ajax error:', error); alert('Error connecting to server'); button.prop('disabled', false); } }); }); // Cancel scheduled pause button click handler $(document).on('click', '.cancel-scheduled-pause-btn', function(e) { e.preventDefault(); if (!confirm('Are you sure you want to cancel the scheduled pause?')) { return; } const orderId = $(this).data('order-id'); const button = $(this); // Disable button to prevent double-clicks button.prop('disabled', true); $.ajax({ url: pauseManagement.ajaxurl, type: 'POST', data: { action: 'cancel_scheduled_pause', order_id: orderId, nonce: pauseManagement.nonce }, success: function(response) { if (response.success) { location.reload(); } else { alert(response.data || 'Error canceling scheduled pause'); button.prop('disabled', false); } }, error: function(xhr, status, error) { console.error('Ajax error:', error); alert('Error connecting to server'); button.prop('disabled', false); } }); }); // Helper function to get next available dates function getNextAvailableDates(remainingTiffins, preferredDays) { const availableDates = []; let currentDate = new Date(); currentDate.setDate(currentDate.getDate() + 1); // Start from tomorrow while (availableDates.length < remainingTiffins) { if (preferredDays.includes(currentDate.getDay())) { availableDates.push($.datepicker.formatDate('yy-mm-dd', currentDate)); } currentDate.setDate(currentDate.getDate() + 1); } return availableDates; } // Helper function to convert preferred days string to array function convertPreferredDays(preferredDaysStr) { const daysMap = { 'sunday': 0, 'monday': 1, 'tuesday': 2, 'wednesday': 3, 'thursday': 4, 'friday': 5, 'saturday': 6 }; const days = preferredDaysStr.toLowerCase().split('-').map(day => day.trim()); const result = []; if (days.length === 2) { // Handle range of days const startDay = daysMap[days[0]]; const endDay = daysMap[days[1]]; if (startDay !== undefined && endDay !== undefined) { // Handle the case where the range wraps around the week (e.g., Monday-Sunday) if (startDay > endDay) { // Add days from startDay to Saturday (6) for (let i = startDay; i <= 6; i++) { result.push(i); } // Add days from Sunday (0) to endDay for (let i = 0; i <= endDay; i++) { result.push(i); } } else { // Normal case: Include all days in the range for (let i = startDay; i <= endDay; i++) { result.push(i); } } } } else { // Handle individual days separated by spaces const individualDays = preferredDaysStr.toLowerCase().split(/\s+/); individualDays.forEach(day => { if (daysMap.hasOwnProperty(day.trim())) { result.push(daysMap[day.trim()]); } }); } // Sort the days numerically return result.sort((a, b) => a - b); } });