(function ($) {
    $.fn.cpError = function (action, message = "") {
        if (action === "add") {
            this.addClass("bdpcp-control-error");
            this.next(".bdpcp-error").show();
        } else if (action === "remove") {
            this.removeClass("bdpcp-control-error");
            this.next(".bdpcp-error").hide();
        }
        return this;
    };
})(jQuery);

jQuery(document).ready(function ($) {
    let bdpcp_date_picker_option = {
        dateFormat: "d-m-Y",
    };

    if (
        bdpcp_object.booking_everyday == "" ||
        bdpcp_object.booking_everyday == 0
    ) {
        const bdpcp_today = new Date();
        const [bdpcp_day, bdpcp_month, bdpcp_year] = bdpcp_object.start_date.split("-");
        const bdpcp_start_date = new Date(`${bdpcp_year}-${bdpcp_month}-${bdpcp_day}`);

        bdpcp_date_picker_option.minDate = bdpcp_start_date < bdpcp_today ? "today" : bdpcp_object.start_date;
        bdpcp_date_picker_option.maxDate = bdpcp_object.end_date;
    } else {
        bdpcp_date_picker_option.minDate = "today";
    }

    let bdpcp_disable = [];
    if (bdpcp_object.booking_week_off.length > 0) {
        for (let week_off of bdpcp_object.booking_week_off) {
            bdpcp_disable.push(function (date) {
                return date.getDay() === parseInt(week_off);
            });
        }
    }

    if (bdpcp_object.booking_day_off.length > 0) {
        for (let day_off of bdpcp_object.booking_day_off) {
            bdpcp_disable.push(function (date) {
                const formattedDate = date.toLocaleDateString("en-GB");
                const finalDate = formattedDate.replace(/\//g, "-");
                return day_off === finalDate;
            });
        }
    }

    bdpcp_date_picker_option.disable = bdpcp_disable;

    $("#bdpcp_booking_date").flatpickr(bdpcp_date_picker_option);

    $(document).on("click", ".bdpcp-people-select-control", function (e) {
        e.stopPropagation();

        var offset = $(this).offset();
        var top = offset.top;
        var left = offset.left;

        $(".bdpcp-people-container")
            .css({
                top: top - 82,
                left: left,
                width: $(this).width(),
            })
            .toggle();
    });

    $(document).on("click", "body", function () {
        $(".bdpcp-people-container").hide();
    });

    $(document).on("change", "#bdpcp_booking_date", function () {
        $("#bdpcp_time_slot_div").show();
        $("#bdpcp_booking_date").cpError("remove");
        bdpcp_count_amount();
    });

    $(document).on("submit", "#bdpcp_booking_form", function () {
        let times = [];
        $(".bdpcp-time-badge-selected").each(function () {
            times.push($(this).data("bdpcp-slot-time"));
        });
        $("#bdpcp_time_slots").val(JSON.stringify(times));
    });

    $(document).on("click", ".bdpcp-time-badge", function () {
        if (
            bdpcp_object.is_multiple_time_select == "" ||
            bdpcp_object.is_multiple_time_select == 0
        ) {
            $(".bdpcp-time-badge").removeClass("bdpcp-time-badge-selected");
            $(".bdpcp-time-badge").removeClass("bdpcp-time-badge-error");
            $(this).addClass("bdpcp-time-badge-selected");
        } else {
            $(this).toggleClass("bdpcp-time-badge-selected");
        }
        $("#bdpcp_booking_time").cpError("remove");
        bdpcp_count_amount();
    });

    $(document).on("click", ".bdpcp-btn-minus", function (e) {
        e.stopPropagation();
        let type = $(this).data("people-type");
        let min = $(this).data("min");
        let bdpcp_count = $(`#bdpcp_count_${type}`).val();
        if (parseInt(min) < parseInt(bdpcp_count)) {
            bdpcp_count--;
            $(`#bdpcp_count_${type}`).val(bdpcp_count);
            $(`#bdpcp_count_display_${type}`).html(`${bdpcp_count} ${type}`);
            $(`#bdpcp_count_control_${type}`).html(bdpcp_count);
            bdpcp_count_amount();
        }
    });

    $(document).on("click", ".bdpcp-btn-plus", function (e) {
        e.stopPropagation();

        let bdpcp_booking_date = $("#bdpcp_booking_date").val();
        if (bdpcp_booking_date == "") {
            $("#bdpcp_booking_date").cpError("add");
            return false;
        }

        if ($(".bdpcp-time-badge").length > 0) {
            if ($(".bdpcp-time-badge-selected").length == 0) {
                $("#bdpcp_booking_time").cpError("add");
                return false;
            }
        }

        $(".bdpcp-people-select-control").cpError("remove");

        let type = $(this).data("people-type");
        let bdpcp_count = $(`#bdpcp_count_${type}`).val();
        let max = $(this).data("max");

        let max_left_slot = [];
        $(".bdpcp-time-badge-selected").each(function () {
            max_left_slot.push($(this).data("left-slots"));
        });
        max_left_slot = Math.max(...max_left_slot);

        console.log("max_left_slot: " + max_left_slot);
        console.log("max: " + parseInt(max));
        console.log(
            "bdpcp_get_total_type_count: " + bdpcp_get_total_type_count()
        );

        if (
            (parseInt(bdpcp_count) < parseInt(max) || parseInt(max) < 0) &&
            (bdpcp_get_total_type_count() < parseInt(max_left_slot) ||
                parseInt(max_left_slot) < 0)
        ) {
            bdpcp_count++;
            $(`#bdpcp_count_${type}`).val(bdpcp_count);
            $(`#bdpcp_count_display_${type}`).html(
                `${bdpcp_count} ${bdpcp_ucfirst(type)}`
            );
            $(`#bdpcp_count_control_${type}`).html(bdpcp_count);

            $(".bdpcp-time-badge-selected").each(function () {
                let left_slots = $(this).data("left-slots");
                if (
                    parseInt(left_slots) < bdpcp_count &&
                    parseInt(left_slots) > 0
                ) {
                    $(this).addClass("bdpcp-time-badge-error");
                }
            });

            bdpcp_count_amount();
        }
    });

    function bdpcp_ucfirst(str) {
        if (!str) return "";
        return str.charAt(0).toUpperCase() + str.slice(1);
    }

    function bdpcp_get_total_type_count() {
        let total_count = 0;
        $(".bdpcp-type-count").each(function () {
            total_count += parseInt($(this).val());
        });
        return total_count;
    }

    function bdpcp_count_amount() {
        let bdpcp_booking_date = $("#bdpcp_booking_date").val();
        let bdpcp_booking_time = $("#bdpcp_booking_time").val();
        bdpcp_booking_time = [];
        let product_id = $("#bdpcp_product_id").val();
        let bdpcp_hour_count = $("#bdpcp_hour_count").val();
        let people_type_count = [];

        $(".bdpcp-type-count").each(function () {
            let type = $(this).data("people-type");
            let count = $(this).val();
            people_type_count.push({
                type: type,
                count: count,
            });
        });

        $(".bdpcp-time-badge-selected").each(function () {
            let bdpcp_slot_time = $(this).data("bdpcp-slot-time");
            bdpcp_booking_time.push(bdpcp_slot_time);
        });

        $.ajax({
            url: bdpcp_object.ajaxurl,
            type: "POST",
            data: {
                action: "bdpcp_count_amount",
                nonce: bdpcp_object.nonce,
                product_id: product_id,
                people_type_count: people_type_count,
                booking_date: bdpcp_booking_date,
                booking_time: JSON.stringify(bdpcp_booking_time),
                booking_hours: bdpcp_hour_count,
            },
            beforeSend: function () {
                $("#bdpcp_price_loading").show();
                $("#bdpcp_time_loading").show();
            },
            complete: function () {
                $("#bdpcp_price_loading").hide();
                $("#bdpcp_time_loading").hide();
            },
            success: function (response) {
                if (response.success) {
                    let time_slots = response.data.time_slots;
                    let options = ``;
                    let error_html = `Not enough slots for `;
                    let times_error_html = [];
                    for (let slot of time_slots) {
                        let extra_class = "";
                        if (
                            parseInt(bdpcp_get_total_type_count()) >
                                parseInt(slot.left_slots) &&
                            bdpcp_booking_time.includes(slot.slot_start) &&
                            parseInt(slot.left_slots) >= 0
                        ) {
                            extra_class += " bdpcp-time-badge-error";
                            times_error_html.push(slot.slot_start_display);
                        }
                        if (bdpcp_booking_time.includes(slot.slot_start)) {
                            extra_class += " bdpcp-time-badge-selected";
                        }
                        options += `<div data-left-slots="${slot.left_slots}" class="bdpcp-time-badge ${extra_class}" data-bdpcp-slot-time="${slot.slot_start}">
                                        ${slot.slot_start_display}
                                    </div>`;
                    }
                    $("#bdpcp_booking_time").html(options);
                    $("#bdpcp_price_details").html(response.data.total_amount);
                    if (times_error_html.length > 0) {
                        $("#bdpcp_time_select_error").html(
                            error_html + times_error_html.join(", ")
                        );
                    } else {
                        $("#bdpcp_time_select_error").empty();
                    }
                    $("#bdpcp_total_price_details").html(
                        response.data.price_details_html
                    );
                }
            },
            error: function (error) {
                console.error("Error updating counts:", error);
            },
        });
    }

    $(document).on("click", "#bdpcp_btn_book_now", function () {
        let bdpcp_booking_date = $("#bdpcp_booking_date").val();
        if (bdpcp_booking_date == "") {
            $("#bdpcp_booking_date").cpError("add");
            return false;
        }

        if ($(".bdpcp-time-badge").length > 0) {
            if ($(".bdpcp-time-badge-selected").length == 0) {
                $("#bdpcp_booking_time").cpError("add");
                return false;
            }
        }

        if ($(".bdpcp-type-count").length > 0) {
            if (bdpcp_get_total_type_count() == 0) {
                $(".bdpcp-people-select-control").cpError("add");
                return false;
            }
        }

        $("#bdpcp_booking_form").submit();
    });

    $(document).on(
        "click",
        ".bdpcp-people-container, .bdpcp-people-type, .bdpcp-people-actions",
        function (e) {
            e.stopPropagation();
        }
    );
});
