jQuery(document).ready(function() {
    // Initialize everything on document ready
    initializePage();

    // Re-initialize everything after the popup content is loaded
    $(document).on('cbox_complete', function() {
        initializePage();
    });
	
	
		$(document).on('change', '#period', function() {
			var elmObj = jQuery(this);
			var target = $('#week');
			var period = $(this).val();
			var  eoptionsel = jQuery(this).attr('data-val');
			if(period.length > 0){
				$.ajax({
					url: siteUrl + 'ptg_calendars/getWeeksOptions',
					type: "POST",
					dataType: "json",
					data: {
						period: period, eoption:eoptionsel
					},
					beforeSend: function(){
						elmObj.after('<img src="'+siteUrl+'img/loading20.gif" class="loading" />');
					},
					success: function (response) { 
						jQuery('.loading').remove();
						//var response = $.parseJSON(response); 
						var weeks = response.weeks; 
						if(weeks){
							$('#week').fillSelect(weeks);
							if(eoptionsel=='setsel'){
								$('#week').prepend('<option value="" selected>Select Week</option>');
							}
							$('#week-field').show();
						}else{
							$('#week-field').hide();
						}
						
					},
					error: function (xhr, status) {
						alert("Sorry, there was a problem!");
					},
				});
			}else{
				$('#week-field').hide();
			}
		});
		
		$(document).on('change', '.period-dt', function() { 
			var elmObj = jQuery(this);
			var target = $(this).closest('div').nextAll('.period-wk').first();
			var period = $(this).val();
			if(period.length > 0){
				$.ajax({
					url: siteUrl + 'ptg_calendars/getWeeksOptions',
					type: "POST",
					dataType: "json",
					data: {
						period: period,
					},
					beforeSend: function(){
						elmObj.after('<img src="'+siteUrl+'img/loading20.gif" class="loading" />');
					},
					success: function (response) { 
						jQuery('.loading').remove();
						//var response = $.parseJSON(response); 
						var weeks = response.weeks;
						if(weeks){ 
							target.fillSelect(weeks);
							var isFromToField = $(elmObj).parents('#from-to-fields').length > 0;
							if (isFromToField) {
								target.find('option[value="0"]').text('Select Week');
							}
							 
							target.show();
						}else{
							target.hide();
						}
						
					},
					error: function (xhr, status) {
						alert("Sorry, there was a problem!");
					},
				});
			}else{
				target.hide();
			}
		});

    // Use event delegation to bind submit event to dynamically loaded form
    $(document).on('submit', '#popup-filter-form', function(e) {
        e.preventDefault(); // STOP default action
        
        var ft_count = 0;
        $('.fromto-dt').each(function (res) {
            if(this.value !=''){
                ft_count++;
            }
        });
        
        if( ft_count > 0 && ft_count !=$('.fromto-dt').length){
            alert('Please select both From and To dates.');
            return false;
        }

        var targetField = $('#target-fields');
        if (targetField.length > 0 && targetField.is(':visible')) {
            var targetMonth = $('#month').val();
            if (!targetMonth) {
                alert('Please select Target month.');
                return false;
            }
        }
		
		var fromToFields = $('#from-to-fields');
		if (fromToFields.length > 0 && fromToFields.is(':visible')) {
			var pdt_count = 0;
            $('#from-to-fields .period-dt').each(function (res) {
				
                if(this.value !=''){
                    pdt_count++;
                }
            });
            if( pdt_count != $('#from-to-fields .period-dt').length){
                alert('Please select Period From and To dates first.');
                return false;
            }
			
			var pwk_count = 0;
			$('#from-to-fields .period-wk').each(function (res) {
                if(this.value !='' && this.value !== '0'){
                    pwk_count++;
                }
            });
            if(pwk_count != $('#from-to-fields .period-wk').length){
                alert('Please select Period From and To Weeks first.');
                return false;
            }
			
			// Check if periodtype is 'ptg_cal_range' and years of pfrom and pto are same
			var periodtype = $('#periodtype-select').val();
			if (periodtype === 'ptg_cal_range') {
				var pfrom = $('#pfrom').val();
				var pto = $('#pto').val();

				// Check if both 'pfrom' and 'pto' have values
				if (pfrom && pto) {
					// Extract the year directly from 'pfrom' and 'pto'
					var pfromYear = pfrom.split('-')[0];  // '2025' from '2025-02'
					var ptoYear = pto.split('-')[0];      // '2025' from '2025-02'

					// If the years are different, show the alert and prevent form submission
					if (pfromYear !== ptoYear) {
						alert('Please ensure the Period From and To dates belong to the same year.');
						return false;  // Prevent form submission
					}
				}
			}
		}
		
        
        var postData = $(this).serializeArray();
        var formURL = $(this).attr("action");
        $('#po-submit').after('<img src="'+siteUrl+'img/loading20.gif" class="loading" />');

        $.ajax({
            url : formURL,
            type: "GET",
            data : postData,
            success: function(data, textStatus, jqXHR) {
                $("#popup-container").html(data); // Directly replace content
                $.colorbox.resize();
                initializePage(); // Re-initialize after content replacement
            },
            error: function(jqXHR, textStatus, errorThrown) {
                // Handle errors here
            }
        });
    });

    // Event delegation for pagination links or any other dynamically loaded content
    $(document).on('click', '#popup-container .prev-arrow a, #popup-container .next-arrow a, #popup-container .linksinside li a, #popup-container .popuppaging a', function(e) { 
        e.preventDefault();
        var linkURL = $(this).attr("href");
        
        // Update the URL by removing specified query parameters
        linkURL = removeQueryParams(linkURL, ['periodtype','period', 'week', 'from', 'to']);
        
        $(this).after('<div class="btn-overlay"></div>');
        
        $.get(linkURL, function(data) {
            $("#popup-container").html(data); // Replace content with new data
            $.colorbox.resize();
            initializePage(); // Re-initialize after content replacement
        });
    });
});

function initializePage() { 
    // Re-initialize all necessary functionalities like datepickers and field displays

    initializePeriodTypeFields();

    $("#from-date").datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'yy-mm-dd',
        onClose: function(selectedDate) {
            $("#to-date").datepicker("option", "minDate", selectedDate);
        }
    });

    $("#to-date").datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'yy-mm-dd',
        onClose: function(selectedDate) {
            $("#from-date").datepicker("option", "maxDate", selectedDate);
        }
    });

    $("#period").datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'yy-mm',
        showButtonPanel: true,
        onClose: function(dateText, inst) {
            $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
            $('#period').trigger('change');
        },
    }).focus(function() {
        $(".ui-datepicker-calendar").hide();
        $("#ui-datepicker-div").position({
            my: "center top",
            at: "center bottom",
            of: $(this)
        });
    });
}

function initializePeriodTypeFields() {
    var $periodTypeSelect = $('#periodtype-select');
    var $fromToFields = $('#from-to-fields');
    var $periodField = $('#period-field');
    var $weeksField = $('#week-field');

    var $fromDateInput = $('#from-date');
    var $toDateInput = $('#to-date');
    var $periodInput = $('#period');
    var $weekInput = $('#week');

    // Display date fields on page load
    displayPeriodTypeFields();

    // Update fields on change (bind to document)
    $(document).on('change', '#periodtype-select', displayPeriodTypeFields);

    function displayPeriodTypeFields() {
        var selectedValue = $periodTypeSelect.val();
        if (selectedValue === 'ptg_calendar') {
            $periodField.show();
            //$weeksField.show();
            $fromToFields.hide();

            $fromDateInput.val('');
            $toDateInput.val('');
        } else if (selectedValue === 'date_range') {
            $fromToFields.show();
            $periodField.hide();
            $weeksField.hide();

            $periodInput.val('');
            $weekInput.val('').trigger('change');
        }else if (selectedValue === 'ptg_cal_range') {
            $fromToFields.show();
            $periodField.hide();
            $weeksField.hide();

            $periodInput.val('');
            $weekInput.val('').trigger('change');
        } else {
            $fromToFields.hide();
            $periodField.hide();
            $weeksField.hide();

            // Clear all fields
            /* $fromDateInput.val('');
            $toDateInput.val('');
            $periodInput.val('');
            $weekInput.val('').trigger('change'); */
        }
    }
}

// Helper function to remove query parameters from URL
function removeQueryParams(url, paramsToRemove) {
    var urlObj = new URL(url, window.location.origin);
    var searchParams = new URLSearchParams(urlObj.search);

    paramsToRemove.forEach(function(param) {
        searchParams.delete(param);
    });

    urlObj.search = searchParams.toString();
    return urlObj.toString();
}


