// Admin Dashboard - Conectado ao Backend PHP
class AdminDashboard {
    constructor() {
        this.charts = {};
        this.init();
    }

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

    // --- Configuração PIX (SQLite via PHP) ---

    async fetchPixConfigFromDb() {
        const response = await fetch('config.php', { 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 savePixConfigToDb(config) {
        const response = await fetch('config.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            cache: 'no-store',
            body: JSON.stringify(config)
        });
        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 setupPixConfig() {
        const keyEl = document.getElementById('pix-key');
        const nameEl = document.getElementById('pix-receiver-name');
        const cityEl = document.getElementById('pix-receiver-city');
        const saveBtn = document.getElementById('save-pix-config');
        const statusEl = document.getElementById('pix-config-status');

        // Se a tela não tiver o bloco (futuro), não faz nada.
        if (!keyEl || !nameEl || !cityEl || !saveBtn) return;

        const showStatus = (msg) => {
            if (!statusEl) return;
            statusEl.textContent = msg;
            setTimeout(() => {
                statusEl.textContent = '';
            }, 2500);
        };

        const showStatusError = (msg) => {
            if (!statusEl) return;
            statusEl.textContent = msg;
            statusEl.style.color = '#dc3545';
            setTimeout(() => {
                statusEl.textContent = '';
                statusEl.style.color = '';
            }, 4000);
        };

        // Carrega do DB
        try {
            const dbCfg = await this.fetchPixConfigFromDb();
            keyEl.value = (dbCfg.pixKey || '').trim();
            nameEl.value = (dbCfg.receiverName || '').trim();
            cityEl.value = (dbCfg.receiverCity || '').trim();
        } catch (e) {
            keyEl.value = '';
            nameEl.value = '';
            cityEl.value = '';
            showStatusError(`Falha ao carregar do DB: ${e.message}`);
        }

        saveBtn.addEventListener('click', async () => {
            const pixKey = (keyEl.value || '').trim();
            const receiverName = (nameEl.value || '').trim();
            const receiverCity = (cityEl.value || '').trim();

            if (!pixKey) {
                showStatusError('Informe a chave PIX.');
                return;
            }

            // O site usa o valor calculado pelos períodos selecionados, não um valor fixo no admin.
            const payload = { pixKey, receiverName, receiverCity, amount: null };

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

            try {
                await this.savePixConfigToDb(payload);
                // Rebusca do DB para confirmar persistência e evitar efeito de cache
                const dbCfg = await this.fetchPixConfigFromDb();
                keyEl.value = (dbCfg.pixKey || '').trim();
                nameEl.value = (dbCfg.receiverName || '').trim();
                cityEl.value = (dbCfg.receiverCity || '').trim();
                showStatus('Salvo no DB!');
            } catch (err) {
                showStatusError(`Falha ao salvar no DB: ${err.message}`);
            } finally {
                saveBtn.disabled = false;
                saveBtn.textContent = originalText;
            }
        });
    }

    // 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.updateTables(data.events);
            this.updateCharts(data.events); // Adicionado para atualizar gráficos
            this.updateUtmSources(data.utm_sources);
            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);

        // CNPJ Consultas
        const cnpjs = stats.cnpj_consulta || { total: 0, change: 0 };
        document.getElementById('cnpj-consultas').textContent = cnpjs.total;
        this.updateStatsChange('cnpj-change', cnpjs.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 tabelas de eventos recentes
    updateTables(events) {
        const recentEventsBody = document.getElementById('recent-events-body');
        recentEventsBody.innerHTML = ''; // Limpa a tabela

        if (!events || events.length === 0) {
            recentEventsBody.innerHTML = '<tr><td colspan="4">Nenhum evento recente.</td></tr>';
            return;
        }

        events.forEach(event => {
            const row = document.createElement('tr');
            let metadata;
            try {
                metadata = JSON.parse(event.metadata || '{}');
            } catch (e) {
                metadata = { info: 'Metadados inválidos' };
            }
            
            const utm = metadata.utm || {};
            const utmString = Object.entries(utm).map(([key, value]) => `${key}=${value}`).join(' & ');

            row.innerHTML = `
                <td>${event.event_type}</td>
                <td>${new Date(event.event_timestamp).toLocaleString()}</td>
                <td>${metadata.page || metadata.cnpj || 'N/A'}</td>
                <td>${utmString || 'N/A'}</td>
            `;
            recentEventsBody.appendChild(row);
        });
    }

    // 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
    updateCharts(events) {
        // Agrupa visitas por hora
        const visitsByHour = {};
        events.filter(e => e.event_type === 'visit').forEach(event => {
            const hour = new Date(event.event_timestamp).getHours();
            visitsByHour[hour] = (visitsByHour[hour] || 0) + 1;
        });

        const chartLabels = Object.keys(visitsByHour).sort((a, b) => a - b).map(h => `${h}:00`);
        const chartData = Object.values(visitsByHour);

        this.charts.visits.data.labels = chartLabels;
        this.charts.visits.data.datasets[0].data = chartData;
        this.charts.visits.update();
    }

    // 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 por Hora',
                    data: [],
                    borderColor: '#3e95cd',
                    backgroundColor: 'rgba(62, 149, 205, 0.1)',
                    fill: true,
                    tension: 0.3
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false
            }
        });
    }
}

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