// Admin Dashboard - Conectado ao Backend PHP
class AdminDashboard {
    constructor() {
        this.charts = {};
        this.pixCurrentPage = 1;
        this.pixPerPage = 15;
        this.pixTotalItems = 0;
        this.sessionsCurrentPage = 1;
        this.sessionsPerPage = 15;
        this.init();
    }

    async init() {
        console.log('Iniciando Admin Dashboard com PHP Backend...');
        this.setupCharts();
        await this.setupPixTransactions();
        await this.setupValoresMeses();
        await this.setupPixConfig();
        this.setupClearDataButton();
        await this.loadData();
        await this.loadSessions();
        this.setupSessionsControls();
        this.startAutoRefresh();
        this.updateLastUpdateTime();
    }

    // --- Gerenciamento de Transações PIX ---
    async setupPixTransactions() {
        await this.loadPixStats();
        await this.loadPixTransactions();
        this.setupPixFilters();
    }

    async loadPixStats() {
        try {
            const response = await fetch('../pix-api.php?action=stats', { cache: 'no-store' });
            const result = await response.json();
            
            if (result.status === 'success' && result.data) {
                const stats = result.data;
                
                // Conta waiting_payment junto com pending
                const pendingCount = (stats.pending || 0) + (stats.waiting_payment || 0);
                
                document.getElementById('pix-total').textContent = stats.total || 0;
                document.getElementById('pix-pending').textContent = pendingCount;
                document.getElementById('pix-paid').textContent = stats.paid || 0;
                document.getElementById('pix-paid-amount').textContent = this.formatCurrency(stats.paid_amount || 0);
            }
        } catch (error) {
            console.error('Erro ao carregar stats PIX:', error);
        }
    }

    async loadPixTransactions(statusFilter = '', page = 1, modeFilter = '') {
        const tbody = document.getElementById('pix-transactions-body');
        if (!tbody) return;

        tbody.innerHTML = `<tr><td colspan="8" class="text-center"><div class="loading"></div> Carregando...</td></tr>`;

        try {
            const offset = (page - 1) * this.pixPerPage;
            // Usar list-local para pegar do banco local com campos padronizados
            let url = `../pix-api.php?action=list-local&limit=${this.pixPerPage}&offset=${offset}`;
            if (statusFilter) {
                url += `&status=${encodeURIComponent(statusFilter)}`;
            }
            if (modeFilter) {
                url += `&pix_mode=${encodeURIComponent(modeFilter)}`;
            }

            const response = await fetch(url, { cache: 'no-store' });
            const result = await response.json();

            if (result.status === 'success' && Array.isArray(result.data)) {
                if (result.data.length === 0 && page === 1) {
                    tbody.innerHTML = `<tr><td colspan="8" class="text-center text-muted">Nenhuma transação encontrada.</td></tr>`;
                    this.updatePaginationControls(0, page);
                    return;
                }

                tbody.innerHTML = result.data.map(tx => this.renderTransactionRow(tx)).join('');
                
                // Atualizar controles de paginação
                // Se retornou menos que o limite, provavelmente é a última página
                const hasMore = result.data.length === this.pixPerPage;
                this.updatePaginationControls(result.data.length, page, hasMore);
            } else {
                tbody.innerHTML = `<tr><td colspan="8" class="text-center text-danger">Erro ao carregar transações.</td></tr>`;
            }
        } catch (error) {
            console.error('Erro ao carregar transações PIX:', error);
            tbody.innerHTML = `<tr><td colspan="8" class="text-center text-danger">Erro de conexão.</td></tr>`;
        }
    }

    updatePaginationControls(itemsOnPage, currentPage, hasMore = false) {
        this.pixCurrentPage = currentPage;
        
        const prevBtn = document.getElementById('pix-prev-page');
        const nextBtn = document.getElementById('pix-next-page');
        const pageIndicator = document.getElementById('pix-page-indicator');
        const paginationInfo = document.getElementById('pix-pagination-info');
        
        if (prevBtn) {
            prevBtn.disabled = currentPage <= 1;
        }
        
        if (nextBtn) {
            nextBtn.disabled = !hasMore;
        }
        
        if (pageIndicator) {
            pageIndicator.textContent = `Página ${currentPage}`;
        }
        
        if (paginationInfo) {
            const start = (currentPage - 1) * this.pixPerPage + 1;
            const end = start + itemsOnPage - 1;
            if (itemsOnPage === 0) {
                paginationInfo.textContent = 'Nenhum registro';
            } else {
                paginationInfo.textContent = `Mostrando ${start} - ${end}`;
            }
        }
    }

    renderTransactionRow(tx) {
        const statusBadge = this.getStatusBadge(tx.status);
        const createdAt = tx.created_at ? new Date(tx.created_at).toLocaleString('pt-BR') : '-';
        const paidAt = tx.paid_at ? new Date(tx.paid_at).toLocaleString('pt-BR') : '-';
        const amount = this.formatCurrency(tx.amount || 0);
        const renavam = tx.renavam || '-';
        const placaVeiculo = tx.placa || tx.veiculo || tx.proprietario || '-';
        
        return `
            <tr>
                <td><small>${tx.transaction_id || tx.id}</small></td>
                <td><small>${createdAt}</small></td>
                <td><small>${renavam}</small></td>
                <td><small>${placaVeiculo}</small></td>
                <td><strong>${amount}</strong></td>
                <td>${statusBadge}</td>
                <td><small>${paidAt}</small></td>
                <td>
                    <button class="btn btn-sm btn-outline-primary" onclick="adminDashboard.checkTransaction('${tx.transaction_id || tx.id}')" title="Verificar status">
                        ↻
                    </button>
                </td>
            </tr>
        `;
    }

    getStatusBadge(status) {
        const badges = {
            'pending': '<span class="badge" style="background-color: #ffc107; color: #000;">Pendente</span>',
            'waiting_payment': '<span class="badge" style="background-color: #ffc107; color: #000;">Aguardando</span>',
            'paid': '<span class="badge" style="background-color: #28a745; color: #fff;">Pago</span>',
            'failed': '<span class="badge" style="background-color: #dc3545; color: #fff;">Falhou</span>',
            'refused': '<span class="badge" style="background-color: #dc3545; color: #fff;">Recusado</span>',
            'refunded': '<span class="badge" style="background-color: #6c757d; color: #fff;">Reembolsado</span>',
            'expired': '<span class="badge" style="background-color: #6c757d; color: #fff;">Expirado</span>'
        };
        return badges[status] || `<span class="badge" style="background-color: #6c757d; color: #fff;">${status}</span>`;
    }

    async checkTransaction(transactionId) {
        try {
            const response = await fetch(`../pix-api.php?action=check&id=${transactionId}`, { cache: 'no-store' });
            const result = await response.json();

            if (result.status === 'success') {
                await this.loadPixStats();
                await this.loadPixTransactions(document.getElementById('pix-filter-status')?.value || '', this.pixCurrentPage);
                
                const statusText = result.data.status === 'paid' ? 'PAGO' : result.data.status.toUpperCase();
                alert(`Transação ${transactionId}\nStatus: ${statusText}`);
            } else {
                alert('Erro ao verificar: ' + (result.message || 'Erro desconhecido'));
            }
        } catch (error) {
            alert('Erro de conexão ao verificar transação.');
        }
    }

    setupPixFilters() {
        const filterStatus = document.getElementById('pix-filter-status');
        const filterMode = document.getElementById('pix-filter-mode');
        const refreshBtn = document.getElementById('refresh-pix-transactions');
        const prevBtn = document.getElementById('pix-prev-page');
        const nextBtn = document.getElementById('pix-next-page');

        const getFilters = () => ({
            status: filterStatus?.value || '',
            mode: filterMode?.value || ''
        });

        if (filterStatus) {
            filterStatus.addEventListener('change', () => {
                this.pixCurrentPage = 1;
                const f = getFilters();
                this.loadPixTransactions(f.status, 1, f.mode);
            });
        }

        if (filterMode) {
            filterMode.addEventListener('change', () => {
                this.pixCurrentPage = 1;
                const f = getFilters();
                this.loadPixTransactions(f.status, 1, f.mode);
            });
        }

        if (refreshBtn) {
            refreshBtn.addEventListener('click', async () => {
                refreshBtn.disabled = true;
                refreshBtn.textContent = 'Atualizando...';
                
                await this.loadPixStats();
                const f = getFilters();
                await this.loadPixTransactions(f.status, this.pixCurrentPage, f.mode);
                
                refreshBtn.disabled = false;
                refreshBtn.textContent = 'Atualizar';
            });
        }

        // Botão Página Anterior
        if (prevBtn) {
            prevBtn.addEventListener('click', () => {
                if (this.pixCurrentPage > 1) {
                    const f = getFilters();
                    this.loadPixTransactions(f.status, this.pixCurrentPage - 1, f.mode);
                }
            });
        }

        // Botão Próxima Página
        if (nextBtn) {
            nextBtn.addEventListener('click', () => {
                const f = getFilters();
                this.loadPixTransactions(f.status, this.pixCurrentPage + 1, f.mode);
            });
        }
    }

    // --- Gerenciamento de Sessões ---
    async loadSessions(filter = '', page = 1, pixMode = '') {
        const container = document.getElementById('sessions-container');
        if (!container) return;

        container.innerHTML = `<div style="text-align: center; padding: 20px;"><div class="loading"></div> Carregando sessões...</div>`;

        try {
            let url = `api.php?action=sessions&page=${page}&limit=${this.sessionsPerPage}`;
            if (filter) {
                url += `&filter=${encodeURIComponent(filter)}`;
            }
            if (pixMode) {
                url += `&pix_mode=${encodeURIComponent(pixMode)}`;
            }

            const response = await fetch(url, { cache: 'no-store' });
            const result = await response.json();

            if (result.status === 'success' && Array.isArray(result.data)) {
                if (result.data.length === 0) {
                    container.innerHTML = `<div style="text-align: center; padding: 30px; color: #666;">Nenhuma sessão encontrada.</div>`;
                    this.updateSessionsPagination(0, page, result.pagination);
                    return;
                }

                container.innerHTML = result.data.map(session => this.renderSessionCard(session)).join('');
                this.updateSessionsPagination(result.data.length, page, result.pagination);
            } else {
                container.innerHTML = `<div style="text-align: center; padding: 30px; color: #dc3545;">Erro ao carregar sessões.</div>`;
            }
        } catch (error) {
            console.error('Erro ao carregar sessões:', error);
            container.innerHTML = `<div style="text-align: center; padding: 30px; color: #dc3545;">Erro de conexão.</div>`;
        }
    }

    renderSessionCard(session) {
        const startedAt = session.started_at ? new Date(session.started_at).toLocaleString('pt-BR') : '-';
        const lastActivity = session.last_activity ? new Date(session.last_activity).toLocaleString('pt-BR') : '-';
        
        // Determinar nome da sessão (RENAVAM/Placa para MG)
        let sessionName = 'Visitante';
        const renavam = session.renavam || session.renavam_consulta || '';
        const placa = session.placa || session.placa_consulta || '';
        
        if (placa) {
            sessionName = '🚗 ' + placa;
        } else if (renavam) {
            sessionName = 'RENAVAM: ' + renavam;
        }
        
        // Classes extras
        let extraClasses = '';
        if (session.has_payment == 1) extraClasses += ' has-payment';
        else if (renavam || placa) extraClasses += ' has-cnpj';
        
        // Badges
        let badges = '';
        const eventTypes = (session.event_types || '').split(',');
        
        if (eventTypes.includes('visit') || eventTypes.includes('page_view')) {
            badges += `<span class="session-badge visit">👁️ Visitou</span>`;
        }
        if (renavam || placa) {
            badges += `<span class="session-badge cnpj">🚗 Consultou</span>`;
        }
        if (session.has_pix == 1) {
            const amount = session.pix_amount ? this.formatCurrency(parseFloat(session.pix_amount)) : '';
            badges += `<span class="session-badge pix">💳 PIX ${amount}</span>`;
        }
        if (session.has_payment == 1) {
            badges += `<span class="session-badge paid">✅ Pagou</span>`;
        }
        
        // Summary
        let summary = `${session.event_count} eventos`;
        if (renavam) {
            summary += ` • RENAVAM: ${renavam}`;
        }
        if (placa) {
            summary += ` • Placa: ${placa}`;
        }
        
        return `
            <div class="session-card${extraClasses}" onclick="adminDashboard.showSessionDetails('${session.session_id}', '${sessionName.replace(/'/g, "\\'")}')">
                <div class="session-header">
                    <span class="session-name">${sessionName}</span>
                    <span class="session-time">${startedAt}</span>
                </div>
                <div class="session-badges">${badges}</div>
                <div class="session-summary">${summary}</div>
            </div>
        `;
    }

    updateSessionsPagination(itemsOnPage, currentPage, pagination) {
        this.sessionsCurrentPage = currentPage;
        
        const prevBtn = document.getElementById('sessions-prev-page');
        const nextBtn = document.getElementById('sessions-next-page');
        const pageIndicator = document.getElementById('sessions-page-indicator');
        const paginationInfo = document.getElementById('sessions-pagination-info');
        
        const totalPages = pagination?.totalPages || 1;
        const total = pagination?.total || 0;
        
        if (prevBtn) {
            prevBtn.disabled = currentPage <= 1;
        }
        
        if (nextBtn) {
            nextBtn.disabled = currentPage >= totalPages;
        }
        
        if (pageIndicator) {
            pageIndicator.textContent = `Página ${currentPage} de ${totalPages}`;
        }
        
        if (paginationInfo) {
            paginationInfo.textContent = `${total} sessões encontradas`;
        }
    }

    setupSessionsControls() {
        const filterSelect = document.getElementById('sessions-filter');
        const pixModeFilter = document.getElementById('sessions-pix-mode-filter');
        const refreshBtn = document.getElementById('refresh-sessions');
        const prevBtn = document.getElementById('sessions-prev-page');
        const nextBtn = document.getElementById('sessions-next-page');

        const getFilters = () => ({
            filter: filterSelect?.value || '',
            pixMode: pixModeFilter?.value || ''
        });

        if (filterSelect) {
            filterSelect.addEventListener('change', () => {
                this.sessionsCurrentPage = 1;
                const f = getFilters();
                this.loadSessions(f.filter, 1, f.pixMode);
            });
        }

        if (pixModeFilter) {
            pixModeFilter.addEventListener('change', () => {
                this.sessionsCurrentPage = 1;
                const f = getFilters();
                this.loadSessions(f.filter, 1, f.pixMode);
            });
        }

        if (refreshBtn) {
            refreshBtn.addEventListener('click', () => {
                const f = getFilters();
                this.loadSessions(f.filter, this.sessionsCurrentPage, f.pixMode);
            });
        }

        if (prevBtn) {
            prevBtn.addEventListener('click', () => {
                if (this.sessionsCurrentPage > 1) {
                    const f = getFilters();
                    this.loadSessions(f.filter, this.sessionsCurrentPage - 1, f.pixMode);
                }
            });
        }

        if (nextBtn) {
            nextBtn.addEventListener('click', () => {
                const f = getFilters();
                this.loadSessions(f.filter, this.sessionsCurrentPage + 1, f.pixMode);
            });
        }
    }

    async showSessionDetails(sessionId, sessionName) {
        const modal = document.getElementById('session-modal');
        const title = document.getElementById('session-modal-title');
        const content = document.getElementById('session-modal-content');
        
        if (!modal || !content) return;
        
        title.textContent = sessionName || 'Detalhes da Sessão';
        content.innerHTML = `<div style="text-align: center; padding: 30px;"><div class="loading"></div> Carregando...</div>`;
        modal.style.display = 'block';
        
        try {
            const response = await fetch(`api.php?action=session-details&session_id=${encodeURIComponent(sessionId)}`, { cache: 'no-store' });
            const result = await response.json();
            
            if (result.status === 'success' && Array.isArray(result.data)) {
                content.innerHTML = this.renderSessionTimeline(result.data);
            } else {
                content.innerHTML = `<div style="text-align: center; color: #dc3545;">Erro ao carregar detalhes.</div>`;
            }
        } catch (error) {
            content.innerHTML = `<div style="text-align: center; color: #dc3545;">Erro de conexão.</div>`;
        }
    }

    renderSessionTimeline(events) {
        if (events.length === 0) {
            return `<div style="text-align: center; color: #666;">Nenhum evento encontrado.</div>`;
        }
        
        let html = '<div class="event-timeline">';
        
        events.forEach(event => {
            const time = new Date(event.event_timestamp).toLocaleString('pt-BR');
            let metadata = {};
            try {
                metadata = JSON.parse(event.metadata || '{}');
            } catch (e) {}
            
            // Determinar classe e detalhe baseado no tipo
            let eventClass = '';
            let detail = '';
            const type = event.event_type;
            
            if (type === 'visit' || type === 'page_view' || type === 'page_load') {
                eventClass = 'visit';
                detail = metadata.page || metadata.url || '-';
            } else if (type === 'consulta_ipva' || type === 'cnpj_consulta' || type === 'cnpj_consultation_start') {
                eventClass = 'cnpj';
                detail = metadata.renavam || metadata.cnpj || '-';
                if (metadata.placa) detail += ` - ${metadata.placa}`;
                if (metadata.razao_social) detail += ` - ${metadata.razao_social}`;
            } else if (type === 'pix_gerado' || type === 'pagamento_gerado' || type === 'pix_generation_success') {
                eventClass = 'pix';
                detail = metadata.amount ? this.formatCurrency(parseFloat(metadata.amount)) : '';
                if (metadata.transaction_id) detail += ` (ID: ${metadata.transaction_id})`;
            } else if (type === 'pix_pago') {
                eventClass = 'paid';
                detail = metadata.amount ? this.formatCurrency(parseFloat(metadata.amount)) : 'Pagamento confirmado';
            } else if (type === 'button_click') {
                detail = metadata.button || '-';
            } else {
                detail = JSON.stringify(metadata).substring(0, 100);
            }
            
            // Traduzir tipo de evento
            const typeLabels = {
                'visit': 'Visita',
                'page_view': 'Visualização',
                'page_load': 'Página carregada',
                'button_click': 'Clique em botão',
                'consulta_ipva': 'Consulta IPVA',
                'cnpj_consulta': 'Consulta CNPJ',
                'cnpj_consultation_start': 'Início consulta CNPJ',
                'pix_gerado': 'PIX gerado',
                'pix_copiado': 'PIX copiado',
                'pix_confirmado': 'PIX confirmado',
                'pagamento_gerado': 'Pagamento gerado',
                'pix_generation_success': 'PIX criado com sucesso',
                'pix_pago': '✅ PAGAMENTO CONFIRMADO'
            };
            
            const typeLabel = typeLabels[type] || type;
            
            html += `
                <div class="timeline-event ${eventClass}">
                    <div class="timeline-time">${time}</div>
                    <div class="timeline-type">${typeLabel}</div>
                    <div class="timeline-detail">${detail}</div>
                </div>
            `;
        });
        
        html += '</div>';
        return html;
    }

    formatCurrency(value) {
        return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(value);
    }

    formatCNPJ(cnpj) {
        const clean = (cnpj || '').replace(/\D/g, '');
        if (clean.length !== 14) return cnpj;
        return clean.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/, '$1.$2.$3/$4-$5');
    }

    // --- Limpar Todos os Dados ---
    setupClearDataButton() {
        const clearBtn = document.getElementById('clear-all-data');
        const statusEl = document.getElementById('clear-data-status');
        
        if (!clearBtn) return;

        const showStatus = (msg, isError = false) => {
            if (!statusEl) return;
            statusEl.textContent = msg;
            statusEl.style.color = isError ? '#dc3545' : '#28a745';
            setTimeout(() => {
                statusEl.textContent = '';
                statusEl.style.color = '';
            }, 4000);
        };

        clearBtn.addEventListener('click', async () => {
            const confirmed = confirm(
                'ATENÇÃO!\n\n' +
                'Você está prestes a APAGAR TODOS OS DADOS:\n' +
                '• Todas as visitas\n' +
                '• Todas as consultas CNPJ\n' +
                '• Todos os PIX gerados\n' +
                '• Todos os PIX pagos\n\n' +
                'A configuração PIX e a senha do admin serão mantidas.\n\n' +
                'Esta ação NÃO pode ser desfeita!\n\n' +
                'Deseja continuar?'
            );

            if (!confirmed) return;

            const doubleConfirm = confirm(
                'CONFIRMAÇÃO FINAL\n\n' +
                'Tem CERTEZA ABSOLUTA que deseja apagar todos os dados?\n\n' +
                'Clique em OK para confirmar.'
            );

            if (!doubleConfirm) return;

            const originalText = clearBtn.innerHTML;
            clearBtn.disabled = true;
            clearBtn.innerHTML = 'Apagando...';

            try {
                const response = await fetch('api.php', {
                    method: 'DELETE',
                    cache: 'no-store'
                });

                const result = await response.json().catch(() => null);

                if (!response.ok) {
                    throw new Error(result?.message || `Erro HTTP ${response.status}`);
                }

                showStatus('✓ Todos os dados foram apagados!');
                
                // Recarrega os dados para atualizar a interface
                await this.loadData();
                
            } catch (err) {
                showStatus(`Erro: ${err.message}`, true);
            } finally {
                clearBtn.disabled = false;
                clearBtn.innerHTML = originalText;
            }
        });
    }

    // --- Configuração PIX Completa (Automático e Manual) ---
    async setupPixConfig() {
        const saveBtn = document.getElementById('save-pix-config');
        const statusEl = document.getElementById('pix-config-status');
        const modeAutoRadio = document.getElementById('pix-mode-auto');
        const modeManualRadio = document.getElementById('pix-mode-manual');
        const autoConfigDiv = document.getElementById('pix-auto-config');
        const manualConfigDiv = document.getElementById('pix-manual-config');
        const modeAutoLabel = document.getElementById('mode-auto-label');
        const modeManualLabel = document.getElementById('mode-manual-label');

        if (!saveBtn) {
            console.log('setupPixConfig: botão salvar não encontrado');
            return;
        }

        console.log('setupPixConfig: elementos encontrados', {
            autoConfigDiv: !!autoConfigDiv,
            manualConfigDiv: !!manualConfigDiv,
            modeAutoRadio: !!modeAutoRadio,
            modeManualRadio: !!modeManualRadio
        });

        const showStatus = (msg, isError = false) => {
            if (!statusEl) return;
            statusEl.textContent = msg;
            statusEl.style.color = isError ? '#dc3545' : '#28a745';
            setTimeout(() => {
                statusEl.textContent = '';
                statusEl.style.color = '';
            }, 4000);
        };

        // Função para alternar a visualização dos modos
        const toggleModeVisibility = (mode) => {
            console.log('toggleModeVisibility:', mode);
            
            const autoDiv = document.getElementById('pix-auto-config');
            const manualDiv = document.getElementById('pix-manual-config');
            const autoLabel = document.getElementById('mode-auto-label');
            const manualLabel = document.getElementById('mode-manual-label');
            
            if (!autoDiv || !manualDiv) {
                console.error('Divs de configuração não encontrados');
                return;
            }
            
            if (mode === 'auto') {
                autoDiv.style.display = 'block';
                manualDiv.style.display = 'none';
                if (autoLabel) {
                    autoLabel.style.borderColor = '#27ae60';
                    autoLabel.style.background = '#f0fff0';
                }
                if (manualLabel) {
                    manualLabel.style.borderColor = '#ddd';
                    manualLabel.style.background = 'white';
                }
            } else {
                autoDiv.style.display = 'none';
                manualDiv.style.display = 'block';
                if (manualLabel) {
                    manualLabel.style.borderColor = '#3498db';
                    manualLabel.style.background = '#f0f8ff';
                }
                if (autoLabel) {
                    autoLabel.style.borderColor = '#ddd';
                    autoLabel.style.background = 'white';
                }
            }
        };

        // Event listeners para trocar modo (no radio e no label)
        if (modeAutoRadio) {
            modeAutoRadio.addEventListener('change', () => toggleModeVisibility('auto'));
        }
        if (modeManualRadio) {
            modeManualRadio.addEventListener('change', () => toggleModeVisibility('manual'));
        }
        
        // Também adicionar click nos labels para maior compatibilidade
        if (modeAutoLabel) {
            modeAutoLabel.addEventListener('click', () => {
                if (modeAutoRadio) modeAutoRadio.checked = true;
                toggleModeVisibility('auto');
            });
        }
        if (modeManualLabel) {
            modeManualLabel.addEventListener('click', () => {
                if (modeManualRadio) modeManualRadio.checked = true;
                toggleModeVisibility('manual');
            });
        }

        // Carregar configuração existente
        try {
            const response = await fetch('config.php?type=pix', { cache: 'no-store' });
            const result = await response.json();
            
            if (result.status === 'success' && result.data) {
                const cfg = result.data;
                
                // Modo
                if (cfg.mode === 'manual') {
                    if (modeManualRadio) modeManualRadio.checked = true;
                    toggleModeVisibility('manual');
                } else {
                    if (modeAutoRadio) modeAutoRadio.checked = true;
                    toggleModeVisibility('auto');
                }
                
                // Ativo
                document.getElementById('pix-active').checked = cfg.active !== false;
                
                // PIX Automático
                document.getElementById('pix-api-url').value = cfg.apiUrl || 'https://api.raypaymentsv2.com.br/functions/v1';
                document.getElementById('pix-secret-key').value = cfg.secretKey || '';
                document.getElementById('pix-company-id').value = cfg.companyId || '';
                
                // PIX Manual
                document.getElementById('pix-key-type').value = cfg.pixKeyType || 'cpf';
                document.getElementById('pix-key').value = cfg.pixKey || '';
                document.getElementById('pix-receiver-name').value = cfg.receiverName || 'PAGAMENTO';
                document.getElementById('pix-receiver-city').value = cfg.receiverCity || 'SAO PAULO';
            }
        } catch (e) {
            console.error('Erro ao carregar config PIX:', e);
        }

        // Salvar configuração
        saveBtn.addEventListener('click', async () => {
            const mode = modeManualRadio.checked ? 'manual' : 'auto';
            
            const configData = {
                mode: mode,
                active: document.getElementById('pix-active').checked,
                
                // PIX Automático
                apiUrl: document.getElementById('pix-api-url').value.trim(),
                secretKey: document.getElementById('pix-secret-key').value.trim(),
                companyId: document.getElementById('pix-company-id').value.trim(),
                
                // PIX Manual
                pixKeyType: document.getElementById('pix-key-type').value,
                pixKey: document.getElementById('pix-key').value.trim(),
                receiverName: document.getElementById('pix-receiver-name').value.trim() || 'PAGAMENTO',
                receiverCity: document.getElementById('pix-receiver-city').value.trim() || 'SAO PAULO'
            };

            // Validações básicas
            if (mode === 'auto' && (!configData.secretKey || !configData.companyId)) {
                showStatus('Preencha Secret Key e Company ID para o modo automático', true);
                return;
            }
            
            if (mode === 'manual' && !configData.pixKey) {
                showStatus('Preencha a Chave PIX para o modo manual', true);
                return;
            }

            const originalText = saveBtn.textContent;
            saveBtn.disabled = true;
            saveBtn.textContent = 'Salvando...';

            try {
                const response = await fetch('config.php?type=pix', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(configData)
                });
                
                const result = await response.json();
                
                if (result.status === 'success') {
                    showStatus('✓ Configurações PIX salvas com sucesso!');
                } else {
                    showStatus(result.message || 'Erro ao salvar', true);
                }
            } catch (e) {
                showStatus('Erro de conexão: ' + e.message, true);
            } finally {
                saveBtn.disabled = false;
                saveBtn.textContent = originalText;
            }
        });
    }

    // --- Configuração Valores dos Meses DAS-MEI ---

    async fetchValoresMesesFromDb() {
        const response = await fetch('config.php?type=valores_meses', { method: 'GET', cache: 'no-store' });
        if (!response.ok) throw new Error(`HTTP ${response.status}`);
        const payload = await response.json();
        if (payload?.status !== 'success' || !payload?.data) throw new Error('Invalid response');
        return payload.data;
    }

    async saveValoresMesesToDb(valores) {
        const response = await fetch('config.php?type=valores_meses', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            cache: 'no-store',
            body: JSON.stringify({ valores_meses: valores })
        });
        const payload = await response.json().catch(() => null);
        if (!response.ok) {
            const msg = payload?.message || `HTTP ${response.status}`;
            throw new Error(msg);
        }
        if (payload?.status !== 'success') {
            throw new Error(payload?.message || 'Erro ao salvar');
        }
        return payload.data;
    }

    async setupValoresMeses() {
        const saveBtn = document.getElementById('save-valores-meses');
        const statusEl = document.getElementById('valores-meses-status');

        if (!saveBtn) return;

        const showStatus = (msg, isError = false) => {
            if (!statusEl) return;
            statusEl.textContent = msg;
            statusEl.style.color = isError ? '#dc3545' : '#28a745';
            setTimeout(() => {
                statusEl.textContent = '';
                statusEl.style.color = '';
            }, 3000);
        };

        // Formatar valor para exibição (75.90 -> 75,90)
        const formatValorDisplay = (valor) => {
            if (valor === null || valor === undefined || valor === '') return '';
            return parseFloat(valor).toFixed(2).replace('.', ',');
        };

        // Parse valor do input (75,90 -> 75.90)
        const parseValorInput = (valorStr) => {
            if (!valorStr || valorStr.trim() === '') return 0;
            // Remove pontos de milhar e troca vírgula por ponto
            const normalized = valorStr.replace(/\./g, '').replace(',', '.');
            return parseFloat(normalized) || 0;
        };

        // Carregar valores do DB
        try {
            const dbCfg = await this.fetchValoresMesesFromDb();
            
            // Preencher os inputs
            document.querySelectorAll('.valor-mes').forEach(input => {
                const mes = input.dataset.mes;
                if (mes && dbCfg[mes] !== undefined) {
                    input.value = formatValorDisplay(dbCfg[mes]);
                }
            });
        } catch (e) {
            console.error('Falha ao carregar valores dos meses:', e);
            showStatus(`Falha ao carregar: ${e.message}`, true);
        }

        // Evento de salvar
        saveBtn.addEventListener('click', async () => {
            const valores = {};
            
            document.querySelectorAll('.valor-mes').forEach(input => {
                const mes = input.dataset.mes;
                if (mes) {
                    valores[mes] = parseValorInput(input.value);
                }
            });

            const originalHTML = saveBtn.innerHTML;
            saveBtn.disabled = true;
            saveBtn.innerHTML = 'Salvando...';

            try {
                const savedData = await this.saveValoresMesesToDb(valores);
                
                // Atualizar inputs com valores salvos
                document.querySelectorAll('.valor-mes').forEach(input => {
                    const mes = input.dataset.mes;
                    if (mes && savedData[mes] !== undefined) {
                        input.value = formatValorDisplay(savedData[mes]);
                    }
                });
                
                showStatus('✓ Valores salvos com sucesso!');
            } catch (err) {
                showStatus(`Erro: ${err.message}`, true);
            } finally {
                saveBtn.disabled = false;
                saveBtn.innerHTML = originalHTML;
            }
        });
    }

    // Carrega dados da API PHP
    async loadData() {
        try {
            const response = await fetch('api.php');
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const data = await response.json();

            this.updateStats(data.stats);
            this.updateUtmSources(data.utm_sources);
            this.updateCharts(); // Atualiza gráficos independentemente
            console.log('Dados carregados da API PHP');
        } catch (error) {
            console.error('Erro ao carregar dados da API PHP:', error);
        }
    }

    // Atualiza estatísticas principais dos cards
    updateStats(stats) {
        // Visits
        const visits = stats.visit || { total: 0, change: 0 };
        document.getElementById('total-visits').textContent = visits.total;
        this.updateStatsChange('visits-change', visits.change);

        // Consultas IPVA (ou CNPJ legado)
        const consultas = stats.consulta_ipva || stats.cnpj_consulta || { total: 0, change: 0 };
        document.getElementById('cnpj-consultas').textContent = consultas.total;
        this.updateStatsChange('cnpj-change', consultas.change);

        // PIX Gerados
        const pixGerados = stats.pix_gerado || { total: 0, change: 0 };
        document.getElementById('pix-gerados').textContent = pixGerados.total;
        this.updateStatsChange('pix-gerados-change', pixGerados.change);

        // PIX Pagos
        const pixPagos = stats.pix_pago || { total: 0, change: 0 };
        document.getElementById('pix-pagos').textContent = pixPagos.total;
        this.updateStatsChange('pix-pagos-change', pixPagos.change);
    }

    // Helper para atualizar o card de mudança de %
    updateStatsChange(elementId, change) {
        const el = document.getElementById(elementId);
        if (!el) return;

        const changeRounded = Math.round(change);
        el.textContent = `${changeRounded >= 0 ? '+' : ''}${changeRounded}% hoje`;

        el.classList.remove('stats-positive', 'stats-negative');
        if (changeRounded >= 0) {
            el.classList.add('stats-positive');
        } else {
            el.classList.add('stats-negative');
        }
    }

    // Atualiza a lista de fontes UTM
    updateUtmSources(sources) {
        const utmList = document.getElementById('utm-sources-list');
        if (!utmList) return;

        utmList.innerHTML = ''; // Limpa a lista

        if (!sources || sources.length === 0) {
            utmList.innerHTML = '<li class="list-group-item">Nenhuma fonte UTM registrada.</li>';
            return;
        }

        sources.forEach(source => {
            const li = document.createElement('li');
            li.className = 'list-group-item d-flex justify-content-between align-items-center';
            li.textContent = source.utm_source || 'direto';
            
            const badge = document.createElement('span');
            badge.className = 'badge badge-primary badge-pill';
            badge.textContent = source.count;
            
            li.appendChild(badge);
            utmList.appendChild(li);
        });
    }

    // Atualiza os gráficos com os novos dados
    async updateCharts() {
        try {
            // Busca eventos das últimas 24 horas para o gráfico
            const response = await fetch('api.php?action=events&limit=1000');
            const data = await response.json();
            
            if (!data.events || data.events.length === 0) {
                this.charts.visits.data.labels = [];
                this.charts.visits.data.datasets.forEach(ds => ds.data = []);
                this.charts.visits.update();
                return;
            }
            
            // Agrupa eventos por hora e tipo
            const byHour = {};
            const now = new Date();
            const last24h = new Date(now.getTime() - 24 * 60 * 60 * 1000);
            
            // Inicializa todas as 24 horas
            for (let i = 0; i < 24; i++) {
                byHour[i] = { visit: 0, cnpj_consulta: 0, pix_gerado: 0, pix_pago: 0 };
            }
            
            data.events
                .filter(e => new Date(e.event_timestamp) >= last24h)
                .forEach(event => {
                    const hour = new Date(event.event_timestamp).getHours();
                    const type = event.event_type;
                    
                    // Mapeia page_view para visit
                    if (type === 'visit' || type === 'page_view') {
                        byHour[hour].visit++;
                    } else if (type === 'consulta_ipva' || type === 'cnpj_consulta' || type === 'cnpj_consultation_start') {
                        byHour[hour].cnpj_consulta++;
                    } else if (type === 'pix_gerado' || type === 'pagamento_gerado' || type === 'pix_generation_success') {
                        byHour[hour].pix_gerado++;
                    } else if (type === 'pix_pago') {
                        byHour[hour].pix_pago++;
                    }
                });

            const chartLabels = Object.keys(byHour).sort((a, b) => a - b).map(h => `${h}:00`);
            
            this.charts.visits.data.labels = chartLabels;
            this.charts.visits.data.datasets[0].data = chartLabels.map((_, i) => byHour[i].visit);
            this.charts.visits.data.datasets[1].data = chartLabels.map((_, i) => byHour[i].cnpj_consulta);
            this.charts.visits.data.datasets[2].data = chartLabels.map((_, i) => byHour[i].pix_gerado);
            this.charts.visits.data.datasets[3].data = chartLabels.map((_, i) => byHour[i].pix_pago);
            this.charts.visits.update();
        } catch (error) {
            console.error('Erro ao atualizar gráficos:', error);
        }
    }

    // Inicia a atualização automática
    startAutoRefresh() {
        setInterval(() => {
            this.loadData();
            this.updateLastUpdateTime();
        }, 30000); // Atualiza a cada 30 segundos
    }

    // Atualiza o horário da última atualização
    updateLastUpdateTime() {
        const now = new Date();
        document.getElementById('last-update-time').textContent = now.toLocaleTimeString();
    }

    // Configuração inicial dos gráficos
    setupCharts() {
        const ctx = document.getElementById('visits-chart').getContext('2d');
        this.charts.visits = new Chart(ctx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [
                    {
                        label: 'Visitas',
                        data: [],
                        borderColor: '#3e95cd',
                        backgroundColor: 'rgba(62, 149, 205, 0.1)',
                        fill: false,
                        tension: 0.3
                    },
                    {
                        label: 'Consultas CNPJ',
                        data: [],
                        borderColor: '#28a745',
                        backgroundColor: 'rgba(40, 167, 69, 0.1)',
                        fill: false,
                        tension: 0.3
                    },
                    {
                        label: 'PIX Gerados',
                        data: [],
                        borderColor: '#fd7e14',
                        backgroundColor: 'rgba(253, 126, 20, 0.1)',
                        fill: false,
                        tension: 0.3
                    },
                    {
                        label: 'PIX Pagos',
                        data: [],
                        borderColor: '#dc3545',
                        backgroundColor: 'rgba(220, 53, 69, 0.1)',
                        fill: false,
                        tension: 0.3
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: true,
                        position: 'top'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }
}

// Variável global para acesso às funções do dashboard
let adminDashboard;

// Função para toggle da configuração PIX
function togglePixConfig() {
    const body = document.getElementById('pix-config-body');
    const toggle = document.getElementById('pix-config-toggle');
    
    if (body && toggle) {
        const isVisible = body.style.display !== 'none';
        body.style.display = isVisible ? 'none' : 'block';
        toggle.textContent = isVisible ? '▼' : '▲';
    }
}

// Inicia o dashboard quando o DOM estiver pronto
document.addEventListener('DOMContentLoaded', () => {
    adminDashboard = new AdminDashboard();
});
