/* Comportamentos exclusivos da página users.php */

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

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

    var macsDelete = [];

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

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

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

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

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

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

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

        var 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();
        }, 900);
    }

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

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

    function safeVal(selector, value) {
        var $el = $(selector);
        if ($el.length) $el.val(value == null ? '' : value);
    }

    function safeText(selector, value) {
        var $el = $(selector);
        if ($el.length) $el.text(value == null ? '' : value);
    }

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

    function setSwitch(selector, checked) {
        var $el = $(selector);
        if ($el.length) $el.prop('checked', !!checked);
    }

    function syncAccessHidden() {
        var movies = $('#allowTabMoviesSwitch').is(':checked');
        var series = $('#allowTabSeriesSwitch').is(':checked');
        var kids = $('#allowTabKidsSwitch').is(':checked');
        var anime = $('#allowTabAnimeSwitch').is(':checked');
        var novelas = $('#allowTabNovelasSwitch').is(':checked');
        var esportes = $('#allowTabEsportesSwitch').is(':checked');

        safeVal('#allowTabMovies', movies ? '1' : '0');
        safeVal('#allowTabSeries', series ? '1' : '0');
        safeVal('#allowTabKids', kids ? '1' : '0');
        safeVal('#allowTabAnime', anime ? '1' : '0');
        safeVal('#allowTabNovelas', novelas ? '1' : '0');
        safeVal('#allowTabEsportes', esportes ? '1' : '0');

        safeVal('#allowContentMovies', movies ? '1' : '0');
        safeVal('#allowContentSeries', (series || novelas) ? '1' : '0');
        safeVal('#allowContentLive', '1');

        safeVal('#allowAllMovies', movies ? '1' : '0');
        safeVal('#allowAllSeries', (series || novelas) ? '1' : '0');
        safeVal('#allowAllLive', '1');

        safeVal('#allowTv', '1');
        safeVal('#allowMobile', '1');

        safeText('#moviesStatusText', movies ? 'Liberado' : '🔒 Bloqueado');
        safeText('#seriesStatusText', series ? 'Liberado' : '🔒 Bloqueado');
        safeText('#kidsStatusText', kids ? 'Liberado' : '🔒 Bloqueado');
        safeText('#animeStatusText', anime ? 'Liberado' : '🔒 Bloqueado');
        safeText('#novelasStatusText', novelas ? 'Liberado' : '🔒 Bloqueado');
        safeText('#esportesStatusText', esportes ? 'Liberado' : '🔒 Bloqueado');

        $('#moviesStatusText').css('color', movies ? '#22c55e' : '#ef4444');
        $('#seriesStatusText').css('color', series ? '#22c55e' : '#ef4444');
        $('#kidsStatusText').css('color', kids ? '#22c55e' : '#ef4444');
        $('#animeStatusText').css('color', anime ? '#22c55e' : '#ef4444');
        $('#novelasStatusText').css('color', novelas ? '#22c55e' : '#ef4444');
        $('#esportesStatusText').css('color', esportes ? '#22c55e' : '#ef4444');
    }

    function filterRows() {
        var tipo = String($('#filterTipo').val() || '').toLowerCase().trim();
        var search = String($('#searchTable').val() || '').toLowerCase().trim();

        $('#usersTable tbody tr').each(function() {
            var $tr = $(this);
            if ($tr.find('td').length === 1) return;

            var rowTipo = String($tr.data('tipo') || '').toLowerCase();
            var rowSearch = String($tr.data('search') || '').toLowerCase();
            var show = true;

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

            $tr.toggle(show);
        });
    }

    $(document).on('click', '[data-bs-dismiss="modal"], .btn-close', function(e) {
        var 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', $(this).prop('checked'));
    });

    $(document).on('click', '.btn-delete', function(e) {
        e.preventDefault();
        var mac = $(this).data('mac') || $(this).closest('tr').attr('data-mac') || '';
        macsDelete = mac ? [String(mac)] : [];
        if (!macsDelete.length) {
            alert('MAC não encontrado para apagar.');
            return;
        }
        openModal('confirmDeleteModal');
    });

    $(document).on('click', '#btnDeleteSelected', function(e) {
        e.preventDefault();
        macsDelete = $('.chk:checked').map(function() {
            return this.value;
        }).get();

        if (!macsDelete.length) {
            alert('Selecione pelo menos um usuário para apagar.');
            return;
        }

        openModal('confirmDeleteModal');
    });

    $(document).on('click', '#confirmDelete', function(e) {
        e.preventDefault();

        if (!macsDelete.length) {
            alert('Nenhum usuário selecionado.');
            return;
        }

        $.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.');
            }
        });
    });


    var multiServersState = [];

    function newServerKey() {
        return 'srv_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 10);
    }

    function normalizeServerState(raw) {
        var out = [];
        if (!Array.isArray(raw)) return out;
        raw.slice(0, 12).forEach(function(item, index) {
            item = item || {};
            var dns = String(item.dns || '').trim();
            var username = String(item.username || '').trim();
            var password = String(item.password || '');
            if (!dns && !username && !password && !item.name) return;
            out.push({
                key: String(item.key || newServerKey()),
                name: String(item.name || ('Servidor ' + (index + 1))),
                dns: dns,
                username: username,
                password: password
            });
        });
        return out;
    }

    function escapeServerHtml(value) {
        return $('<div>').text(String(value == null ? '' : value)).html();
    }

    function syncMultiServerForm() {
        var list = [];
        $('#serverEditorList .server-editor-card').each(function(index) {
            var $card = $(this);
            list.push({
                key: String($card.attr('data-key') || newServerKey()),
                name: String($card.find('.server-name').val() || ('Servidor ' + (index + 1))).trim(),
                dns: String($card.find('.server-dns').val() || '').trim(),
                username: String($card.find('.server-user').val() || '').trim(),
                password: String($card.find('.server-pass').val() || '')
            });
        });
        multiServersState = list;
        $('#serversJsonInput').val(JSON.stringify(list));
        var primary = list.length ? list[0] : {dns:'',username:'',password:''};
        safeFormValue(document.getElementById('editForm'), 'dns', primary.dns || '');
        safeFormValue(document.getElementById('editForm'), 'username', primary.username || '');
        safeFormValue(document.getElementById('editForm'), 'password', primary.password || '');
        return list;
    }

    function renderMultiServers() {
        var $list = $('#serverEditorList');
        if (!$list.length) return;
        $list.empty();
        if (!multiServersState.length) {
            $list.html('<div class="server-editor-empty"><i class="bi bi-hdd-network"></i><br>Nenhum servidor cadastrado. Clique em <strong>Adicionar servidor</strong>.</div>');
            syncMultiServerForm();
            return;
        }
        multiServersState.forEach(function(server, index) {
            var primary = index === 0;
            var card = ''+
                '<div class="server-editor-card '+(primary?'primary':'')+'" data-key="'+escapeServerHtml(server.key || newServerKey())+'">'+
                  '<div class="server-editor-card-head">'+
                    '<div class="server-editor-index"><i class="bi bi-server"></i> Servidor '+(index+1)+(primary?' <span class="primary-pill">Padrão</span>':'')+'</div>'+
                    '<div class="server-editor-actions">'+
                      '<button type="button" class="move-server-up" title="Mover para cima" '+(index===0?'disabled':'')+'><i class="bi bi-arrow-up"></i></button>'+
                      '<button type="button" class="move-server-down" title="Mover para baixo" '+(index===multiServersState.length-1?'disabled':'')+'><i class="bi bi-arrow-down"></i></button>'+
                      '<button type="button" class="remove-server" title="Remover"><i class="bi bi-trash"></i></button>'+
                    '</div>'+
                  '</div>'+
                  '<div class="server-fields">'+
                    '<div><label>Nome</label><input class="form-control server-name" maxlength="60" value="'+escapeServerHtml(server.name || ('Servidor '+(index+1)))+'" placeholder="Ex.: Principal"></div>'+
                    '<div><label>DNS</label><input class="form-control server-dns" value="'+escapeServerHtml(server.dns || '')+'" placeholder="https://servidor.com:porta"></div>'+
                    '<div><label>Usuário</label><input class="form-control server-user" value="'+escapeServerHtml(server.username || '')+'" placeholder="Usuário"></div>'+
                    '<div><label>Senha</label><input class="form-control server-pass" value="'+escapeServerHtml(server.password || '')+'" placeholder="Senha"></div>'+
                  '</div>'+
                '</div>';
            $list.append(card);
        });
        syncMultiServerForm();
    }

    $(document).on('input change', '#serverEditorList input', syncMultiServerForm);
    $(document).on('click', '#btnAddServer', function() {
        syncMultiServerForm();
        if (multiServersState.length >= 12) { alert('Limite de 12 servidores por usuário.'); return; }
        multiServersState.push({key:newServerKey(), name:'Servidor '+(multiServersState.length+1), dns:'', username:'', password:''});
        renderMultiServers();
        $('#serverEditorList .server-editor-card:last .server-name').trigger('focus');
    });
    $(document).on('click', '.remove-server', function() {
        syncMultiServerForm();
        var index = $(this).closest('.server-editor-card').index();
        if (index >= 0) multiServersState.splice(index, 1);
        renderMultiServers();
    });
    $(document).on('click', '.move-server-up', function() {
        syncMultiServerForm();
        var index = $(this).closest('.server-editor-card').index();
        if (index > 0) { var tmp=multiServersState[index-1]; multiServersState[index-1]=multiServersState[index]; multiServersState[index]=tmp; }
        renderMultiServers();
    });
    $(document).on('click', '.move-server-down', function() {
        syncMultiServerForm();
        var index = $(this).closest('.server-editor-card').index();
        if (index >= 0 && index < multiServersState.length-1) { var tmp=multiServersState[index+1]; multiServersState[index+1]=multiServersState[index]; multiServersState[index]=tmp; }
        renderMultiServers();
    });

    $(document).on('click', '.btn-edit', function(e) {
        e.preventDefault();

        var $tr = $(this).closest('tr');
        var form = document.getElementById('editForm');

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

        safeFormValue(form, 'mac', rowData($tr, 'mac'));
        safeFormValue(form, 'username', rowData($tr, 'username'));
        safeFormValue(form, 'password', rowData($tr, 'password'));
        safeFormValue(form, 'dns', rowData($tr, 'dns'));
        safeFormValue(form, 'status', rowData($tr, 'status') || 'ativo');
        safeFormValue(form, 'vencimento', rowData($tr, 'venc'));
        safeFormValue(form, 'nome_cliente', rowData($tr, 'nome'));
        safeFormValue(form, 'whatsapp', rowData($tr, 'whatsapp'));
        safeFormValue(form, 'tipo_registro', rowData($tr, 'tipo-registro') || 'cliente');
        safeFormValue(form, 'login_mode', rowData($tr, 'login-mode') || 'normal');
        safeFormValue(form, 'activation_code', rowData($tr, 'activation-code') || '');
        var profileUrl = String(rowData($tr, 'profile-url') || '');
        $('#editProfilePreview').attr('src', profileUrl || 'assets/images/profile-placeholder.svg');
        $('#editProfileImage').val('');
        $('#deleteProfileImage').prop('checked', false);

        var rawServers = rowData($tr, 'servers') || '[]';
        try { multiServersState = normalizeServerState(typeof rawServers === 'string' ? JSON.parse(rawServers) : rawServers); }
        catch (err) { multiServersState = []; }
        if (!multiServersState.length && (rowData($tr,'dns') || rowData($tr,'username') || rowData($tr,'password'))) {
            multiServersState = normalizeServerState([{name:'Servidor principal',dns:rowData($tr,'dns'),username:rowData($tr,'username'),password:rowData($tr,'password')}]);
        }
        renderMultiServers();

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

        openModal('editModal');
    });

    $(document).on('change', '#editProfileImage', function() {
        var file = this.files && this.files[0];
        if (!file) return;
        var reader = new FileReader();
        reader.onload = function(ev){ $('#editProfilePreview').attr('src', ev.target.result); };
        reader.readAsDataURL(file);
        $('#deleteProfileImage').prop('checked', false);
    });

    $(document).on('submit', '#editForm', function(e) {
        e.preventDefault();
        var servers = syncMultiServerForm();
        var invalid = servers.some(function(s){ return !s.dns || !s.username || !s.password; });
        if (invalid) { alert('Preencha DNS, usuário e senha em todos os servidores.'); return; }

        var formData = new FormData(this);
        $.ajax({
            url: 'users.php',
            type: 'POST',
            dataType: 'json',
            data: formData,
            processData: false,
            contentType: false,
            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-access', function(e) {
        e.preventDefault();

        var $tr = $(this).closest('tr');
        var mac = String(rowData($tr, 'mac') || '');

        safeVal('#accessMac', mac);
        safeText('#accessMacLabel', 'MAC: ' + mac);

        var allowMovies = String(rowData($tr, 'allow-tab-movies') || rowData($tr, 'allow-movies') || '1') === '1';
        var allowSeries = String(rowData($tr, 'allow-tab-series') || rowData($tr, 'allow-series') || '1') === '1';
        var allowKids = String(rowData($tr, 'allow-tab-kids') || '1') === '1';
        var allowAnime = String(rowData($tr, 'allow-tab-anime') || '1') === '1';
        var allowNovelas = String(rowData($tr, 'allow-tab-novelas') || rowData($tr, 'allow-tab-series') || '1') === '1';
        var allowEsportes = String(rowData($tr, 'allow-tab-esportes') || '1') === '1';

        setSwitch('#allowTabMoviesSwitch', allowMovies);
        setSwitch('#allowTabSeriesSwitch', allowSeries);
        setSwitch('#allowTabKidsSwitch', allowKids);
        setSwitch('#allowTabAnimeSwitch', allowAnime);
        setSwitch('#allowTabNovelasSwitch', allowNovelas);
        setSwitch('#allowTabEsportesSwitch', allowEsportes);

        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') || ''));

        syncAccessHidden();
        openModal('accessModal');
    });

    $(document).on('change', '#allowTabMoviesSwitch, #allowTabSeriesSwitch, #allowTabKidsSwitch, #allowTabAnimeSwitch, #allowTabNovelasSwitch, #allowTabEsportesSwitch', function() {
        syncAccessHidden();
    });

    $(document).on('submit', '#accessForm', function(e) {
        e.preventDefault();
        syncAccessHidden();

        var formData = new FormData(this);
        $.ajax({
            url: 'users.php',
            type: 'POST',
            dataType: 'json',
            data: formData,
            processData: false,
            contentType: false,
            success: function(resp) {
                if (resp && resp.status === 'success') {
                    closeModal('accessModal');
                    showSuccessAndReload();
                    return;
                }
                alert(resp && resp.message ? resp.message : 'Não foi possível salvar o controle de acesso.');
            },
            error: function(xhr) {
                showRequestError(xhr, 'Falha ao salvar o controle de acesso.');
            }
        });
    });


    $(document).on('click', '.btn-activate-user', function(e) {
        e.preventDefault();
        var $tr = $(this).closest('tr');
        var mac = $(this).data('mac') || rowData($tr, 'mac') || '';
        safeVal('#activateUserMac', mac);
        var now = new Date();
        now.setDate(now.getDate() + 30);
        var pad = function(n){ return String(n).padStart(2, '0'); };
        var dt = now.getFullYear() + '-' + pad(now.getMonth()+1) + '-' + pad(now.getDate()) + 'T' + pad(now.getHours()) + ':' + pad(now.getMinutes());
        safeVal('#activateUserVencimento', dt);
        safeVal('#activateUserM3u', '');
        openModal('activateUserModal');
    });

    $(document).on('submit', '#activateUserForm', function(e) {
        e.preventDefault();
        var formData = new FormData(this);
        $.ajax({
            url: 'users.php',
            type: 'POST',
            dataType: 'json',
            data: formData,
            processData: false,
            contentType: false,
            success: function(resp) {
                if (resp && resp.status === 'success') {
                    closeModal('activateUserModal');
                    showSuccessAndReload();
                    return;
                }
                alert(resp && resp.message ? resp.message : 'Não foi possível ativar o cliente.');
            },
            error: function(xhr) {
                showRequestError(xhr, 'Falha ao ativar o cliente.');
            }
        });
    });

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

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

        var 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.');
            }
        });
    });

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

    $(function() {
        syncAccessHidden();
        filterRows();
    });

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

document.addEventListener('DOMContentLoaded', function(){
    var pairingModalEl = document.getElementById('claimPairingModal');
    var pairingButton = document.getElementById('btnClaimPairingCode');

    function pairingManualShow(){
        if (!pairingModalEl) return;
        pairingModalEl.style.display = 'block';
        pairingModalEl.classList.add('show');
        pairingModalEl.removeAttribute('aria-hidden');
        pairingModalEl.setAttribute('aria-modal', 'true');
        pairingModalEl.setAttribute('role', 'dialog');
        document.body.classList.add('modal-open');
        document.body.style.overflow = 'hidden';
        var old = document.querySelector('.pairing-modal-backdrop');
        if (old) old.remove();
        var backdrop = document.createElement('div');
        backdrop.className = 'modal-backdrop fade show pairing-modal-backdrop';
        document.body.appendChild(backdrop);
    }

    function pairingShow(){
        if (!pairingModalEl) return;
        if (window.bootstrap && window.bootstrap.Modal) {
            window.bootstrap.Modal.getOrCreateInstance(pairingModalEl).show();
        } else {
            pairingManualShow();
        }
        setTimeout(function(){ var input = document.getElementById('pairingCodeInput'); if (input) input.focus(); }, 120);
    }

    function pairingHide(){
        if (!pairingModalEl) return;
        if (window.bootstrap && window.bootstrap.Modal) {
            window.bootstrap.Modal.getOrCreateInstance(pairingModalEl).hide();
            return;
        }
        pairingModalEl.classList.remove('show');
        pairingModalEl.style.display = 'none';
        pairingModalEl.setAttribute('aria-hidden', 'true');
        pairingModalEl.removeAttribute('aria-modal');
        pairingModalEl.removeAttribute('role');
        document.body.classList.remove('modal-open');
        document.body.style.overflow = '';
        document.querySelectorAll('.pairing-modal-backdrop').forEach(function(el){ el.remove(); });
    }

    if (pairingButton) {
        pairingButton.addEventListener('click', function(e){
            e.preventDefault();
            e.stopPropagation();
            pairingShow();
        });
    }
    document.addEventListener('click', function(e){
        if (!pairingModalEl) return;
        if (e.target.closest('#claimPairingModal [data-bs-dismiss="modal"]') || e.target.classList.contains('pairing-modal-backdrop')) {
            e.preventDefault();
            pairingHide();
        }
    });
    document.addEventListener('keydown', function(e){ if (e.key === 'Escape') pairingHide(); });

    var pairingInput = document.getElementById('pairingCodeInput');
    if (pairingInput) {
        pairingInput.addEventListener('input', function(){ this.value = this.value.replace(/\D/g, '').slice(0, 4); });
        var pairingModal = document.getElementById('claimPairingModal');
        if (pairingModal) pairingModal.addEventListener('shown.bs.modal', function(){ pairingInput.focus(); });
    }

    var runtime = document.getElementById('usersRuntime');
    var autoMac = runtime ? String(runtime.dataset.autoMac || '') : '';
    if (autoMac) {
        var macInput = document.getElementById('activateUserMac');
        var vencInput = document.getElementById('activateUserVencimento');
        if (macInput) macInput.value = autoMac;
        if (vencInput && !vencInput.value) {
            var d = new Date(); d.setDate(d.getDate() + 30);
            var pad = function(n){ return String(n).padStart(2, '0'); };
            vencInput.value = d.getFullYear() + '-' + pad(d.getMonth()+1) + '-' + pad(d.getDate()) + 'T' + pad(d.getHours()) + ':' + pad(d.getMinutes());
        }
        var modalEl = document.getElementById('activateUserModal');
        if (modalEl && window.bootstrap && window.bootstrap.Modal) {
            window.bootstrap.Modal.getOrCreateInstance(modalEl).show();
            setTimeout(function(){ var m3u = document.getElementById('activateUserM3u'); if (m3u) m3u.focus(); }, 180);
        }
    }
});
