jQuery(document).ready(function ($) {
    "use strict";

    $(document).on("click", "#iwbvel-bulk-edit-form-schedule-bulk", function () {
        $('.iwbvel-tab-item[data-content="set_schedule"]').show().trigger("click");
    });

    $(document).on("click", "#iwbvel-bulk-edit-form-reset", function () {
        $(".iwbvel-set-schedule-enable-schedule").prop("checked", false).change();
        $(".iwbvel-set-schedule-run-at").val("now").change();
    });

    $(document).on("change", ".iwbvel-set-schedule-enable-schedule", function () {
        let container = $(this).closest("#iwbvel-float-side-modal-bulk-edit");
        if (!container.length) {
            return;
        }

        if ($(this).prop("checked") === true) {
            container.find(".iwbvel-set-schedule-form").show();
            container.find(".iwbvel-set-schedule-run-at").change();
            $(".iwbvel-bulk-edit-form-schedule-bulk-edit").show();
            $("#iwbvel-bulk-edit-form-do-bulk-edit").hide();
        } else {
            container.find(".iwbvel-set-schedule-form").hide();
            $(".iwbvel-bulk-edit-form-schedule-bulk-edit").hide();
            $("#iwbvel-bulk-edit-form-do-bulk-edit").show();
        }
    });

    $(document).on("change", ".iwbvel-set-schedule-run-at", function () {
        let container;
        if ($(this).closest("#iwbvel-modal-schedule-edit-job").length) {
            container = $(this).closest("#iwbvel-modal-schedule-edit-job");
        } else {
            container = $('.iwbvel-tab-content-item[data-content="set_schedule"]');
        }

        container.find(".iwbvel-set-schedule-dependent > div").hide();

        let dependentElement = container.find(".iwbvel-set-schedule-dependent");
        if (!dependentElement.length) {
            return;
        }

        if ($(this).val() != "") {
            dependentElement.find('div[data-content="revert_changes"]').show();
        } else {
            dependentElement.find('div[data-content="revert_changes"]').hide();
        }

        if ($(this).val() == "later") {
            dependentElement.find('div[data-content="later"]').show();
            dependentElement.find(".iwbvel-set-schedule-run-for").change();
        } else {
            dependentElement.find('div[data-content="later"]').hide();
        }

        if ($(this).val() == "now") {
            dependentElement.find('div[data-content="stop_schedule"]').hide();
            dependentElement.find('div[data-content="now"]').show();
        } else {
            dependentElement.find('div[data-content="now"]').hide();
        }
    });

    $(document).on("change", ".iwbvel-set-schedule-run-for", function () {
        let container;
        if ($(this).closest("#iwbvel-modal-schedule-edit-job").length) {
            container = $(this).closest("#iwbvel-modal-schedule-edit-job");
        } else {
            container = $('.iwbvel-tab-content-item[data-content="set_schedule"]');
        }

        let dependentElement = container.find(".iwbvel-set-schedule-dependent");
        if (!dependentElement.length) {
            return;
        }

        if ($(this).val() == "once") {
            dependentElement.find('div[data-content="once"]').show();
            dependentElement.find('div[data-content="stop_schedule"]').hide();
            dependentElement.find(".iwbvel-set-schedule-once-type").change();
        } else {
            if ($(this).val() != "") {
                dependentElement.find('div[data-content="stop_schedule"]').show();
            } else {
                dependentElement.find('div[data-content="stop_schedule"]').hide();
            }
            dependentElement.find('div[data-content="once"]').hide();
            dependentElement.find('div[data-content="specific_date_time"]').hide();
            dependentElement.find('div[data-content="n_hours_later"]').hide();
            dependentElement.find('div[data-content="n_days_later"]').hide();
        }

        if ($(this).val() == "daily") {
            dependentElement.find('div[data-content="daily"]').show();
        } else {
            dependentElement.find('div[data-content="daily"]').hide();
        }

        if ($(this).val() == "weekly") {
            dependentElement.find('div[data-content="weekly"]').show();
        } else {
            dependentElement.find('div[data-content="weekly"]').hide();
        }

        if ($(this).val() == "monthly") {
            dependentElement.find('div[data-content="monthly"]').show();
        } else {
            dependentElement.find('div[data-content="monthly"]').hide();
        }
    });

    $(document).on("change", ".iwbvel-set-schedule-once-type", function (e) {
        let container;
        if ($(this).closest("#iwbvel-modal-schedule-edit-job").length) {
            container = $(this).closest("#iwbvel-modal-schedule-edit-job");
        } else {
            container = $('.iwbvel-tab-content-item[data-content="set_schedule"]');
        }

        let dependentElement = container.find(".iwbvel-set-schedule-dependent");
        if (!dependentElement.length) {
            return;
        }

        dependentElement.find('div[data-content="specific_date_time"]').hide();
        dependentElement.find('div[data-content="n_hours_later"]').hide();
        dependentElement.find('div[data-content="n_days_later"]').hide();

        if ($(this).val() != "") {
            dependentElement.find('div[data-content="' + $(this).val() + '"]').show();
        }
    });

    $(document).on("click", ".iwbvel-schedule-bulk-edit-button", function (e) {
        $(".iwbvel-schedule-multiple-bulk-edit-container").slideToggle(100);
    });

    $(document).on("click", '.iwbvel-schedule-jobs-list-action-button[data-action="delete"]', function (e) {
        let jobId = $(this).attr("data-id");
        swal(
            {
                title: "Are you sure?",
                type: "warning",
                showCancelButton: true,
                cancelButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-white",
                confirmButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-green",
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: true,
            },
            function (isConfirm) {
                if (isConfirm) {
                    iwbvelScheduleDeleteJob(jobId);
                }
            }
        );
    });

    $(document).on("click", '.iwbvel-schedule-jobs-list-action-button[data-action="stop"]', function (e) {
        let jobId = $(this).attr("data-id");
        swal(
            {
                title: "Are you sure?",
                type: "warning",
                showCancelButton: true,
                cancelButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-white",
                confirmButtonClass: "iwbvel-button iwbvel-button-lg iwbvel-button-green",
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: true,
            },
            function (isConfirm) {
                if (isConfirm) {
                    iwbvelScheduleStopJob(jobId);
                }
            }
        );
    });

    $(document).on("click", ".iwbvel-schedule-edit-job-apply-button", function (e) {
        iwbvelScheduleUpdateJob($(this).attr("data-id"));
    });

    $(document).on("click", '.iwbvel-schedule-jobs-list-action-button[data-action="log"]', function (e) {
        $(".iwbvel-schedule-job-log-loading").show();
        $(".iwbvel-schedule-job-log-container").html("");
        iwbvelScheduleGetJobLog($(this).attr("data-id"));
    });

    $(document).on("click", '.iwbvel-schedule-jobs-list-action-button[data-action="show_edit_items"]', function (e) {
        $(".iwbvel-schedule-job-edit-items-loading").show();
        $(".iwbvel-schedule-job-edit-items-container").html("");
        iwbvelScheduleGetEditItems($(this).attr("data-id"));
    });

    $(document).on("click", '.iwbvel-schedule-jobs-list-action-button[data-action="edit"]', function (e) {
        $(".iwbvel-schedule-edit-job-container").hide();
        $(".iwbvel-schedule-edit-job-loading").show();
        iwbvelScheduleGetJobData($(this).attr("data-id"));
    });

    $(document).on("click", 'a[data-target="#iwbvel-float-side-modal-schedule-jobs"]', function () {
        $.ajax({
            url: IWBVEL_DATA.ajax_url,
            type: "post",
            dataType: "json",
            data: {
                action: IWBVEL_SCHEDULE_DATA.identifier + "_get_schedule_jobs",
                nonce: IWBVEL_DATA.ajax_nonce,
            },
            success: function (response) {
                $("#iwbvel-float-side-modal-schedule-jobs table tbody")
                    .html(response.rows)
                    .ready(function () {
                        iwbvelSetTipsyTooltip();
                    });
                iwbvelScheduleAwaitingCountUpdate(response.awaiting_count);
            },
            error: function () { },
        });
    });

    $(document).on("click", '.iwbvel-tab-item[data-content="set_schedule"]', function () {
        iwbvelScheduleCurrentTimeUpdate();
    });

    $(document).on("click", ".iwbvel-schedule-current-time-update-button", function () {
        jQuery(".iwbvel-set-schedule-current-time").css({ color: "#9d9d9d" });
        iwbvelScheduleCurrentTimeUpdate();
    });

    iwbvelScheduleDateTimePickerInit();
});

function iwbvelScheduleCurrentTimeUpdate() {
    jQuery.ajax({
        url: IWBVEL_DATA.ajax_url,
        type: "post",
        dataType: "json",
        data: {
            action: "iwbvel_schedule_get_current_time",
            nonce: IWBVEL_DATA.ajax_nonce,
        },
        success: function (response) {
            jQuery(".iwbvel-set-schedule-current-time").html(response.time).css({ color: "#444" });
        },
        error: function () { },
    });
}

function iwbvelScheduleStopJob(jobId) {
    iwbvelLoadingStart();
    jQuery.ajax({
        url: IWBVEL_SCHEDULE_DATA.ajax_url,
        type: "post",
        dataType: "json",
        data: {
            action: IWBVEL_SCHEDULE_DATA.identifier + "_schedule_job_stop",
            nonce: IWBVEL_SCHEDULE_DATA.ajax_nonce,
            job_id: jobId,
        },
        success: function (response) {
            if (response.success) {
                jQuery("#iwbvel-float-side-modal-schedule-jobs table tbody")
                    .html(response.rows)
                    .ready(function () {
                        iwbvelLoadingSuccess();
                        iwbvelScheduleAwaitingCountUpdate(response.awaiting_count);
                    });
            } else {
                iwbvelLoadingError();
            }
        },
        error: function () {
            iwbvelLoadingError();
        },
    });
}

function iwbvelScheduleUpdateJob(jobId) {
    iwbvelLoadingStart();

    let container = jQuery("#iwbvel-modal-schedule-edit-job .iwbvel-set-schedule-form");
    container
        .find(".required:visible")
        .each(function () {
            if (jQuery(this).val() != "") {
                jQuery(this).removeClass("error");
            } else {
                jQuery(this).addClass("error");
            }
        })
        .promise()
        .done(function () {
            if (container.find(".error").length) {
                iwbvelLoadingError("Please fill the required fields");
                return;
            }

            let dates = iwbvelScheduleGetDatesFromJobForm(container);
            jQuery.ajax({
                url: IWBVEL_SCHEDULE_DATA.ajax_url,
                type: "post",
                dataType: "json",
                data: {
                    action: IWBVEL_SCHEDULE_DATA.identifier + "_schedule_update_job",
                    nonce: IWBVEL_SCHEDULE_DATA.ajax_nonce,
                    job_id: jobId,
                    label: container.find(".iwbvel-set-schedule-name").val(),
                    description: container.find(".iwbvel-set-schedule-description").val(),
                    run_at: container.find(".iwbvel-set-schedule-run-at").val(),
                    run_for: container.find(".iwbvel-set-schedule-run-for:visible").length ? container.find(".iwbvel-set-schedule-run-for").val() : null,
                    dates: dates,
                    stop_date: container.find(".iwbvel-set-schedule-stop-date-time:visible").length ? container.find(".iwbvel-set-schedule-stop-date-time").val() : null,
                    revert_date: container.find(".iwbvel-set-schedule-revert-date-time:visible").length ? container.find(".iwbvel-set-schedule-revert-date-time").val() : null,
                },
                success: function (response) {
                    if (response.success) {
                        if (container.find(".iwbvel-set-schedule-run-at").val() == "now") {
                            iwbvelLoadingSuccess("Success | Reloading ...");
                            location.reload();
                        } else {
                            iwbvelLoadingSuccess();
                            jQuery(".iwbvel-schedule-jobs-list-navigation-button>a").trigger("click");
                            iwbvelCloseModal();
                        }
                    } else {
                        iwbvelLoadingError();
                    }
                },
                error: function () {
                    iwbvelLoadingError();
                },
            });
        });
}

function iwbvelScheduleDeleteJob(jobId) {
    iwbvelLoadingStart();
    jQuery.ajax({
        url: IWBVEL_SCHEDULE_DATA.ajax_url,
        type: "post",
        dataType: "json",
        data: {
            action: IWBVEL_SCHEDULE_DATA.identifier + "_schedule_job_delete",
            nonce: IWBVEL_SCHEDULE_DATA.ajax_nonce,
            job_id: jobId,
        },
        success: function (response) {
            if (response.success) {
                jQuery("#iwbvel-float-side-modal-schedule-jobs table tbody")
                    .html(response.rows)
                    .ready(function () {
                        iwbvelLoadingSuccess();
                        iwbvelScheduleAwaitingCountUpdate(response.awaiting_count);
                    });
            } else {
                iwbvelLoadingError();
            }
        },
        error: function () {
            iwbvelLoadingError();
        },
    });
}

function iwbvelScheduleGetJobLog(jobId) {
    jQuery.ajax({
        url: IWBVEL_SCHEDULE_DATA.ajax_url,
        type: "post",
        dataType: "json",
        data: {
            action: IWBVEL_SCHEDULE_DATA.identifier + "_schedule_get_job_log",
            nonce: IWBVEL_SCHEDULE_DATA.ajax_nonce,
            job_id: jobId,
        },
        success: function (response) {
            jQuery(".iwbvel-schedule-job-log-loading").hide();
            if (response.success) {
                jQuery(".iwbvel-schedule-job-log-container")
                    .html(response.html)
                    .ready(function () {
                        iwbvelFixModalHeight(jQuery("#iwbvel-modal-schedule-job-log"));
                        iwbvelSetTipsyTooltip();
                    });
            } else {
                jQuery(".iwbvel-schedule-job-log-container").html("No data available");
            }
        },
        error: function () {
            jQuery(".iwbvel-schedule-job-log-container").html("No data available");
        },
    });
}

function iwbvelScheduleGetEditItems(jobId) {
    jQuery.ajax({
        url: IWBVEL_SCHEDULE_DATA.ajax_url,
        type: "post",
        dataType: "json",
        data: {
            action: IWBVEL_SCHEDULE_DATA.identifier + "_schedule_get_edit_items",
            nonce: IWBVEL_SCHEDULE_DATA.ajax_nonce,
            job_id: jobId,
        },
        success: function (response) {
            jQuery(".iwbvel-schedule-job-edit-items-loading").hide();
            if (response.success && response.edit_items) {
                jQuery(".iwbvel-schedule-job-edit-items-container").html(response.edit_items);

                setTimeout(function () {
                    iwbvelFixModalHeight(jQuery("#iwbvel-modal-schedule-job-edit-items"));
                }, 150);
            }
        },
        error: function () { },
    });
}

function iwbvelScheduleGetJobData(jobId) {
    jQuery.ajax({
        url: IWBVEL_SCHEDULE_DATA.ajax_url,
        type: "post",
        dataType: "json",
        data: {
            action: IWBVEL_SCHEDULE_DATA.identifier + "_schedule_get_job_data",
            nonce: IWBVEL_SCHEDULE_DATA.ajax_nonce,
            job_id: jobId,
        },
        success: function (response) {
            jQuery(".iwbvel-schedule-edit-job-loading").hide();
            if (response.success && response.job.id) {
                let container = jQuery(".iwbvel-schedule-edit-job-container");
                container.find(".iwbvel-set-schedule-name").val(response.job.label).change();
                container.find(".iwbvel-set-schedule-description").val(response.job.description).change();
                container.find(".iwbvel-set-schedule-run-at").val(response.job.run_at).change();
                container.find(".iwbvel-set-schedule-run-for").val(response.job.run_for).change();
                if (response.job.run_for != "") {
                    switch (response.job.run_for) {
                        case "once":
                            if (response.job.dates.type) {
                                container.find(".iwbvel-set-schedule-once-type").val(response.job.dates.type).change();
                                switch (response.job.dates.type) {
                                    case "specific_date_time":
                                        container.find(".iwbvel-set-schedule-once-date-time").val(response.job.dates.date_time).change();
                                        break;
                                    case "n_hours_later":
                                        container.find(".iwbvel-set-schedule-once-hours").val(response.job.dates.time).change();
                                        break;
                                    case "n_days_later":
                                        container.find(".iwbvel-set-schedule-once-days").val(response.job.dates.days).change();
                                        break;
                                }
                            }
                            break;
                        case "daily":
                            if (response.job.dates.time) {
                                container.find(".iwbvel-set-schedule-daily-time").val(response.job.dates.time).change();
                            }
                            break;
                        case "weekly":
                            if (response.job.dates.days && response.job.dates.time) {
                                container.find(".iwbvel-set-schedule-weekly-days").val(response.job.dates.days).change();
                                container.find(".iwbvel-set-schedule-weekly-time").val(response.job.dates.time).change();
                            }
                            break;
                        case "monthly":
                            if (response.job.dates.days && response.job.dates.time) {
                                container.find(".iwbvel-set-schedule-monthly-days").val(response.job.dates.days).change();
                                container.find(".iwbvel-set-schedule-monthly-time").val(response.job.dates.time).change();
                            }
                            break;
                    }
                }
                container.find(".iwbvel-set-schedule-stop-date-time").val(response.job.stop_date).change();
                container.find(".iwbvel-set-schedule-revert-date-time").val(response.job.revert_date).change();
                container.show();

                setTimeout(function () {
                    iwbvelFixModalHeight(jQuery("#iwbvel-modal-schedule-edit-job"));
                    jQuery(".iwbvel-schedule-edit-job-apply-button").attr("data-id", response.job.id).prop("disabled", false);
                }, 150);
            } else {
            }
        },
        error: function () { },
    });
}

var iwbvelScheduleAllowTimes = [];
for (let hour = 0; hour < 24; hour++) {
    for (let minute = 0; minute < 60; minute += 5) {
        let formattedHour = ("0" + hour).slice(-2);
        let formattedMinute = ("0" + minute).slice(-2);
        iwbvelScheduleAllowTimes.push(formattedHour + ":" + formattedMinute);
    }
}

function iwbvelScheduleDateTimePickerInit() {
    if (!jQuery.fn.datetimepicker) {
        return false;
    }

    jQuery(".iwbvel-schedule-datetimepicker").datetimepicker("destroy");
    jQuery(".iwbvel-schedule-timepicker").datetimepicker("destroy");
    jQuery(".iwbvel-schedule-datetimepicker").datetimepicker({
        format: "Y-m-d H:i",
        scrollMonth: false,
        scrollInput: false,
        allowTimes: iwbvelScheduleAllowTimes,
    });
    jQuery(".iwbvel-schedule-timepicker").datetimepicker({
        datepicker: false,
        format: "H:i",
        scrollMonth: false,
        scrollInput: false,
        allowTimes: iwbvelScheduleAllowTimes,
    });
}

function iwbvelScheduleAwaitingCountUpdate(awaitingCount) {
    if (awaitingCount && parseInt(awaitingCount) > 0) {
        if (jQuery(".iwbvel-jobs-list-button-number").length) {
            jQuery(".iwbvel-jobs-list-button-number").text(awaitingCount);
        } else {
            jQuery(".iwbvel-schedule-jobs-list-navigation-button").append('<span class="iwbvel-jobs-list-button-number">' + awaitingCount + "</span>");
        }
    } else {
        jQuery(".iwbvel-jobs-list-button-number").remove();
    }
}

function iwbvelScheduleGetDatesFromJobForm(containerElement) {
    let dates = {};

    if (containerElement.find(".iwbvel-set-schedule-run-for").val() != "") {
        switch (containerElement.find(".iwbvel-set-schedule-run-for").val()) {
            case "once":
                dates["type"] = containerElement.find(".iwbvel-set-schedule-once-type").val();
                switch (containerElement.find(".iwbvel-set-schedule-once-type").val()) {
                    case "specific_date_time":
                        dates["date_time"] = containerElement.find(".iwbvel-set-schedule-once-date-time").val();
                        break;
                    case "n_hours_later":
                        dates["time"] = containerElement.find(".iwbvel-set-schedule-once-hours").val();
                        break;
                    case "n_days_later":
                        dates["days"] = containerElement.find(".iwbvel-set-schedule-once-days").val();
                        break;
                }
                break;
            case "daily":
                dates["time"] = containerElement.find(".iwbvel-set-schedule-daily-time").val();
                break;
            case "weekly":
                dates["days"] = containerElement.find(".iwbvel-set-schedule-weekly-days").val();
                dates["time"] = containerElement.find(".iwbvel-set-schedule-weekly-time").val();
                break;
            case "monthly":
                dates["days"] = containerElement.find(".iwbvel-set-schedule-monthly-days").val();
                dates["time"] = containerElement.find(".iwbvel-set-schedule-monthly-time").val();
                break;
        }
    }

    return dates;
}
