(function( $) {
    // filter course grid
    const updateQueryParams = (url, params) => {
        // Create a URL object from the current URL
        let urlObj = new URL(url);
        
        // Iterate over the params object
        for (let key in params) {
            if (params.hasOwnProperty(key)) {
                // Update or add the parameter
                urlObj.searchParams.set(key, params[key]);
            }
        }
    
        // Update the browser history without reloading the page
        history.replaceState(null, '', urlObj.toString());
    };

    $(document).on('change', '.ilms-courses-filter', function(){
        window['ajax_grid-courses-req'] = jQuery.ajax({
            type: "POST",
            url: proqyz_data.ajaxurl,
            data: {
                "action": "proqyz-ajax-get-courses",
                "order_by": $('#ilms-courses-order-by').val(),
                "course_category": $('#ilms-course-category').val()
            },
            beforeSend: function () {
                if (window['ajax_grid-courses-req'] != null) {
                    window['ajax_grid-courses-req'].abort();
                }
                $('body').addClass('is-course-loading');
                updateQueryParams(window.location.href, {
                    "order_by": $('#ilms-courses-order-by').val(),
                    "course_category": $('#ilms-course-category').val()
                });
            },
            success: function (response) {
                if(response.success){
                    const { has_html, html } = response.success;
                    if( has_html ) {
                        $('.ilms-ajax-courses-list').html(html);
                    }

                }
                $('body').removeClass('is-course-loading');
            },
            error: function (err) {
                $('body').removeClass('is-course-loading');
                if (err.status == 404) {
                    console.warn("404 Auth location !");
                } else if (err.status == 0) {
                    alert("Network Error");
                } else {
                    console.warn(err.message);
                }
            }
        });
    });

})( jQuery);