// Please see documentation at https://learn.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.

// Write your JavaScript code.
function parseValue(value, type = "string") {
    if (type === "string") {
        return value;
    }

    if (value === "") return null;

    // Boolean
    if (value.toLowerCase() === "true") return true;
    if (value.toLowerCase() === "false") return false;

    // Number
    if (!isNaN(value) && value.trim() !== "") return Number(value);

    // ISO dátum formátum felismerése (alap logika)
    if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(value)) return new Date(value).toISOString();

    return value;
}
function getFormAsNestedObject(formSelector) {
    var formArray = $(formSelector).serializeArray();
    var result = {};

    formArray.forEach(function (item) {
        var keys = item.name.split('.');
        var inputElement = document.querySelector(`[name="${item.name}"]`);
        var type = inputElement?.dataset?.type || "string"; // ha nincs data-type, alap: string
        var value = parseValue(item.value, type);
        var current = result;

        for (var i = 0; i < keys.length; i++) {
            var key = keys[i];

            if (i === keys.length - 1) {
                current[key] = value;
            } else {
                if (!current[key]) {
                    current[key] = {};
                }
                current = current[key];
            }
        }
    });

    return result;
}

function showConfirmModal(options) {
    return new Promise(function (resolve) {
        // Alapértelmezett értékek
        var defaults = {
            title: 'Megerősítés',
            message: 'Biztos vagy benne?',
            okText: 'Igen',
            cancelText: 'Mégsem'
        };

        // Opciók összeolvasztása
        var settings = $.extend({}, defaults, options);

        // Beállítások betöltése a modalba
        $('#confirmModalLabel').text(settings.title);
        $('#confirmModalBody').html(settings.message);
        $('#confirmModalOkBtn').text(settings.okText);
        $('#confirmModalCancelBtn').text(settings.cancelText);

        // Események letisztítása
        $('#confirmModalOkBtn').off('click');
        $('#confirmModalCancelBtn').off('click');

        // OK gomb esemény
        $('#confirmModalOkBtn').on('click', function () {
            $('#confirmModal').modal('hide');
            resolve('ok');
        });

        // Cancel gomb esemény
        $('#confirmModalCancelBtn').on('click', function () {
            resolve('cancel');
        });

        // Modal megjelenítése
        var modal = new bootstrap.Modal(document.getElementById('confirmModal'), {
            backdrop: 'static',
            keyboard: false
        });
        modal.show();
    });
}
function showConfirmModalWithMessage(options) {
    return new Promise(function (resolve) {
        // Alapértelmezett értékek
        var defaults = {
            title: 'Megerősítés',
            message: 'Biztos vagy benne?',
            okText: 'Igen',
            cancelText: 'Mégsem'
        };

        // Opciók összeolvasztása
        var settings = $.extend({}, defaults, options);

        // Beállítások betöltése a modalba
        $('#confirmModalLabel').text(settings.title);
        $('#confirmModalBody').html(`
            <label for="confirmModalTextarea" class="form-label">${settings.message}</label>
            <textarea class="form-control" id="confirmModalTextarea" rows="4" placeholder="Írd ide..."></textarea>
            <div class="invalid-feedback">A mező kitöltése kötelező.</div>
        `);
        $('#confirmModalOkBtn').text(settings.okText);
        $('#confirmModalCancelBtn').text(settings.cancelText);

        // Események letisztítása
        $('#confirmModalOkBtn').off('click');
        $('#confirmModalCancelBtn').off('click');

        // OK gomb esemény
        $('#confirmModalOkBtn').on('click', function () {
            var text = $('#confirmModalTextarea').val().trim();
            if (text === '') {
                $('#confirmModalTextarea').addClass('is-invalid');
                return;
            }
            $('#confirmModalTextarea').removeClass('is-invalid');

            $('#confirmModal').modal('hide');
            resolve({ action: 'ok', text: text });
        });

        // Cancel gomb esemény
        $('#confirmModalCancelBtn').on('click', function () {
            $('#confirmModal').modal('hide');
            resolve({ action: 'cancel' });
        });

        // Modal megjelenítése
        var modal = new bootstrap.Modal(document.getElementById('confirmModal'), {
            backdrop: 'static',
            keyboard: false
        });
        modal.show();
    });
}
function showMessageModal(options) {
    // Alapértelmezett értékek
    var defaults = {
        title: 'Üzenet',
        message: 'Ez egy információs üzenet.',
        okText: 'OK',
        redirectUrl: null
    };

    var settings = $.extend({}, defaults, options);

    // Tartalom beállítása
    $('#messageModalLabel').text(settings.title);
    $('#messageModalBody').html(settings.message);
    $('#messageModalOkBtn').text(settings.okText);

    $('#messageModalOkBtn').off('click').on('click', function () {
        if (settings.redirectUrl) {
            window.location.href = settings.redirectUrl;
        }
    });

    // Modal megnyitása
    var modal = new bootstrap.Modal(document.getElementById('messageModal'), {
        backdrop: 'static',
        keyboard: false
    });
    modal.show();
}

function renderActionButtons(rowId) {
    return `
        <button class="btn btn-primary edit-btn btn-sm" data-id="${rowId}">
            <i class="bi bi-pencil-fill"></i>
        </button>
        <button class="btn btn-danger delete-btn btn-sm" data-id="${rowId}">
            <i class="bi bi-trash-fill"></i>
        </button>
    `;
}
function renderActionButtonsDownloadImages(rowId) {
    return `
        <button class="btn btn-primary download-btn btn-sm" data-id="${rowId}">
            <i class="bi bi-file-earmark-arrow-down"></i>
        </button>`;
}
function renderActionButtonsDownloadPDFs(rowId) {
    return `
        <button class="btn btn-primary download-btn btn-sm" data-id="${rowId}">
            <i class="bi bi-file-earmark-arrow-down"></i>
        </button>`;
}
function renderActionButtonsforCheckListHeader(data, rowId) {
    if (data === 4) {
        return `
        <button class="btn btn-primary edit-btn btn-sm" data-id="${rowId}">
            <i class="bi bi-pencil-fill"></i>
        </button>
        <button class="btn btn-warning accept-btn btn-sm" data-id="${rowId}">
            <i class="bi bi-save2"></i>
        </button>
        <button class="btn btn-danger pdf-btn btn-sm" data-id="${rowId}">
            <i class="bi bi-file-earmark-pdf-fill"></i>
        </button>`;
    }
    if (data === 2) {
        return `
        <button class="btn btn-primary edit-btn btn-sm" data-id="${rowId}">
            <i class="bi bi-pencil-fill"></i>
        </button>
        <button class="btn btn-success unblock-btn btn-sm" data-id="${rowId}">
            <i class="bi bi-arrow-clockwise"></i>
        </button>
        <button class="btn btn-primary close-btn btn-sm" data-id="${rowId}">
            <i class="bi bi-x-lg"></i>
        </button>`;
    }
    if (data === 1) {
        return `
        <button class="btn btn-primary edit-btn btn-sm" data-id="${rowId}">
            <i class="bi bi-pencil-fill"></i>
        </button>
        <button class="btn btn-danger block-btn btn-sm" data-id="${rowId}">
            <i class="bi bi bi-sign-stop"></i>
        </button>`;
    }
    if (data === 5) {
        return `
        <button class="btn btn-danger pdf-btn btn-sm" data-id="${rowId}">
            <i class="bi bi-file-earmark-pdf-fill"></i>
        </button>`;
    }
    if (data === 3 || data === 6) {
        return ``;
    }
    return `
        <button class="btn btn-primary edit-btn btn-sm" data-id="${rowId}">
            <i class="bi bi-pencil-fill"></i>
        </button>
        <button class="btn btn-primary close-btn btn-sm" data-id="${rowId}">
            <i class="bi bi-x-lg"></i>
        </button>`;
        //<button class="btn btn-danger delete-btn btn-sm" data-id="${rowId}">
        //    <i class="bi bi-trash-fill"></i>
        //</button>`;

}
function renderActionButtonsforCheckListTemplateHeader(rowId) {
    return `
        <button class="btn btn-primary edit-btn btn-sm" data-id="${rowId}">
            <i class="bi bi-pencil-fill"></i>
        </button>
        <button class="btn btn-danger delete-btn btn-sm" data-id="${rowId}">
            <i class="bi bi-trash-fill"></i>
        </button>
        <button class="btn btn-primary clone-btn btn-sm" data-id="${rowId}">
            <i class="bi bi bi-copy"></i>
        </button>
    `;
}

function renderCheckStatus(data) {
    //Open = 0,
    //InProgress = 1,
    //Blocked = 2,
    //Storno = 3,
    //Sent = 4,
    //Signed = 5,
    //Closed = 6
    switch (data) {
        case 0:
            return 'Nyitott';
            break;
        case 1:
            return 'Folyamatban';
            break;
        case 2:
            return 'Blokkolt';
            break;
        case 3:
            return 'Stornózva';
            break;
        case 4:
            return 'Beküldve';
            break;
        case 5:
            return 'Jóváhagyva';
            break;
        case 6:
            return 'Lezárt';
            break;
        default:
            return '';
            break;
    }
}
function renderCheckBox(data) {
    if (data === true) {
        return '<input type="checkbox" class="form-check-input no-click" checked>';
    }
    if (data === false) {
        return '<input type="checkbox" class="form-check-input no-click">';
    }
    return data;
}
function renderAnswerType(data) {
    if (data === 'SI-N') {
        return '<div class="text-center"><div class="box yellow-box">I</div><div class="box">N</div></div>';
    }
    if (data === 'I-SN') {
        return '<div class="text-center"><div class="box">I</div><div class="box yellow-box">N</div></div>';
    }
    if (data === 'PI-N') {
        return '<div class="text-center"><div class="box red-box">I</div><div class="box">N</div></div>';
    }
    if (data === 'I-PN') {
        return '<div class="text-center"><div class="box">I</div><div class="box red-box">N</div></div>';
    }
    if (data === 'P') {
        return '<div class="text-center"><i class="fas fa-camera fa-2x"></i></div>';
    }
    if (data === 'PN') {
        return '<div class="text-center"><i class="fas fa-camera fa-2x icon-green"></i></div>';
    }
    if (data === 'V') {
        return '<div class="text-center"><span class="border border-dark rounded p-1">0,00</span></div>';
    }
    return data;
}
function renderAnswerPhoto(data, row) {
    if ((row.checkListTemplateRowDTO.answerType === 'P' || row.checkListTemplateRowDTO.answerType === 'PN')  && data.length > 0) {
        return `<div class="text-center"><img src="${data}" alt="Image" style="height: 100px; width: auto;" /></div>`;
    }
    if (row.checkListTemplateRowDTO.answerType === 'SI-N' && data === 'Igen') {
        return '<div class="text-center"><div class="box yellow-box">I</div></div>';
    }
    if (row.checkListTemplateRowDTO.answerType === 'SI-N' && data === 'Nem') {
        return '<div class="text-center"><div class="box">N</div></div>';
    }
    if (row.checkListTemplateRowDTO.answerType === 'I-SN' && data === 'Igen') {
        return '<div class="text-center"><div class="box">I</div></div>';
    }
    if (row.checkListTemplateRowDTO.answerType === 'I-SN' && data === 'Nem') {
        return '<div class="text-center"><div class="box yellow-box">N</div></div>';
    }
    if (row.checkListTemplateRowDTO.answerType === 'PI-N' && data === 'Igen') {
        return '<div class="text-center"><div class="box red-box">I</div></div>';
    }
    if (row.checkListTemplateRowDTO.answerType === 'PI-N' && data === 'Nem') {
        return '<div class="text-center"><div class="box">N</div></div>';
    }
    if (row.checkListTemplateRowDTO.answerType === 'I-PN' && data === 'Igen') {
        return '<div class="text-center"><div class="box">I</div></div>';
    }
    if (row.checkListTemplateRowDTO.answerType === 'I-PN' && data === 'Nem') {
        return '<div class="text-center"><div class="box red-box">N</div></div>';
    }
    return `<div class="text-center">${data}</div></div>`;
}

//Törlési funkció adatbázisnál
function deleteEntity(table, url, entityid) {
    showConfirmModal({
        title: 'Törlés megerősítése',
        message: 'Biztosan törölni szeretnéd ezt az elemet?',
        okText: 'Törlés',
        cancelText: 'Mégsem'
    }).then(function (result) {
        if (result === 'ok') {
            $.ajax({
                url: url,
                type: 'GET',
                data: { id: entityid },
                success: function (data) {
                    if (data) {
                        showMessageModal({
                            title: 'Információ',
                            message: 'A törlés sikerült!',
                            okText: 'Értettem'
                        });
                        table.ajax.reload();
                    } else {
                        showMessageModal({
                            title: 'Hiba!',
                            message: 'A törlés NEM sikerült!',
                            okText: 'Értettem'
                        });
                    }
                },
                error: function (xhr, status, error) {
                    showMessageModal({
                        title: 'Hiba!',
                        message: 'A törlés NEM sikerült!',
                        okText: 'Értettem'
                    });
                }
            });
        }
    });
}
function saveEntity(csrfToken, data, url) {
    $.ajax({
        url: url,
        type: 'POST',
        headers: {
            'X-CSRF-TOKEN': csrfToken,
            'Content-Type': 'application/json'
        },
        data: JSON.stringify(data),
        success: function (response) {
            if (response.success) {
                showMessageModal({
                    title: 'Figyelmem!',
                    message: 'Sikeres mentés.',
                    okText: 'Értettem'
                });
            }
            else {
                showMessageModal({
                    title: 'Figyelmem, HIBA!',
                    message: 'Sikertelen mentés.',
                    okText: 'Értettem'
                });
            }
        },
        error: function (xhr, status, error) {
            console.error("Hiba: ", error);
            showMessageModal({
                title: 'Hiba!',
                message: 'A mentés NEM sikerült!',
                okText: 'Értettem'
            });
        }
    });
}
function togglePasswordVisibility() {
    const passwordInput = document.getElementById("passwordInput");
    const icon = document.getElementById("toggleIcon");

    if (passwordInput.type === "password") {
        passwordInput.type = "text";
        icon.classList.remove("bi-eye");
        icon.classList.add("bi-eye-slash");
    } else {
        passwordInput.type = "password";
        icon.classList.remove("bi-eye-slash");
        icon.classList.add("bi-eye");
    }
}