(function ($) {
    toastr.options = {
        "closeButton": false,
        "debug": false,
        "newestOnTop": true,
        "progressBar": true,
        "positionClass": "toast-top-right",
        "preventDuplicates": false,
        "onclick": null,
        "showDuration": "300",
        "hideDuration": "1000",
        "timeOut": "5000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    }

    $(document).on('click', '.proqyz-create_group-btn', function () {
        let btn = $(this);
        let tmp = btn.html();
        $.ajax({
            url: '/wp-admin/admin-ajax.php',
            method: 'POST',
            data: {
                "action": 'proqyz-get-group-modal',
                "type": 'new'
            },
            beforeSend: function () {
                btn.prop('disabled', true);
                btn.html('Loading...');
            },
            success: function (res) {
                if (res.success) {
                    if (res.success.has_html) {

                        $('#modal-group .modal-content').html(res.success.html);
                        $('#modal-group').modal('show');

                    }
                }
            },
            error: function (err) {

            }
        }).always(() => {
            btn.prop('disabled', false);
            btn.html(tmp);
        });
    });

    $(document).on('click','.proqyz-sync_courses-btn', function () {
        let btn = $(this);
        let tmp = btn.html();
        const sync = confirm("This process is time consuming, if there are large amount of courses, would you still want to sync courses?");
        if( sync ) {
            window['proqyz-ajax_sync-courses'] = $.ajax({
                url: '/wp-admin/admin-ajax.php',
                method: 'POST',
                data: {
                    "action": 'proqyz-sync-courses'
                },
                beforeSend: function () {
                    if( window['proqyz-ajax_sync-courses'] != null ) {
                        window['proqyz-ajax_sync-courses'].abort();
                    }
                    btn.prop('disabled', true);
                    btn.html('Syncing...');
                },
                success: function (res) {
                    if (res.success) {
                        const { res_type, message } = res.success;
                        if(res_type == "success"){
                            toastr.success(message);
                        } else {
                            toastr.info(message);
                        } 
                    }

                    if (res.error) {
                        const { res_type, message } = res.error;
                        if(res_type == "error"){
                            toastr.error(message);
                        } else {
                            toastr.info(message);
                        } 
                    }
                },
                error: function (err) {
                    toastr.error(err.code);
                }
            }).always(() => {
                btn.prop('disabled', false);
                btn.html(tmp);
            });
        }
    });


    $(document).on('click', '.ielts-lms-binary-selector-button-add', addRight);
    $(document).on('click', '.ielts-lms-binary-selector-button-remove', addLeft);
    $(document).on('keyup', '.search-left', search);
    $(document).on('keyup', '.search-right', search);
    $(document).on('click', '[data-type=prev]', previousLmsData);
    $(document).on('click', '[data-type=next]', nextLmsData);
    $(document).on('submit', '[data-proqyz-form="create-group-form"]', submitGroupData);
    $(document).on('submit', '[data-proqyz-form="course-access"]', submitCourseAccess);


    function changeSearchText(e) {
        let typeOfSearch = $(this).data('proqyz-search-for');
        if( typeOfSearch == "course-access" ) {
            
        }

        let topE = document.querySelectorAll('.top-search');
        let bottomE = document.querySelectorAll('.bottom-search');

        if (e.target.checked) {
            
            let text = "";
            if (e.target.value == "username") {
                text = "Username";
            } else if (e.target.value == "user-id") {
                text = "User id";
            } else if (e.target.value == "email") {
                text = "Email";
            }

            if( typeOfSearch == "course-access" ) {
                $('.search-left').prop('placeholder', `Search All Course Users By ${text}`);
                $('.search-right').prop('placeholder', `Search Assigned Course Users By ${text}`);
            } else {

                topE.forEach(te => {
                    te.placeholder = `Search student by ${text} `;
                });

                bottomE.forEach(be => {
                    be.placeholder = `Search teacher by ${text} `;
                });
            }


        }
    }

    function addRight(ev) {
        let rootElement = $(this).data('proqyz-root');

        let selectorLeft = $(rootElement).find('.left-selector .ielts-lms-binary-selector-select');
        let selectorRight = $(rootElement).find('.right-selector .ielts-lms-binary-selector-select');
        let dataIdsRoot = $(rootElement).find('[name="data-ids"]');
        let jsonDataIds = JSON.parse(dataIdsRoot.val());
        let options = selectorLeft.find('option:selected');

        options.each(function () {
            let option = $(this);
            let cloneOption = option.clone();
            option.prop('disabled', true);
            option.addClass('ielts-lms-binary-selector-item-disabled');
            option.prop('selected', false);
            cloneOption.prop('selected', false);
            selectorRight.append(cloneOption);
            jsonDataIds.push(option.data('value'));
            dataIdsRoot.val(JSON.stringify(jsonDataIds));
        });

    }

    function addLeft(ev) {
        let rootElement = $(this).data('proqyz-root');
        console.log(rootElement);
        let selectorLeft = $(rootElement).find('.left-selector .ielts-lms-binary-selector-select');
        let selectorRight = $(rootElement).find('.right-selector .ielts-lms-binary-selector-select');
        let dataIdsRoot = $(rootElement).find('[name="data-ids"]');
        let jsonDataIds = JSON.parse(dataIdsRoot.val());
        let options = selectorRight.find('option:selected');

        options.each(function () {
            let option = $(this);
            let dataValue = option.data('value');
            console.log(dataValue);
            if (selectorLeft.find(`[data-value='${dataValue}']`)) {
                option.remove();
                if (jsonDataIds.indexOf(dataValue) != - 1 || jsonDataIds.indexOf(+dataValue) != - 1) {
                    for (var i = 0; i < jsonDataIds.length; i++) {
                        if (jsonDataIds[i] == dataValue || +jsonDataIds[i] == +dataValue) {
                            jsonDataIds.splice(i, 1);
                        }
                    }
                    dataIdsRoot.val(JSON.stringify(jsonDataIds));
                }

                let lop = selectorLeft.find(`[data-value='${dataValue}']`);
                lop.prop('disabled', false);
                lop.removeClass('ielts-lms-binary-selector-item-disabled');
                lop.prop('selected', false);
            } else {
                options.each(function () {
                    if (jsonDataIds.indexOf(dataValue) != - 1 | jsonDataIds.indexOf(+dataValue) != - 1) {
                        for (var i = 0; i < jsonDataIds.length; i++) {
                            if (jsonDataIds[i] == dataValue || +jsonDataIds[i] == +dataValue) {
                                jsonDataIds.splice(i, 1);
                            }
                        }
                        dataIdsRoot.val(JSON.stringify(jsonDataIds));
                    }
                    option.remove();
                });
            }
        });
    }

    function search(event) {
        let data; let allOk = false;
        let rootEle = $(this).data('proqyz-root');
        let root = $(rootEle);
        let typeOfAction = "proqyz-binary-selector";
        let category = root.data('category');
        let searchKey = event.target.value;
        let pos = event.target.dataset.type;
        let dataIdsRoot = root.find('[name="data-ids"]');
        let dataIds = JSON.parse(dataIdsRoot.val());
        let selectorLeft = root.find('.left-selector .ielts-lms-binary-selector-select');
        let selectorRight = root.find('.right-selector .ielts-lms-binary-selector-select');
        let leftPagination = root.find('.left-selector .ielts-lms-pagination-left');
        let leftPaginationLi = leftPagination.find('li');

        let totalPages = root.find('.total_pages');
        let currentPageText = root.find('.current_page');
        let currentPage = root.find('[name=current-page]');
        let totalPagesIn = root.find('[name=total-pages]');
        let preLeft = leftPagination.find('[data-type=prev]');
        let nextLeft = leftPagination.find('[data-type=next]');

        let keyType = document.querySelector('[name=search-by]:checked');
        if (searchKey.length != 0) {
            data = {
                "action": typeOfAction,
                "type": category,
                "key": searchKey,
                "ids": dataIds,
                "sort-by": "key",
                "key-type": keyType.value,
                "pos": pos,
                "group-id": $('#create-group-form').find("#id").val()
            };
            allOk = true;
        } else {
            // reset results | show all
            allOk = true;
            data = {
                "action": typeOfAction,
                "type": category,
                "sort-by": "all",
                "ids": dataIds,
                "pos": pos,
                "items": 20,
                "current_page": 1,
                "group-id": $('#create-group-form').find("#id").val()
            };
        }

        if (allOk) {
            // onsearch hide pagination in [x pos] side
            window['ielts_lms_ajax_request'+pos] = $.ajax({
                type: 'POST',
                url: window.ajaxurl,
                dataType: 'json',
                cache: false,
                data: data,
                beforeSend: function () {
                    if (window['ielts_lms_ajax_request'+pos] != null) {
                        window['ielts_lms_ajax_request'+pos].abort();
                    }
                    // hide pagination inside selected root
                    if (pos == "left") {
                        leftPaginationLi.css('display', 'none');
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.warn('init: error HTTP Status[' + jqXHR.status + '] ' + errorThrown);
                },
                success: function (reply_data) {
                    try {
                        let jData = reply_data;
                        if (jData.success) {
                            const { has_html, has_json, html, json } = jData.success;
                            const { sort_by, pos, current_page, total_pages, ids } = json;
                            const { html_left, html_right } = html;
                            if (has_html && has_json) {

                                if (sort_by == "all") {

                                    if (pos == "left") {
                                        selectorLeft.html(html_left);

                                    }


                                    leftPaginationLi.css('display', 'list-item');
                                    selectorRight.html(html_right);
                                    dataIdsRoot.val(ids);


                                } else if (sort_by == "key") {
                                    if (pos == "left") {
                                        selectorLeft.html(html_left);
                                    }

                                    if (pos == "right") {
                                        selectorRight.html(html_right);
                                    }

                                    dataIdsRoot.val(ids);

                                }
                            }
                        }
                    } catch (err) {
                        console.warn("ERROR:", err);
                    }

                },
            });
        }


    }

    function previousLmsData(e) {
        let data; let allOk = true;
        let rootEle = $(this).data('proqyz-root');
        let root = $(rootEle);
        let typeOfAction = "proqyz-binary-selector";
        let category = root.data('category');
        let pos = e.target.dataset.pos;
        let dataIdsRoot = root.find('[name="data-ids"]');
        let dataIds = JSON.parse(dataIdsRoot.val());
        let selectorLeft = root.find('.left-selector .ielts-lms-binary-selector-select');
        let selectorRight = root.find('.right-selector .ielts-lms-binary-selector-select');
        let leftPagination = root.find('.left-selector .ielts-lms-pagination-left');
        let leftPaginationLi = leftPagination.find('li');

        let totalPages = root.find('.total_pages');
        let currentPageText = root.find('.current_page');
        let currentPage = root.find('[name=current-page]');
        let totalPagesIn = root.find('[name=total-pages]');
        let preLeft = leftPagination.find('[data-type=prev]');
        let nextLeft = leftPagination.find('[data-type=next]');
        let pageMod = "prev";

        data = {
            "action": typeOfAction,
            "type": category,
            "sort-by": "all",
            "ids": dataIds,
            "pos": pos,
            "items": 20,
            "current_page": currentPage.val(),
            "page_mod": pageMod,
            "group-id": $('#create-group-form').find("#id").val()
        };

        if (allOk) {
            // onsearch hide pagination in [x pos] side
            window['ielts_lms_ajax_request'] = jQuery.ajax({
                type: 'POST',
                url: window.ajaxurl,
                dataType: 'json',
                cache: false,
                data: data,
                beforeSend: function () {
                    if (window['ielts_lms_ajax_request'] != null) {
                        window['ielts_lms_ajax_request'].abort();
                    }
                    // hide pagination inside selected root
                    if (pos == "left") { }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.warn('init: error HTTP Status[' + jqXHR.status + '] ' + errorThrown);
                },
                success: function (reply_data) {


                    try {
                        let jData = reply_data;
                        if (jData.success) {
                            const { has_html, has_json, html, json } = jData.success;
                            const { sort_by, pos, current_page, total_pages, ids } = json;
                            const { html_left, html_right } = html;
                            if (has_html && has_json) {
                                if (pos == "left") {
                                    selectorLeft.html(html_left);
                                    leftPaginationLi.css('display', 'list-item');
                                    totalPages.html(total_pages);
                                    currentPageText.html(current_page);
                                    if (total_pages <= 1) {
                                        // If there's only one page, hide both links
                                        preLeft.css('display', 'none');
                                        nextLeft.css('display', 'none');
                                    } else if (current_page == 1) {
                                        // If current page is the first page, hide the "prev" link
                                        preLeft.css('display', 'none');
                                        nextLeft.css('display', 'flex');
                                    } else if (current_page > 1 && current_page < total_pages) {
                                        // If current page is between first and last page, show both links
                                        preLeft.css('display', 'flex');
                                        nextLeft.css('display', 'flex');
                                    } else if (current_page == total_pages) {
                                        // If current page is the last page, hide the "next" link
                                        preLeft.css('display', 'flex');
                                        nextLeft.css('display', 'none');
                                    }
                                }




                                selectorRight.html(html_right);
                                dataIdsRoot.val(ids);
                            }
                        }
                    } catch (err) {
                        console.warn("ERROR:", err);
                    }

                },
            });
        }


    }

    function nextLmsData(e) {
        let data; let allOk = true;
        let rootEle = $(this).data('proqyz-root');
        let root = $(rootEle);
        let typeOfAction = "proqyz-binary-selector";
        let category = root.data('category');
        let pos = e.target.dataset.pos;
        let dataIdsRoot = root.find('[name="data-ids"]');
        let dataIds = JSON.parse(dataIdsRoot.val());
        let selectorLeft = root.find('.left-selector .ielts-lms-binary-selector-select');
        let selectorRight = root.find('.right-selector .ielts-lms-binary-selector-select');
        let leftPagination = root.find('.left-selector .ielts-lms-pagination-left');
        let leftPaginationLi = leftPagination.find('li');

        let totalPages = root.find('.total_pages');
        let currentPageText = root.find('.current_page');
        let currentPage = root.find('[name=current-page]');
        let totalPagesIn = root.find('[name=total-pages]');
        let preLeft = leftPagination.find('[data-type=prev]');
        let nextLeft = leftPagination.find('[data-type=next]');
        let pageMod = "next";

        data = {
            "action": typeOfAction,
            "type": category,
            "sort-by": "all",
            "ids": dataIds,
            "pos": pos,
            "items": 20,
            "current_page": currentPage.val(),
            "page_mod": pageMod,
            "group-id": $('#create-group-form').find("#id").val()
        };

        if (allOk) {
            // onsearch hide pagination in [x pos] side
            window['ielts_lms_ajax_request'] = jQuery.ajax({
                type: 'POST',
                url: window.ajaxurl,
                dataType: 'json',
                cache: false,
                data: data,
                beforeSend: function () {
                    if (window['ielts_lms_ajax_request'] != null) {
                        window['ielts_lms_ajax_request'].abort();
                    }
                    // hide pagination inside selected root
                    if (pos == "left") { }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.warn('init: error HTTP Status[' + jqXHR.status + '] ' + errorThrown);
                },
                success: function (reply_data) {

                    try {
                        let jData = reply_data;
                        if (jData.success) {
                            const { has_html, has_json, html, json } = jData.success;
                            const { sort_by, pos, current_page, total_pages, ids } = json;
                            const { html_left, html_right } = html;
                            if (has_html && has_json) {
                                if (pos == "left") {
                                    selectorLeft.html(html_left);
                                    leftPaginationLi.css('display', 'list-item');
                                    totalPages.html(total_pages);
                                    currentPageText.html(current_page);
                                    if (total_pages <= 1) {
                                        // If there's only one page, hide both links
                                        preLeft.css('display', 'none');
                                        nextLeft.css('display', 'none');
                                    } else if (current_page == 1) {
                                        // If current page is the first page, hide the "prev" link
                                        preLeft.css('display', 'none');
                                        nextLeft.css('display', 'flex');
                                    } else if (current_page > 1 && current_page < total_pages) {
                                        // If current page is between first and last page, show both links
                                        preLeft.css('display', 'flex');
                                        nextLeft.css('display', 'flex');
                                    } else if (current_page == total_pages) {
                                        // If current page is the last page, hide the "next" link
                                        preLeft.css('display', 'flex');
                                        nextLeft.css('display', 'none');
                                    }
                                }




                                selectorRight.html(html_right);
                                dataIdsRoot.val(ids);
                            }
                        }
                    } catch (err) {
                        console.warn("ERROR:", err);
                    }

                },
            });
        }
    }

    function submitGroupData(ev) {
        ev.preventDefault();
        let root = $(this);
        let groupTitle = root.find('#group-title');
        let studentIds = root.find('[data-category="students"]').find('#data-ids');
        let teacherIds = root.find('[data-category="teachers"]').find('#data-ids');

        let groupTitleVal = groupTitle.val();
        let studentIdsVal = studentIds.val();
        let teacherIdsVal = teacherIds.val();

        let data;
        if (root.find("#id").length == 1) {
            data = {
                "action": "proqyz-ajax-group-form-action",
                "group-title": groupTitleVal,
                "student-ids": JSON.parse(studentIdsVal),
                "teacher-ids": JSON.parse(teacherIdsVal),
                "group-id": root.find("#id").val(),
                "type": 'edit'
            };
        } else {
            data = {
                "action": "proqyz-ajax-group-form-action",
                "group-title": groupTitleVal,
                "student-ids": JSON.parse(studentIdsVal),
                "teacher-ids": JSON.parse(teacherIdsVal),
                "type": 'new'
            };

        }



        window['proqyz_form-submit'] = jQuery.ajax({
            type: 'POST',
            url: window.ajaxurl,
            dataType: 'json',
            cache: false,
            data: data,
            beforeSend: function () {
                if (window['proqyz_form-submit'] != null) {
                    window['proqyz_form-submit'].abort();
                }
                $('#save-btn').prop('disabled', true);
                $('#save-btn').addClass('is-busy');
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.warn('init: error HTTP Status[' + jqXHR.status + '] ' + errorThrown);
            },
            success: function (reply_data) {
                if (reply_data.success) {
                    const { res_type, type, message, reload } = reply_data.success;
                    if (type == "new") {
                        if (res_type == "success") {
                            toastr.success(message);
                        } else if (res_type == "warning") {
                            toastr.warning(message);
                        } else if (res_type == "info") {
                            toastr.info(message);
                        } else if (res_type == "error") {
                            toastr.error(message);
                        }

                        if (reload) { window.location.reload(); }
                    } else if (type == "edit") {
                        if (res_type == "success") {
                            toastr.success(message);
                        } else if (res_type == "warning") {
                            toastr.warning(message);
                        } else if (res_type == "info") {
                            toastr.info(message);
                        } else if (res_type == "error") {
                            toastr.error(message);
                        }

                        if (reload) { window.location.reload(); }
                    }
                }

                if (reply_data.error) {
                    const { res_type, type, message } = reply_data.error;
                    if (type == "new") {
                        if (res_type == "success") {
                            toastr.success(message);
                        } else if (res_type == "warning") {
                            toastr.warning(message);
                        } else if (res_type == "info") {
                            toastr.info(message);
                        } else if (res_type == "error") {
                            toastr.error(message);
                        }

                        if (reload) { window.location.reload(); }
                    } else if (type == "edit") {
                        if (res_type == "success") {
                            toastr.success(message);
                        } else if (res_type == "warning") {
                            toastr.warning(message);
                        } else if (res_type == "info") {
                            toastr.info(message);
                        } else if (res_type == "error") {
                            toastr.error(message);
                        }

                        if (reload) { window.location.reload(); }
                    }
                }
            },
        }).always(() => {
            $('#save-btn').prop('disabled', false);
            $('#save-btn').removeClass('is-busy');
        });


    }

    function submitCourseAccess(ev) {
        ev.preventDefault();
        let root         = $(this);
        
        let userIds     = root.find('[data-category="course-access-all"]').find('#data-ids');

        
        if (root.find("#id").length == 1) {

            let data = {
                "action": "proqyz-ajax-course-access-form-action",
                "user-ids": JSON.parse(userIds.val()),
                "course-id": root.find("#id").val(),
                "type": 'edit'
            };

            window['proqyz_form-submit'] = jQuery.ajax({
                type: 'POST',
                url: window.ajaxurl,
                dataType: 'json',
                cache: false,
                data: data,
                beforeSend: function () {
                    if (window['proqyz_form-submit'] != null) {
                        window['proqyz_form-submit'].abort();
                    }
                    $('#save-btn').prop('disabled', true);
                    $('#save-btn').addClass('is-busy');
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.warn('init: error HTTP Status[' + jqXHR.status + '] ' + errorThrown);
                },
                success: function (reply_data) {
                    if (reply_data.success) {
                        const { res_type, type, message, reload } = reply_data.success;
                        if (type == "edit") {
                            if (res_type == "success") {
                                toastr.success(message);
                            } else if (res_type == "warning") {
                                toastr.warning(message);
                            } else if (res_type == "info") {
                                toastr.info(message);
                            } else if (res_type == "error") {
                                toastr.error(message);
                            }
    
                            if (reload) { window.location.reload(); }
                        }
                    }
    
                    if (reply_data.error) {
                        const { res_type, type, message } = reply_data.error;
                        if (type == "edit") {
                            if (res_type == "success") {
                                toastr.success(message);
                            } else if (res_type == "warning") {
                                toastr.warning(message);
                            } else if (res_type == "info") {
                                toastr.info(message);
                            } else if (res_type == "error") {
                                toastr.error(message);
                            }
    
                            if (reload) { window.location.reload(); }
                        }
                    }
                },
            }).always(() => {
                $('#save-btn').prop('disabled', false);
                $('#save-btn').removeClass('is-busy');
            });




        } else {
            toastr.error("Missing course id");
        }

    }


    $(document).on('change', '[name="search-by"]', changeSearchText);

    // define actions
    $(document).on('click', '[data-type="proqyz-groups-action"]', function () {

        let actionType = $(this).data('proqyz-groups-action-type'); // [edit,trash,delete]
        let actionId = $(this).data('proqyz-groups-action-id'); // post id
        if (actionType == "edit") {
            let btn = $(this);
            let tmp = btn.html();
            window['proqyz_ajax-load-action'] = $.ajax({
                url: '/wp-admin/admin-ajax.php',
                dataType: 'json',
                method: 'POST',
                data: {
                    action: 'proqyz-groups-action',
                    type: actionType,
                    id: actionId
                },
                beforeSend: function () {
                    if (window['proqyz_ajax-load-action'] != null) {
                        window['proqyz_ajax-load-action'].abort();
                    }
                    btn.html('Editing...');
                    btn.prop('disabled', true);
                },
                success: function (res) {
                    if (res.success) {
                        const { res_type, type, message, reload, has_html, html } = res.success;

                        if (has_html) {
                            $('#modal-group .modal-content').html(html);
                            $('#modal-group').modal('show');
                        }

                        if (res_type == "success") {
                            toastr.success(message);
                        } else if (res_type == "warning") {
                            toastr.warning(message);
                        } else if (res_type == "info") {
                            toastr.info(message);
                        } else if (res_type == "error") {
                            toastr.error(message);
                        }

                        if (reload) {
                            window.location.reload();
                        }

                    }

                    if (res.error) {
                        const { res_type, type, message } = res.error;
                        if (res_type == "success") {
                            toastr.success(message);

                        } else if (res_type == "warning") {
                            toastr.warning(message);
                        } else if (res_type == "info") {
                            toastr.info(message);
                        } else if (res_type == "error") {
                            toastr.error(message);
                        } else {
                            toastr.warning(message);
                        }
                    }
                },
                error: function () { }
            }).always(() => {
                btn.html(tmp);
                btn.prop('disabled', false);
            });
        } else if (actionType == "delete") {
            let btn = $(this);
            let tmp = btn.html();
            if (window.confirm(`Would you like to remove this group: ${btn.data('proqyz-group-title')}`)) {
                window['proqyz_ajax-load-action'] = $.ajax({
                    url: '/wp-admin/admin-ajax.php',
                    dataType: 'json',
                    method: 'POST',
                    data: {
                        action: 'proqyz-groups-action',
                        type: actionType,
                        id: actionId
                    },
                    beforeSend: function () {
                        if (window['proqyz_ajax-load-action'] != null) {
                            window['proqyz_ajax-load-action'].abort();
                        }
                        btn.html('Removing...');
                        btn.prop('disabled', true);
                    },
                    success: function (res) {
                        if (res.success) {
                            const { res_type, type, message, reload, has_html, html } = res.success;
                            if (res_type == "success") {
                                toastr.success(message);
                                $(`#group-${actionId}`).remove();
                            } else if (res_type == "warning") {
                                toastr.warning(message);
                            } else if (res_type == "info") {
                                toastr.info(message);
                            } else if (res_type == "error") {
                                toastr.error(message);
                            }
                        }

                        if (res.error) {
                            const { res_type, type, message } = res.error;
                            if (res_type == "success") {
                                toastr.success(message);
                            } else if (res_type == "warning") {
                                toastr.warning(message);
                            } else if (res_type == "info") {
                                toastr.info(message);
                            } else if (res_type == "error") {
                                toastr.error(message);
                            } else {
                                toastr.warning(message);
                            }
                        }
                    },
                    error: function () {

                    }
                }).always(() => {
                    btn.html(tmp);
                    btn.prop('disabled', false);
                });
            }
        }
    });

    $(document).on('click', '[data-type="proqyz-course-action"]', function () {

        let actionType = $(this).data('proqyz-course-action-type'); // [edit,trash,delete]
        let actionId = $(this).data('proqyz-course-action-id'); // post id
        if ( actionType == "course-access" ) {
            let btn = $(this);
            let tmp = btn.html();

            window['proqyz_ajax-load-action'] = $.ajax({
                url: '/wp-admin/admin-ajax.php',
                dataType: 'json',
                method: 'POST',
                data: {
                    action: 'proqyz-course-action',
                    type: actionType,
                    id: actionId
                },
                beforeSend: function () {
                    if (window['proqyz_ajax-load-action'] != null) {
                        window['proqyz_ajax-load-action'].abort();
                    }
                    btn.html('Loading...');
                    btn.prop('disabled', true);
                },
                success: function (res) {
                    if (res.success) {
                        const {
                            res_type,
                            type,
                            message,
                            reload,
                            has_html,
                            html
                        } = res.success;

                        if (has_html) {
                            $('#modal-course-access .modal-content').html(html);
                            $('#modal-course-access').modal('show');
                        }

                        if (res_type == "success") {
                            toastr.success(message);
                        } else if (res_type == "warning") {
                            toastr.warning(message);
                        } else if (res_type == "info") {
                            toastr.info(message);
                        } else if (res_type == "error") {
                            toastr.error(message);
                        }

                        if (reload) {
                            window.location.reload();
                        }

                    }

                    if (res.error) {
                        const { res_type, type, message } = res.error;
                        if (res_type == "success") {
                            toastr.success(message);

                        } else if (res_type == "warning") {
                            toastr.warning(message);
                        } else if (res_type == "info") {
                            toastr.info(message);
                        } else if (res_type == "error") {
                            toastr.error(message);
                        } else {
                            toastr.warning(message);
                        }
                    }
                },
                error: function () {

                }
            }).always(() => {
                btn.html(tmp);
                btn.prop('disabled', false);
            });
        }
    });

    


})(jQuery);

(function ($) {
    $(document).on('click', '[data-st-type="copy-to-clipboard"]', function () {
        if ($(this).data('st-copy-target').length > 0) {
            const tmp = $(this).html();
            $(this).attr('disabled', true);
            $(this).html('Copying...');
            const targetInputId = $(this).data('st-copy-target');
            const stringToCopy = $(targetInputId).val();

            // logic for copy to clipboard
            var tempInput = $("<input>");
            $("body").append(tempInput);
            tempInput.val(stringToCopy).select();
            document.execCommand("copy");
            $(this).html('Copied');
            tempInput.remove();

            setTimeout(() => {
                $(this).html(tmp);
                $(this).attr('disabled', false);
            }, 1000);



        }
    });
})(jQuery);