$(document).ready(function () {

    var selectedPackageId = $('#selected_package_id').val();

    $('#event_date_time').datetimepicker({
        theme: 'dark',
        format: "d-M-Y h:i A",
        formatTime: 'h:i A',
        step: 30,
        defaultSelect: false,
        datepicker: true,
        timepicker: true,
        minDate: 0,
        validateOnBlur: false
    });

    $('#event_date_time').on('change', function () {
        var dateTime = $('#event_date_time').datetimepicker('getValue');
        if (dateTime) {
            var year = dateTime.getFullYear();
            var month = dateTime.getMonth(); // Month is 0-indexed
            var day = dateTime.getDate();

            let hours = dateTime.getHours();
            let minutes = dateTime.getMinutes();

            if (minutes > 0 && minutes <= 30) {
                minutes = 30;
            } else if (minutes > 30) {
                minutes = 0;
                hours += 1;
            }

            var roundedDate = new Date(year, month, day, hours, minutes, 0);

            $('#event_date_time').val('');
            $('#event_date_time').datetimepicker('setOptions', {
                value: roundedDate
            });
        }
    });

    loadSelect2(['#eventType', 'select[name="addonsList[]"]', '#eventStatus']);

    $('#packageList').select2({
        placeholder: 'Select Package',
        templateResult: formatPackage,
        templateSelection: formatPackage,
    });

    $.post('book_us.php', {
        type: 'packageList'
    }, function (response) {
        if (response && response.items) {
            $('#packageList').empty();

            $('#packageList').append('<option value="" data-amt="">Select Package</option>');

            $.each(response.items, function (index, data) {
                $('#packageList').append(`<option value="${data.id}" data-amt="${data.amt}" data-discount="${data.discount_amt}" data-after-discount="${data.after_discount}">${data.name}</option>`);
            });

            if (selectedPackageId) {
                $('#packageList').val(selectedPackageId).trigger('change');
            } else {
                $('#packageList').trigger('change');
            }
        }
    }, 'json');

    function formatPackage(package) {
        if (!package.id) {
            return package.text;
        }

        var amount = $(package.element).data('amt');
        var discountAmount = $(package.element).data('discount');
        var afterDiscount = $(package.element).data('after-discount');

        var formattedText = `<span>${package.text}</span> - `;
        if (discountAmount > 0) {
            formattedText += `<span class="text-danger"><del>${sCurrencySymbol() + amount}</del></span> `;
        }
        formattedText += `<span>${sCurrencySymbol() + afterDiscount}</span>`;

        return $(formattedText);
    }

    $('#packageList, #eventType, #eventStatus').on('select2:open select2:open select2:open', function (e) {
        $('.select2-dropdown').addClass('custom-form-1');
    });

    function conditional_form() {
        $('.s-cond-field').hide();
        $('#groom_name, #bride_name, #birthday_person, #organization_name, #amount, #location, #event_date_time').prop('required', false);

        var eventType = $('#eventType').val();
        var package = $('#packageList').val();

        if (eventType == 0 || eventType == null) {
            $('.s-cond-field').hide();
        }

        if (
            eventType == 1 ||   // Wedding
            eventType == 2 ||   // Reception
            eventType == 3 ||   // Engagement
            eventType == 4 ||   // Halud
            eventType == 5 ||   // Mehadi
            eventType == 6 ||   // Akhd
            eventType == 7 ||   // Anniversary
            eventType == 8 ||   // Rong Khela
            eventType == 9      // Ashirbad
        ) {
            $('.groom_name, .packages_Field').show();
            $('#groom_name, #bride_name').prop('required', true);
        } else if (eventType == 10) { // Birthday
            $('.birthday_person, .packages_Field').show();
            $('#birthday_person').prop('required', true);
        } else if (
            eventType == 11 ||  // Architectural
            eventType == 12     // Corporate
        ) {
            $('.organization_name, .amount, .location_event_date_time').show();
            $('#organization_name, #amount, #location, #event_date_time').prop('required', true);
        } else if (eventType == 13) { // Fashion & Lifetyle
            $('.amount, .location_event_date_time').show();
            $('#amount, #location, #event_date_time').prop('required', true);
        }

        if (
            package == 1 ||   // Standard - I
            package == 2 ||   // Standard - II
            package == 3 ||   // Standard - III
            package == 4 ||   // Premium - I
            package == 5 ||   // Premium - II
            package == 6 ||   // Premium - III
            package == 7 ||   // Elite - I
            package == 8 ||   // Elite - II
            package == 9 ||   // Sonaton - Standrad
            package == 10 ||  // Sonaton - Premium
            package == 11 ||  // Only Photography
            package == 12     // Only Photography - Premium
        ) {
            $('.addons_Field, .location_event_date_time, .song_preference, .your_preference').show();
            $('#location, #event_date_time').prop('required', true);
        } else if (package == 13) { // Other
            $('.addons_Field, .amount, .location_event_date_time, .your_preference').show();
            $('#amount, #location, #event_date_time').prop('required', true);
        }
    }

    $('#eventType, #packageList').change(function () {
        conditional_form();
    });

    conditional_form();

    function loadAddOns() {
        $.post('book_us.php', {
            type: 'addOnsList'
        }, function (response) {
            if (response && response.addons) {
                var newAddonDiv = $('<div class="d-flex align-items-center mb-1"></div>');
                var newSelect = $('<select name="addonsList[]" class="form-control me-2">' +
                    '<option value="">Select ADD-ONS</option>' +
                    response.addons.map(function (addon) {
                        return '<option value="' + addon.id + '" data-amt="' + addon.amt + '">' + addon.name + ' - ' + sCurrencySymbol() + addon.amt + '</option>';
                    }).join('') +
                    '</select>');
                var removeButton = $('<button type="button" class="btn btn-sm text-danger btn-no-border" data-bs-toggle="tooltip" data-bs-title="Remove this addon"><i class="bi bi-dash-lg"></i></button>');
                if ($('select[name="addonsList[]"]').length >= 1) {
                    newAddonDiv.append(newSelect).append(removeButton);
                } else {
                    newAddonDiv.append(newSelect);
                }

                $('#addons-container').append(newAddonDiv);
                loadSelect2([newSelect]);

                $('select[name="addonsList[]"]').on('select2:open', function (e) {
                    $('.select2-dropdown').addClass('custom-form-1');
                });

                removeButton.on('click', function () {
                    const tooltip = bootstrap.Tooltip.getInstance(this);
                    if (tooltip) tooltip.dispose();

                    $(this).parent('.d-flex').remove();
                });

                new bootstrap.Tooltip(removeButton);
            }
        }, 'json');
    }

    function validateAddOns() {
        var addOnsList = Array.from(document.getElementsByName('addonsList[]'));
        var isValid = true;

        addOnsList.forEach(element => {
            var selectedOption = $(element).find('option:selected').val();

            if (!selectedOption) {
                $(element).next('.select2').find('.select2-selection').addClass('border-danger');
                isValid = false;
            } else {
                $(element).next('.select2').find('.select2-selection').removeClass('border-danger');
            }
        });

        return isValid;
    }

    loadAddOns();

    $('#anotherAddOns').on('click', function () {
        if (validateAddOns()) {
            loadAddOns();
        } else {
            swal('Please select an ADD-ONS & try again', {
                icon: "error",
            });
        }
    });

});

function bookEvent(eventId) {
    var clientName = $.trim($('#client_name').val());
    var contactNo = $.trim($('#contact_no').val());
    var email = $.trim($('#email').val());
    var eventType = $.trim($('#eventType').val());
    var groomName = $.trim($('#groom_name').val());
    var brideName = $.trim($('#bride_name').val());
    var birthdayPerson = $.trim($('#birthday_person').val());
    var organizationName = $.trim($('#organization_name').val());
    var packageList = $.trim($('#packageList').val());
    var amount = $.trim($('#amount').val());
    var location = $.trim($('#location').val());
    var eventDateTime = $.trim($('#event_date_time').val());
    var songPreference = $.trim($('#song_preference').val());

    var addOnsList = Array.from(document.getElementsByName('addonsList[]'));

    var addons = [];
    addOnsList.forEach(element => {
        var selectedOption = $(element).find('option:selected').val();

        if (selectedOption) {
            addons.push(selectedOption);
        }
    });
    var addonsStr = addons.join(',')

    // Validation
    if (!clientName || !contactNo || !email) {
        alert('Please fill in all required fields.');
        return;
    }

    // Validate email format
    if (!sEmail(email)) {
        alert('Invalid email format');
        return;
    }

    // Collect the preferences
    var preferences = [];
    if ($('#couplePhotos').is(':checked')) {
        preferences.push('Couple Photos');
    }
    if ($('#candidPhotos').is(':checked')) {
        preferences.push('Candid Photos');
    }
    if ($('#outdoorPhotos').is(':checked')) {
        preferences.push('Outdoor Photos');
    }
    if ($('#familyPhotos').is(':checked')) {
        preferences.push('Family Photos');
    }
    if ($('#guestPhotos').is(':checked')) {
        preferences.push('Guest Photos');
    }
    if ($('#others').is(':checked')) {
        preferences.push('Others');
    }

    var preferencesStr = preferences.join(',')

    var eventStatus = '';
    if ($('#eventStatus').length > 0) { // check for element is valid or available
        eventStatus = $('#eventStatus').val().trim();
    }

    // Prepare the data to be sent in the AJAX request
    var data = {
        id: eventId,
        client_name: clientName,
        contact_no: contactNo,
        email: email,
        event_type: eventType,
        groom_name: groomName,
        bride_name: brideName,
        birthday_person: birthdayPerson,
        organization_name: organizationName,
        package: packageList,
        amount: amount,
        location: location,
        event_date_time: eventDateTime,
        song_preference: songPreference,
        addons: addonsStr,
        your_preference: preferencesStr,
        event_status: eventStatus
    };

    var type = (eventId) ? 'update_frm' : 'submit_frm';

    $.ajax({
        type: "post",
        url: "book_us.php",
        data: {
            type: type,
            frmData: data
        },
        success: function (response) {
            if (response.success) {
                if (response.message == "update") {
                    sAlert('Event information updated!', '', 'success');
                } else {
                    var url = window.location.href + '?orderNumber=' + response.eventId;
                    window.location.href = url;
                    sAlert("", response.message, "success");
                }

            } else {
                sAlert("Error!", response.message, "error");
            }
        }
    });

}

function AddEventAddOns(eventId) {
    event.preventDefault();

    $.ajax({
        type: "post",
        url: "modal_add_event_addons.php",
        data: {
            eventId: eventId,
        },
        success: function (sData) {
            $("#modalDiv").html("");
            $("#modalDiv").append(sData);
            $("#modalModal").modal("show");
        },
    });

}

function DeleteEventAddons(id) {
    event.preventDefault();
    swal({
        title: "Are you sure?",
        text: "Once deleted, you will not be able to recover this collection!",
        icon: "warning",
        buttons: true,
        dangerMode: true,
    }).then((willDelete) => {
        if (willDelete) {
            $.ajax({
                type: "post",
                url: "book_us.php",
                data: {
                    type: "deao",
                    id: id
                },
                success: function (response) {
                    if (response.success) {
                        if (response.message == "d") {
                            window.location.reload();
                        }
                    } else {
                        swal({
                            title: "Error!",
                            text: response.message,
                            icon: "error",
                            button: "OK",
                        })
                    }
                }
            });
        }
    });

}