$(document).ready(function () {
    initializeDrivingLicenceDropdowns();
});

function addBooklet() {
    const newBooklet = getBookletData(0);

    $.ajax({
        type: "POST",
        url: $("#AddBookletUrl").val(),
        data: newBooklet,
        success: function (data) {
            window.location.href = data.indexUrl;
        }
    });
}

function saveBooklets() {
    const data = [];

    $(".isDirty").each(function () {
        const bookletId = $(this).attr("id").split("-")[1];

        const bookletData = getBookletData(bookletId);
        data.push(bookletData);
    });

    if (data.length > 0) {
        $.ajax({
            type: "POST",
            url: $("#SaveBookletUrl").val(),
            contentType: "application/json",
            data: JSON.stringify(data),
            success: function (data) {
                if (data.Status) {
                    location.reload();
                } else {
                    showDefaultErrorCustomModal($("#GeneralErrorMessage").val(), $("#custom-modal-confirm").val());
                }
            },
            error: function () {
                showDefaultErrorCustomModal($("#GeneralErrorMessage").val(), $("#custom-modal-confirm").val());
            }
        });
    }   
 }

function deleteBooklet(qId, id) {
    $.ajax({
        type: "DELETE",
        url: $("#DeleteBookletUrl").val(),
        data: {
            worker: $("#ModelWorker").val(),
            qid: qId
        },
        success: function (data) {
            if (data.isDeleted) {
                $(`#BookletId-${id}`).closest("div").remove();
            }
        }
    });
}

function getBookletData(itemId) {
    return {
        Id: $(`#BookletId-${itemId}`).val(),
        Qid: $(`#BookletQid-${itemId}`).val(),
        Worker: $(`#ModelWorker`).val(),
        Type: $(`#Type-${itemId}`).val(),
        Active: $(`#IsActive-${itemId}`).is(':checked'),
        Number: $(`#Number-${itemId}`).val(),
        SerialNo: $(`#SerialNumber-${itemId}`).val(),
        Issuer: $(`#Issuer-${itemId}`).val(),
        DateIssue: $(`#DateOfIssue-${itemId}`).val(),
        CityIssue: $(`#InvoiceLocation-${itemId}`).val(),
        DateValid: $(`#EffectiveDate-${itemId}`).val(),
        Category: $(`#Category-${itemId}`).val(),
        Note: $(`#Note-${itemId}`).val()
    }
}

function initializeDrivingLicenceDropdowns() {
    $('.driving-lic-dropdown').each(function () {
        const $dropdown = $(this);
        const $chBoxes = $dropdown.find('.driving-lic-dropdown-menu input[type="checkbox"]');
        const $dpInput = $dropdown.find('.driving-lic-input');
        const $selectedItemsContainer = $dropdown.find('.driving-lic-selected-items');
        let mySelectedListItems = [];

        function handleCB() {
            mySelectedListItems = [];
            $selectedItemsContainer.empty();

            $chBoxes.each(function () {
                if ($(this).is(':checked')) {
                    const value = $(this).val();
                    mySelectedListItems.push(value);
                    
                    const selectedCategories = $dropdown.find(".driving-lic-selected-categories");
                    let formatted = mySelectedListItems.join(";");
                    selectedCategories.val(formatted);
                    
                    const selectedItem = $('<span class="driving-lic-selected-item">' + value + '<span class="driving-lic-remove-item">x</span></span>');
                    $selectedItemsContainer.append(selectedItem);
                    selectedItem.find('.driving-lic-remove-item').on('click', function () {
                        $(this).parent().remove();
                        $chBoxes.filter('[value="' + value + '"]').prop('checked', false);
                        setIsDirty($chBoxes.filter('[value="' + value + '"]'));
                        handleCB();
                    });
                }
            });

            $dpInput.val(
                mySelectedListItems.length > 0
                    ? ''
                    : 'Select'
            );
        }

        $dpInput.on('click', function () {
            $('.driving-lic-dropdown-menu').not($dropdown.find('.driving-lic-dropdown-menu')).hide(); // Hide other dropdown menus
            $dropdown.find('.driving-lic-dropdown-menu').toggle();
        });

        $chBoxes.on('change', handleCB);

        $(document).on('click', function (event) {
            if (!$(event.target).closest('.driving-lic-dropdown').length) {
                $('.driving-lic-dropdown-menu').hide();
            }
        });

        // Initialize with pre-selected checkboxes
        handleCB();
    });
}

function setCategoryField(element, id) {
    if ($(`#${element.id}`).val() === $("#DrivingLicenceType").val()) {
        $(`#DrivingLicence-${id}`).removeClass("hidden");
    }
    else {
        $(`#DrivingLicence-${id}`).addClass("hidden");

        $(`#Category-${id}`).val("");
        $(`.category-checkbox-${id}:checkbox:checked`).each(function () {
            $(this).prop('checked', false);
        });
        $(`#SelectedCategoryBoxes-${id}`).empty();
    }
}