jQuery(document).ready(function ($) {
    var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };

    $("#add_package_button").click(function () {
        $(
        "#add_package_button_modal .modal-title,#add_package_button_modal  #savePackage"
        ).text("Add Package");
        $("#add_package_button_modal #id").val("");
        $("#add_package_button_modal #euro_amount").val("");
        $("#add_package_button_modal #packageid").val("");
        $("#add_package_button_modal #packageid").prop("readonly", false);
        $("#add_package_button_modal #description").val("");
        $("#add_package_button_modal #heading").val("");
        $("#saPackageForm #active").prop("checked", false);
        $("#add_package_button_modal").modal("show");
    });

    //Save package
    $(document).on("click", "#savePackage", function () {
        var container = $('#add_package_button_modal .modal-content');
        var formData = $("#saPackageForm").serialize(); // Serialize the form data
        $(container).block( block_config );
        $.ajax({
                type: "POST",
                url: cipscript.ajax_url, // WordPress AJAX handler URL
                data: {
                    action: "handle_sa_package_form", // Action to be handled in PHP
                    form_data: formData,
                },
            success: function (response) {
                // Handle the response here, e.g., show success message or perform additional actions
                // Close the modal after successful submission
                if (response.success) {
                    let eve = jQuery.Event("keyup");

                    eve.which = 13;

                    eve.keyCode = 13;

                    $('#sa_packages_listing_list input[type="search"]').trigger(eve);

                    $("#add_package_button_modal").modal("hide");

                    Swal.fire({
                        toast: true,
                        type: "success",
                        animation: false,
                        position: "bottom",
                        showConfirmButton: false,
                        timer: 3000,
                        timerProgressBar: true,
                        title: response.data.message,
                        text: "",
                        allowOutsideClick: true,
                    });
                } else {
                    Swal.fire({
                        toast: true,
                        type: "error",
                        animation: false,
                        position: "bottom",
                        showConfirmButton: false,
                        timer: 3000,
                        timerProgressBar: true,
                        title: response.data.message,
                        text: "",
                        allowOutsideClick: true,
                    });
                }
                $(container).unblock();
            },
            error: function (xhr, status, error) {
                $(container).unblock();
                // Handle errors here
                console.error(error);
            },
        });
    });

    //Edit Package
    $(document).on("click", "#editpackagesButton", function () {
    var package_id = $(this).attr("data-packages-id");
        $.ajax({
            type: "GET",
            url: cipscript.ajax_url, // WordPress AJAX URL
            data: {
            action: "sa_get_packages_loader",
            package_id: package_id,
            },
            success: function (response) {
            if (response.success) {
                // Handle the success response
                $(
                "#add_package_button_modal .modal-title,#add_package_button_modal  #savePackage"
                ).text("Update Package");
                $("#add_package_button_modal #id").val(response.data.id);
                $("#add_package_button_modal #euro_amount").val(
                response.data.euro_amount
                );
                $("#add_package_button_modal #packageid").val(
                response.data.packageid
                );
                $("#add_package_button_modal #heading").val(response.data.heading);
                $("#add_package_button_modal #description").val(
                response.data.description
                );
                $("#add_package_button_modal #packageid").prop("readonly", true);
                if (response.data.active == 1) {
                $("#saPackageForm #active").prop("checked", true);
                } else {
                $("#saPackageForm #active").prop("checked", false);
                }

                $("#add_package_button_modal").modal("show");
            }
            },
        });
    });

    //Delete package
    $(document).on("click", "#delete_sa_package", function () {
        swal({
            title: "Are you sure?",
            text: "It will permanently deleted !",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            confirmButtonText: "Yes, delete it!",
        }).then((willDelete) => {
            console.log(willDelete);
            if (willDelete.value) {
            var postId = $(this).attr("data-packages-id");
            var package_euro_amount = $(this)
                .parents("tr")
                .find(".euro_amount")
                .text();
            $.ajax({
                type: "POST",
                url: cipscript.ajax_url, // WordPress AJAX URL
                data: {
                action: "delete_sa_package",
                package_id: postId,
                package_euro_amount: package_euro_amount,
                },
                success: function (response) {
                // Handle the success response
                if (response.success) {
                    $("[data-packages-id='" + response.data.id + "']")
                    .parents("tr")
                    .remove();
                    Swal.fire({
                        toast: true,
                        type: "error",
                        animation: false,
                        position: "bottom",
                        showConfirmButton: false,
                        timer: 3000,
                        timerProgressBar: true,
                        title: response.data.message,
                        text: "",
                        allowOutsideClick: true,
                    });
                }
                },
            });
            }
        });
    });

    //Active/Inactive
    $(document).on("change", ".packages-change", function () {
        var checkboxValue = this.checked ? "true" : "false";
        var text, checkboxValuedata;
        var current_tr = $(this).closest('tr');
        // Get the user ID if it's available on your page.
        if (checkboxValue == "true") {
            text = "Active";
            checkboxValuedata = 1;
        } else {
            text = "Inactive";
            checkboxValuedata = 0;
        }
        current_tr.block( block_config );
        $(this).parent(".custom-switch").find(".form-check-label").text(text);
        var userId = $(this).attr("data-id");
        var package_euro_amount = $(this).parents("tr").find(".euro_amount").text();
        $.ajax({
            type: "POST",
            url: cipscript.ajax_url, // WordPress AJAX endpoint URL
            data: {
            action: "update_checkbox_packages_auth",
            user_id: userId,
            checkbox_value: checkboxValuedata,
            package_euro_amount: package_euro_amount,
            },
            success: function (response) {
                //$('#sa_packages_listing_list').bootstrapTable('refresh');
                Swal.fire({
                    toast: true,
                    type: "success",
                    animation: false,
                    position: "bottom",
                    showConfirmButton: false,
                    timer: 3000,
                    timerProgressBar: true,
                    title: response.data.message,
                    text: "",
                    allowOutsideClick: true,
                });
                current_tr.unblock();
            },
        });
    });
});