(function(window, document, $){
    'use strict';

    if (typeof $ === 'undefined') {
        console.error('users-1.js: jQuery não encontrado.');
        return;
    }

    let macsDelete = [];
    let currentMessageMac = "";

    function getModalEl(id){
        return document.getElementById(id);
    }

    function getModalInstance(el){
        if (!el) return null;
        if (window.bootstrap && window.bootstrap.Modal) {
            return window.bootstrap.Modal.getOrCreateInstance(el);
        }
        return null;
    }

    function openModal(id){
        const el = getModalEl(id);
        if (!el) {
            console.error('Modal não encontrado:', id);
            return;
        }

        const instance = getModalInstance(el);
        if (instance) {
            instance.show();
            return;
        }

        // Fallback sem Bootstrap JS
        el.classList.add('show');
        el.style.display = 'block';
        el.removeAttribute('aria-hidden');
        el.setAttribute('aria-modal', 'true');
        document.body.classList.add('modal-open');

        let backdrop = document.querySelector('.modal-backdrop.js-fallback-backdrop');
        if (!backdrop) {
            backdrop = document.createElement('div');
            backdrop.className = 'modal-backdrop fade show js-fallback-backdrop';
            document.body.appendChild(backdrop);
        }
    }

    function closeModal(id){
        const el = getModalEl(id);
        if (!el) return;

        const instance = getModalInstance(el);
        if (instance) {
            instance.hide();
            return;
        }

        el.classList.remove('show');
        el.style.display = 'none';
        el.setAttribute('aria-hidden', 'true');
        el.removeAttribute('aria-modal');
        document.body.classList.remove('modal-open');

        document.querySelectorAll('.modal-backdrop.js-fallback-backdrop').forEach(function(node){
            node.remove();
        });
    }

    function showSuccessAndReload(){
        openModal('successModal');
        setTimeout(function(){
            window.location.reload();
        }, 1200);
    }

    function showRequestError(xhr, fallbackMessage){
        let msg = fallbackMessage || "Ocorreu um erro ao processar a ação.";
        try {
            const resp = xhr && xhr.responseJSON ? xhr.responseJSON : JSON.parse((xhr && xhr.responseText) || '{}');
            if (resp && resp.message) {
                msg = resp.message;
            }
        } catch (e) {}
        alert(msg);
    }

    function syncSwitchValue(switchId, hiddenId) {
        const checked = $(switchId).is(':checked');
        $(hiddenId).val(checked ? '1' : '0');
    }

    function rowData($tr, key){
        const attrName = 'data-' + key;
        const attrValue = $tr.attr(attrName);
        return typeof attrValue !== 'undefined' ? attrValue : '';
    }

    function safeVal(selector, value){
        const $el = $(selector);
        if ($el.length) {
            $el.val(value);
        }
    }

    function safeFormValue(form, name, value){
        if (form && form.elements && form.elements[name]) {
            form.elements[name].value = value;
        }
    }

    $(document).on('click', '[data-bs-dismiss="modal"]', function(){
        const modal = this.closest('.modal');
        if (modal && modal.id) {
            closeModal(modal.id);
        }
    });

    $(document).on('click', '.modal', function(e){
        if (e.target === this && this.id) {
            closeModal(this.id);
        }
    });

    $(document).on('change', '#checkAll', function(){
        $(".chk").prop("checked", $("#checkAll").prop("checked"));
    });

    $(document).on('click', '.btn-delete', function(e){
        e.preventDefault();
        macsDelete = [$(this).data("mac")];
        openModal('confirmDeleteModal');
    });

    $(document).on('click', '#btnDeleteSelected', function(e){
        e.preventDefault();
        macsDelete = $(".chk:checked").map(function(){ return this.value; }).get();
        if (macsDelete.length) {
            openModal('confirmDeleteModal');
            return;
        }
        alert('Selecione pelo menos um usuário para apagar.');
    });

    $(document).on('click', '#confirmDelete', function(e){
        e.preventDefault();
        $.ajax({
            url: 'users.php',
            type: 'POST',
            dataType: 'json',
            data: {delete: macsDelete},
            success: function(resp){
                if (resp && resp.status === "success") {
                    closeModal('confirmDeleteModal');
                    showSuccessAndReload();
                    return;
                }
                alert(resp && resp.message ? resp.message : 'Não foi possível apagar o usuário.');
            },
            error: function(xhr){
                showRequestError(xhr, 'Falha ao apagar o usuário.');
            }
        });
    });

    $(document).on('click', '.btn-edit', function(e){
        e.preventDefault();
        const tr = $(this).closest("tr");
        const f = document.getElementById("editForm");

        if (!f) {
            alert('Formulário de edição não encontrado.');
            return;
        }

        safeFormValue(f, 'mac', rowData(tr, 'mac'));
        safeFormValue(f, 'username', rowData(tr, 'username'));
        safeFormValue(f, 'password', rowData(tr, 'password'));
        safeFormValue(f, 'dns', rowData(tr, 'dns'));
        safeFormValue(f, 'status', rowData(tr, 'status'));
        safeFormValue(f, 'vencimento', rowData(tr, 'venc'));
        safeFormValue(f, 'nome_cliente', rowData(tr, 'nome'));
        safeFormValue(f, 'whatsapp', rowData(tr, 'whatsapp'));
        safeFormValue(f, 'tipo_registro', rowData(tr, 'tipo-registro') || 'cliente');
        safeFormValue(f, 'login_mode', rowData(tr, 'login-mode') || 'normal');
        safeFormValue(f, 'activation_code', rowData(tr, 'activation-code') || '');

        safeVal("#macReadonly", rowData(tr, 'mac'));

        openModal('editModal');
    });

    $(document).on('submit', '#editForm', function(e){
        e.preventDefault();
        $.ajax({
            url: 'users.php',
            type: 'POST',
            dataType: 'json',
            data: $(this).serialize(),
            success: function(resp){
                if (resp && resp.status === "success") {
                    closeModal('editModal');
                    showSuccessAndReload();
                    return;
                }
                alert(resp && resp.message ? resp.message : 'Não foi possível salvar as alterações.');
            },
            error: function(xhr){
                showRequestError(xhr, 'Falha ao salvar as alterações.');
            }
        });
    });

    $(document).on('click', '.btn-renew', function(e){
        e.preventDefault();
        $.ajax({
            url: 'users.php',
            type: 'POST',
            dataType: 'json',
            data: {renew: $(this).data("mac")},
            success: function(resp){
                if (resp && resp.status === "success") {
                    showSuccessAndReload();
                } else if (resp && resp.message) {
                    alert(resp.message);
                }
            },
            error: function(xhr){
                showRequestError(xhr, 'Falha ao renovar o usuário.');
            }
        });
    });

    $(document).on('click', '.btn-send-due', function(e){
        e.preventDefault();
        $.ajax({
            url: 'users.php',
            type: 'POST',
            dataType: 'json',
            data: {send_manual_due: $(this).data("mac")},
            success: function(resp){
                if (resp && resp.status === "success") {
                    showSuccessAndReload();
                } else if (resp && resp.message) {
                    alert(resp.message);
                }
            },
            error: function(xhr){
                showRequestError(xhr, 'Falha ao enviar cobrança manual.');
            }
        });
    });

    $(document).on('click', '.btn-generate-pix', function(e){
        e.preventDefault();
        safeVal("#pixMacField", $(this).data("mac") || "");
        safeVal("#pixClientName", $(this).data("nome") || "");
        safeVal("#pixClientWhatsapp", $(this).data("whatsapp") || "");
        safeVal("#pixPlanField", "");
        openModal('pixModal');
    });

    $(document).on('submit', '#pixForm', function(e){
        e.preventDefault();
        $.ajax({
            url: 'users.php',
            type: 'POST',
            dataType: 'json',
            data: $(this).serialize(),
            success: function(resp){
                if (resp && resp.status === "success") {
                    closeModal('pixModal');
                    const valor = resp.pix && typeof resp.pix.valor_gerado !== "undefined"
                        ? Number(resp.pix.valor_gerado).toLocaleString("pt-BR", {minimumFractionDigits:2, maximumFractionDigits:2})
                        : "";
                    const paymentId = resp.pix && resp.pix.payment_id ? "\nID: " + resp.pix.payment_id : "";
                    alert("PIX gerado com sucesso. Valor: R$ " + valor + paymentId);
                    showSuccessAndReload();
                    return;
                }
                alert(resp && resp.message ? resp.message : 'Não foi possível gerar o PIX.');
            },
            error: function(xhr){
                showRequestError(xhr, 'Falha ao gerar o PIX.');
            }
        });
    });

    $(document).on('click', '.btn-message', function(e){
        e.preventDefault();
        const tr = $(this).closest("tr");
        currentMessageMac = String(rowData(tr, 'mac') || "");
        safeVal("#messageMac", currentMessageMac);
        safeVal("#messageMacReadonly", currentMessageMac);
        safeVal("#messageTitle", String(rowData(tr, 'message-title') || "Mensagem do servidor"));
        safeVal("#messageText", String(rowData(tr, 'message-text') || ""));
        safeVal("#messageTempo", String(rowData(tr, 'message-tempo') || "5"));
        safeVal("#messageActive", String(rowData(tr, 'message-active') || "1"));
        safeVal("#messageShownOnce", String(rowData(tr, 'message-shown-once') || "1"));
        openModal('messageModal');
    });

    $(document).on('submit', '#messageForm', function(e){
        e.preventDefault();
        $.ajax({
            url: 'users.php',
            type: 'POST',
            dataType: 'json',
            data: $(this).serialize(),
            success: function(resp){
                if (resp && resp.status === "success") {
                    closeModal('messageModal');
                    showSuccessAndReload();
                    return;
                }
                alert(resp && resp.message ? resp.message : 'Não foi possível salvar a mensagem.');
            },
            error: function(xhr){
                showRequestError(xhr, 'Falha ao salvar a mensagem.');
            }
        });
    });

    $(document).on('click', '#btnClearMessage', function(e){
        e.preventDefault();
        const mac = $("#messageMac").val();
        if (!mac) return;
        $.ajax({
            url: 'users.php',
            type: 'POST',
            dataType: 'json',
            data: {clear_message: 1, mac: mac},
            success: function(resp){
                if (resp && resp.status === "success") {
                    closeModal('messageModal');
                    showSuccessAndReload();
                    return;
                }
                alert(resp && resp.message ? resp.message : 'Não foi possível limpar a mensagem.');
            },
            error: function(xhr){
                showRequestError(xhr, 'Falha ao limpar a mensagem.');
            }
        });
    });

    $(document).on('click', '.btn-access', function(e){
        e.preventDefault();
        const tr = $(this).closest("tr");
        const mac = String(rowData(tr, 'mac') || "");
        safeVal("#accessMac", mac);
        safeVal("#accessMacReadonly", mac);

        const allowLive = String(rowData(tr, 'allow-live') || "1") === "1";
        const allowMovies = String(rowData(tr, 'allow-movies') || "1") === "1";
        const allowSeries = String(rowData(tr, 'allow-series') || "1") === "1";

        $("#allowAllLiveSwitch").prop("checked", allowLive);
        $("#allowAllMoviesSwitch").prop("checked", allowMovies);
        $("#allowAllSeriesSwitch").prop("checked", allowSeries);

        syncSwitchValue('#allowAllLiveSwitch', '#allowAllLive');
        syncSwitchValue('#allowAllMoviesSwitch', '#allowAllMovies');
        syncSwitchValue('#allowAllSeriesSwitch', '#allowAllSeries');

        safeVal("#blockedLiveIds", String(rowData(tr, 'blocked-live-ids') || ""));
        safeVal("#blockedMovieIds", String(rowData(tr, 'blocked-movie-ids') || ""));
        safeVal("#blockedSeriesIds", String(rowData(tr, 'blocked-series-ids') || ""));
        safeVal("#blockedLiveCategories", String(rowData(tr, 'blocked-live-categories') || ""));
        safeVal("#blockedMovieCategories", String(rowData(tr, 'blocked-movie-categories') || ""));
        safeVal("#blockedSeriesCategories", String(rowData(tr, 'blocked-series-categories') || ""));

        openModal('accessModal');
    });

    $(document).on('change', '#allowAllLiveSwitch, #allowAllMoviesSwitch, #allowAllSeriesSwitch', function(){
        syncSwitchValue('#allowAllLiveSwitch', '#allowAllLive');
        syncSwitchValue('#allowAllMoviesSwitch', '#allowAllMovies');
        syncSwitchValue('#allowAllSeriesSwitch', '#allowAllSeries');
    });

    $(document).on('submit', '#accessForm', function(e){
        e.preventDefault();
        $.ajax({
            url: 'users.php',
            type: 'POST',
            dataType: 'json',
            data: $(this).serialize(),
            success: function(resp){
                if (resp && resp.status === "success") {
                    closeModal('accessModal');
                    showSuccessAndReload();
                    return;
                }
                alert(resp && resp.message ? resp.message : 'Não foi possível salvar os bloqueios.');
            },
            error: function(xhr){
                showRequestError(xhr, 'Falha ao salvar os bloqueios.');
            }
        });
    });

    $(document).on('click', '#btnImportBackupJson', function(e) {
        e.preventDefault();
        safeVal("#backupJsonInput", "");
        $("#backupJsonInput").trigger("click");
    });

    $(document).on('change', '#backupJsonInput', function () {
        const file = this.files && this.files[0] ? this.files[0] : null;
        if (!file) return;

        const formData = new FormData();
        formData.append("import_backup_json", "1");
        formData.append("backup_file", file);

        $.ajax({
            url: "users.php",
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function (resp) {
                if (resp && resp.status === "success") {
                    alert(
                        "Backup importado com sucesso!\n\n" +
                        "Novos: " + (resp.importados || 0) + "\n" +
                        "Atualizados: " + (resp.atualizados || 0) + "\n" +
                        "Ignorados: " + (resp.ignorados || 0)
                    );
                    window.location.reload();
                    return;
                }

                alert(resp && resp.message ? resp.message : "Falha ao importar backup.");
            },
            error: function (xhr) {
                showRequestError(xhr, 'Falha ao enviar o arquivo JSON.');
            }
        });
    });

    function filterRows(){
        const tipo = ($("#filterTipo").val() || "").toLowerCase().trim();
        const search = ($("#searchTable").val() || "").toLowerCase().trim();

        $("#usersTable tbody tr").each(function(){
            const tr = $(this);
            if (tr.find("td").length === 1) {
                return;
            }
            const rowTipo = String(tr.data("tipo") || "").toLowerCase();
            const rowSearch = String(tr.data("search") || "").toLowerCase();
            let show = true;

            if (tipo && rowTipo !== tipo) {
                show = false;
            }
            if (search && rowSearch.indexOf(search) === -1) {
                show = false;
            }
            tr.toggle(show);
        });
    }

    $(document).on('change', '#filterTipo', filterRows);
    $(document).on('input', '#searchTable', filterRows);

})(window, document, window.jQuery);
