function addEmployeeHealth() {
    const newEmployeeHealth = getEmployeeHealthData(0);

    $.ajax({
        type: "POST",
        url: $("#AddEmployeeHealthUrl").val(),
        data: newEmployeeHealth,
        success: function (data) {
            if (data) {
                handleNewRow(data);
                clearNewEmployeeHealthFields();
                initializeDateTimePicker();
            }
        }
    });
}

function saveEmployeeHealthData() {
    const data = { EmployeeHealth: [], EmployeeDisability: [] };

    $(".isDirty").each(function () {
        const rowId = $(this).attr("id").split("-")[1];
        if (rowId === "new") {
            return true;
        }
        if ($(this).hasClass("disability-row")) {
            const disabilityData = getEmployeeDisabilityData(rowId);
            data.EmployeeDisability.push(disabilityData);
        } else {
            const healthData = getEmployeeHealthData(rowId);
            data.EmployeeHealth.push(healthData);
        }
    });

    if (!areDisabilitesValid(data.EmployeeDisability)) {
        return;
    }

    if (data.EmployeeHealth.length > 0 || data.EmployeeDisability.length > 0) {
        $.ajax({
            type: "POST",
            url: $("#SaveAllEmployeeHealthDataUrl").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 deleteEmployeeHealth(healthId) {
    $.ajax({
        type: "DELETE",
        url: $("#DeleteEmployeeHealthUrl").val(),
        data: {
            worker: $("#ModelWorker").val(),
            id: $(`#EmployeeHealthId-${healthId}`).val(),
        },
        success: function (data) {
            if (data.isDeleted) {
                $(`#EmployeeHealthId-${healthId}`).closest("div").remove();
            }
        }
    });
}

function getEmployeeHealthData(itemId) {
    return {
        Worker: $(`#ModelWorker`).val(),
        Id: $(`#EmployeeHealthId-${itemId}`).val(),
        QId: $(`#EmployeeHealthQId-${itemId}`).val(),
        DisabilityCode: $(`#DisabilityCode-${itemId}`).val(),
        Disability: $(`#Disability-${itemId}`).val(),
        CreationCause: $(`#CreationCause-${itemId}`).val(),
        CreationDate: $(`#CreationDate-${itemId}`).val(),
        PhysicalMalfunction: $(`#PhysicalMalfunction-${itemId}`).val(),
        PhysicalMalfunctionCode: $(`#PhysicalMalfunctionCode-${itemId}`).val(),
        PhysicalMalfunctHelpService: $(`#PhysicalMalfunctHelpService-${itemId}`).is(':checked'),
        InjuryCreationDate: $(`#InjuryCreationDate-${itemId}`).val(),
        Decision: $(`#Decision-${itemId}`).val(),
        DateDecision: $(`#DateDecision-${itemId}`).val(),
        Descr: $(`#Descr-${itemId}`).val(),
        DiseaseCode: $(`#DiseaseCode-${itemId}`).val(),
        Foundation: $(`#Foundation-${itemId}`).val(),
        ResidualAbilityWork: $(`#ResidualAbilityWork-${itemId}`).val(),
    };
}

function clearNewEmployeeHealthFields() {
    $("#collapse-new-health").find("select").each(function () {
        $(this).val(null).trigger('change');
    });

    $("#collapse-new-health").find("input, textarea").each(function () {
        $(this).val('');
    });
}

function handlePhysicalMalfunctHelpService(element) {
    const rowNum = $(element).attr("id").split("-")[1];
    const helpCheckbox = $("#PhysicalMalfunctHelpService-" + rowNum);

    if ($(element).val() == "1" && $("#IsLocSI").val() == "True") { // When PhysicalMalfunction equals 1 and SI loc.
        helpCheckbox.closest(".form-group").removeClass("hidden");
    } else {
        helpCheckbox.closest(".form-group").addClass("hidden");

        if (helpCheckbox.prop("checked")) {
            helpCheckbox.trigger("click");
        }
    }
}

// Disability
function addDisability() {
    const data = getEmployeeDisabilityData(0)

    if (!isDisabilityValid(data.PeriodStart)) {
        return;
    }

    $.ajax({
        url: $("#AddEmployeeDisabilityUrl").val(),
        type: 'POST',
        data: data,
        success: function (data) {
            if (data) {
                handleNewDisabilityRow(data);
                clearNewEmployeeDisabilityFields();
            }
        }
    });
}

function deleteDisability(disabilityId) {
    $.ajax({
        type: "DELETE",
        url: $("#DeleteEmployeeDisabilityUrl").val(),
        data: {
            worker: $("#ModelWorker").val(),
            periodStart: $(`#PeriodStart-${disabilityId}`).val(),
        },
        success: function (data) {
            if (data.isDeleted) {
                $(`#PeriodStart-${disabilityId}`).closest("tr").remove();
            }
        }
    });
}

function getEmployeeDisabilityData(itemId) {
    return {
        Worker: $(`#ModelWorker`).val(),
        DisableQuota: $("#DisableQuota-" + itemId).is(':checked'),
        PeriodStart: $("#PeriodStart-" + itemId).val(),
        PeriodEnd: $("#PeriodEnd-" + itemId).val(),
        DisabilityType: $("#DisabilityType-" + itemId).val(),
        QId: $("#EmployeeDisabilityQId-" + itemId).val()
    };
}
function handleNewDisabilityRow(data) {
    $(".disability-wrapper tbody").append(data);
    forEveryHTMLElement('.disability-wrapper .disability-row:last-child .select2', initializeSelect2ByElement);
    $(".disability-wrapper .disability-row:last-child .custom-checkbox").customCheckbox();
}

function clearNewEmployeeDisabilityFields() {
    $("#disability-new").find("select").each(function () {
        $(this).val(null).trigger('change');
    });

    $("#DisableQuota-0").prop('checked', false);
}

function isDisabilityValid(periodStart) {
    if (!periodStart) {
        displayDisabilityPariodStartModal(true);

        return false;
    }

    const isUnique = $('select[name="PeriodStart"]').slice(1).toArray().every(elem => $(elem).val() !== periodStart);
    if (!isUnique) {
        displayDisabilityPariodStartModal();

        return false;
    }

    return true;
}

function areDisabilitesValid(disabilities) {
    const allDisabilitiesHavePeriodStart = disabilities.every(entry => entry.PeriodStart);
    if (!allDisabilitiesHavePeriodStart) {
        displayDisabilityPariodStartModal(true);

        return false;
    }

    // Check if each period start value is unique among the rest
    const areUniquePeriodStartElements = $('select[name="PeriodStart"]')
        .slice(1)
        .toArray()
        .every((elem, index, array) => {
            const currentValue = $(elem).val();
            return array.every((otherElem, otherIndex) => {
                // Skip comparison with itself
                return otherIndex === index || $(otherElem).val() !== currentValue;
            });
        });

    if (!areUniquePeriodStartElements) {
        displayDisabilityPariodStartModal();

        return false;
    }

    return true;
}

function displayDisabilityPariodStartModal(isEmpty = false) {
    const message = isEmpty
        ? $("#RequiredInput").val() + " " + $("#PeriodFrom").val()
        : $("#DisabilityPeriodStartNotUnique").val();

    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: 'alert',
        text: message,
        buttons: [
            {
                icon: 'fa fa-check',
                text: $("#custom-modal-confirm").val(),
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}
