function addFamilyMember() {
    const newFamilyMember = getFamilyMemberData(0);

    $.ajax({
        type: "POST",
        url: $("#AddFamilyMemberUrl").val(),
        data: newFamilyMember,
        success: function (data) {
            if (data) {
                handleNewRow(data);
                clearNewFamilyMemberFields();
                initializeDateTimePicker();
            }
        }
    });
}

function saveFamilyMemberData() {
    const data = [];

    $(".isDirty").each(function () {
        const familyId = $(this).attr("id").split("-")[1];
        if (familyId === "new") {
            return true;
        }

        const familyData = getFamilyMemberData(familyId);
        data.push(familyData);
    });

    if (data.length > 0) {
        $.ajax({
            type: "POST",
            url: $("#SaveFamilyMemberDataUrl").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 deleteFamilyMember(familyId) {
    $.ajax({
        type: "DELETE",
        url: $("#DeleteFamilyMemberUrl").val(),
        data: {
            worker: $("#ModelWorker").val(),
            id: $(`#FamilyMemberId-${familyId}`).val(),
        },
        success: function (data) {
            if (data.isDeleted) {
                $(`#FamilyMemberId-${familyId}`).closest("div").remove();
            }
        }
    });
}

function getFamilyMemberData(itemId) {
    return {
        // Basic data
        AcWorker: $(`#ModelWorker`).val(),
        AnId: $(`#FamilyMemberId-${itemId}`).val(),
        AnQId: $(`#FamilyMemberQId-${itemId}`).val(),
        AcName: $(`#AcName-${itemId}`).val(),
        AcSurname: $(`#AcSurname-${itemId}`).val(),
        AcUcn: $(`#AcUcn-${itemId}`).val(),
        AdDateBirth: $(`#AdDateBirth-${itemId}`).val(),
        AcTaxId: $(`#AcTaxId-${itemId}`).val(),
        AcBirthPost: $(`#AcBirthPost-${itemId}`).val(),
        AcBirthCity: $(`#AcBirthCity-${itemId}`).val(),
        AcRelative: $(`#AcRelative-${itemId}`).val(),
        AcSex: $(`#AcSex-${itemId}`).val(),
        AcBirthSurname: $(`#AcBirthSurname-${itemId}`).val(),
        AcCountryCitizenship: $(`#AcCountryCitizenship-${itemId}`).val(),
        AcCitizenship: $(`#AcCitizenship-${itemId}`).val(),
        AcUpheld: $(`#AcUpheld-${itemId}`).val(),
        CalcZSVarPre: $(`#ZSVarPreField-${itemId}`).attr('hidden') ? '' : $(`#CalcZSVarPre-${itemId}`).val(),

        // Permanent residence data
        AcResidPermStreet: $(`#AcResidPermStreet-${itemId}`).val(),
        AcResidPermPost: $(`#AcResidPermPost-${itemId}`).val(),
        AcResidPermCity: $(`#AcResidPermCity-${itemId}`).val(),
        AcResidPermMunicip: $(`#AcResidPermMunicip-${itemId}`).val(),
        AcResidPermCountry: $(`#AcResidPermCountry-${itemId}`).val(),

        // Temporary residence data
        AcResidTempStreet: $(`#AcResidTempStreet-${itemId}`).val(),
        AcResidTempPost: $(`#AcResidTempPost-${itemId}`).val(),
        AcResidTempCity: $(`#AcResidTempCity-${itemId}`).val(),
        AcResidTempMunicip: $(`#AcResidTempMunicip-${itemId}`).val(),
        AcResidTempCountry: $(`#AcResidTempCountry-${itemId}`).val(),
        AdVisaFrom: $(`#AdVisaFrom-${itemId}`).val(),
        AdVisaTo: $(`#AdVisaTo-${itemId}`).val()
    }
}

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

    $("#collapse-new-family-member").find("input").each(function () {
        $(this).val('');
    });

    var upheldCheckBox = $("#collapse-new-family-member").find("#AcUpheld-0");

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

    $("#AcSurname-0").val($("#InitialSurname").val());

    $("#AcResidPermStreet-0").val($("#InitialPermStreet").val());
    $("#AcResidPermCity-0").val($("#InitialPermCity").val());
    $("#AcResidPermPost-0").val($("#InitialPermPost").val()).trigger('change');
    $("#AcResidPermCountry-0").val($("#InitialPermCountry").val()).trigger('change');

    $("#AcResidTempStreet-0").val($("#InitialTempStreet").val());
    $("#AcResidTempCity-0").val($("#InitialTempCity").val());
    $("#AcResidTempPost-0").val($("#InitialTempPost").val()).trigger('change');
    $("#AcResidTempCountry-0").val($("#InitialTempCountry").val()).trigger('change');
}

function toggleHiddenZsVarField(checkbox, id) {
    $(`#ZSVarPreField-${id}`).attr('hidden', !$(checkbox).is(':checked'));
}

function setRegionByPostCode(postField, regionField) {
    var post = $(postField).val();

    $.ajax({
        type: "GET",
        url: $("#GetRegionByPostCodeUrl").val(),
        data: { post },
        success: function (data) {
            if (data) {
                $(regionField).val(data);
            }
        }
    });
}

function setCitizenshipByCountry(countryField, citizenshipField) {
    var country = $(countryField).val();

    $.ajax({
        type: "GET",
        url: $("#GetCitizenshipByCountryUrl").val(),
        data: { country },
        success: function (data) {
            if (data) {
                $(citizenshipField).val(data);
            } else {
                $(citizenshipField).val(null);
            }
        }
    });
}