$(document).ready(function () {
    $(".pm-accordion-row td:first-child").click();
    setGlobalHelpUrl($("#ForeignersHelpUrl").val());
});

function setWorkPermitName(element, id) {
    const type = $(element).val();
    $("#" + id).val(null).trigger("change");
    const $select = $("#" + id);

    $select.empty().trigger("change");

    if (type) {
        $("#" + id).attr("data-url", `${$("#GetWorkPermitNameLookupItemsUrl").val()}?type=${type}`);
        const url = `${$("#GetWorkPermitNameLookupItemsUrl").val()}?type=${type}`;
        $select.attr("data-url", url);

        $.ajax({
            url: url,
            type: 'GET',
            success: function (data) {
                if (Array.isArray(data) && data.length > 0) {
                    data.forEach(item => {
                        $select.append(new Option(item.Key, item.Value));
                    });

                    $select.val(data[0].Key).trigger("change");
                }
            }
        });
    }
}

function setWorkPermitIssuerValues(isuerId, issuerNameId) {
    if ($("#" + isuerId).val()) {
        const selectedIssuer = $("#select2-" + isuerId + "-container").attr("title");

        if (selectedIssuer.indexOf("|") > -1) {
            const splitted = selectedIssuer.split(" | ");
            $("#" + issuerNameId).val(splitted[1]);
        }
    }
    else {
        $("#" + issuerNameId).val("");
    }
}

function toggleDateTimeReadonly(unlimitedId, workPerToId) {
    const datepicker = $("#" + workPerToId);

    if ($("#" + unlimitedId).is(":checked")) {
        datepicker.prop("readonly", true);
    } else {
        datepicker.prop("readonly", false);
    }
}

function saveForeignerData() {
    if ($('.isDirty').length === 0) {
        return;
    }
    else if ($("#IsFirstForeignerEntry").val() === "True" && $("#isLocSI").val() === "True") {
        openForeignerIRISModal();
    }
    else {
        saveForeignerDataAsync();
    }
}

function saveForeignerDataAsync(isTaxReduct = false) {
    const newForeigner = getForeignerData(isTaxReduct);

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

function getForeignerData(isTaxReduct) {
    return {
        Qid: $("#ForeignerQId").val(),
        Worker: $("#ModelWorker").val(),
        WorkPermitNo: $("#WorkPermitNo").val(),
        WorkPerIssu: $("#WorkPerIssu").val(),
        WorkPerToUnLtd: $("#WorkPerToUnLtd").is(':checked'),
        WorkPerFrom: $("#WorkPerFrom").val(),
        WorkPerTo: $("#WorkPerTo").val(),
        ResidVisaFrom: $("#ResidVisaFrom").val(),
        VisaTo: $("#VisaTo").val(),
        WorkPermitType: $("#WorkPermitType").val(),
        WorkPermitName: $("#WorkPermitName").val(),
        ResidVisaNum: $("#ResidVisaNum").val(),
        ResidVisaIssuer: $("#ResidVisaIssuer").val(),
        CountryResidency: $("#CountryResidency").val(),
        VisaUnLtd: $("#VisaUnLtd").is(':checked'),
        IsTaxReduct: isTaxReduct
    }
}

function openForeignerIRISModal() {
    $('#iris-header').text($('#ForeignersIncomeTaxRelief').val());
    $('#iris-message').text($('#DoYouWantToExcludeGeneralReliefForForeigner').val());
    $('#option-1-header').text($('#Confirm').val());
    $('#option-1-text').text($('#SelectPeriodForExcludingGeneralReliefInTaxCalculation').val());
    $('#option-2-header').text($('#CancelIRIS').val());
    $('#option-2-text').text($('#GeneralReliefIncludedInTaxBaseCalculation').val());
    $('#option-3-header').text($('#ViewInstructions').val());
    $('#option-3-text').text($('#PoIrisHelpDesc').val());

    $('#option-1-clickable').click(function () {
        saveForeignerDataAsync(true)
    });

    $('#option-2-clickable').click(function () {
        saveForeignerDataAsync();
    });

    $('#option-3-clickable').click(function () {
        window.open($('#ForeignersTaxReductHelpUrl').val(), '_blank')
    });

    $('#blank-iris').modal('show');
}

function deleteForeignerHistoryItem(qId, worker) {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "question",
        text: $("#ConfirmDeleteMessage").val(),
        buttons: [
            {
                icon: 'fa fa-times',
                text: $("#Cancel").val(),
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: $("#Confirm").val(),
                action: function () {
                    deleteForeignerHistoryItemAsync(qId, worker);
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function deleteForeignerHistoryItemAsync(qId, worker) {
    $.ajax({
        type: "DELETE",
        url: $("#DeleteForeignerHistoryItemUrl").val(),
        data: {
            qId: qId,
            worker: worker
        },
        success: function (data) {
            if (data && data.result && data.result.Status === true) {
                $("#foreigner-history-" + qId).remove();
            }
        }
    });
}

let selectedNoteNo = '';
function openNoteModal(id) {
    selectedNoteNo = id;
    $("#item-note").val($("#NoteId-" + id).val());
    $('#note-modal').modal('show');
}

function saveNote() {
    $.ajax({
        url: $("#SaveForeignerHistoryNoteUrl").val(),
        method: 'POST',
        data: {
            qId: selectedNoteNo,
            note: $("#item-note").val()
        },
        success: function (data) {
            if (data && data.result && data.result.Note && data.result.Note.trim() !== '') {
                $("#NoteId-" + selectedNoteNo).val(data.result.Note);
                $("#Note-button-" + selectedNoteNo).addClass('text-primary');
            } else {
                $("#Note-button-" + selectedNoteNo).removeClass('text-primary');
            }
        }
    });
}