/**
 * PIX Module
 * Configuração PIX, geração de QR Code, histórico
 */
const PIX = {
    // Site atualmente selecionado para config PIX
    currentSiteId: null,
    
    /**
     * Atualiza o seletor de site na página PIX
     */
    updateSiteSelector() {
        const sitesData = Sites.getData();
        const selector = document.getElementById('pix-site-selector');
        selector.innerHTML = '<option value="">-- Selecione um Site --</option>';
        sitesData.forEach(site => {
            selector.innerHTML += `<option value="${site.id}">${site.name} (${site.domain})</option>`;
        });
        
        // Auto-selecionar para usuário de site
        const currentUser = Auth.getCurrentUser();
        if (currentUser && currentUser.site_id && !currentUser.is_super_admin) {
            selector.value = currentUser.site_id;
            selector.disabled = true;
            this.currentSiteId = currentUser.site_id;
            
            const site = Sites.getById(currentUser.site_id);
            const siteName = document.getElementById('pix-site-name');
            if (siteName && site) {
                siteName.textContent = `${site.name} (${site.domain})`;
            }
            
            document.getElementById('pix-select-alert')?.classList.add('hidden');
            document.getElementById('pix-config-form')?.classList.remove('hidden');
            document.getElementById('pix-test-section')?.classList.remove('hidden');
            this.loadConfig(currentUser.site_id);
        }
    },
    
    /**
     * Handler do change no seletor de site
     */
    async onSiteChange(siteId) {
        this.currentSiteId = siteId;
        
        if (!siteId) {
            document.getElementById('pix-select-alert')?.classList.remove('hidden');
            document.getElementById('pix-config-form')?.classList.add('hidden');
            document.getElementById('pix-test-section')?.classList.add('hidden');
            return;
        }
        
        document.getElementById('pix-select-alert')?.classList.add('hidden');
        document.getElementById('pix-config-form')?.classList.remove('hidden');
        document.getElementById('pix-test-section')?.classList.remove('hidden');
        
        // Nome do site
        const site = Sites.getById(siteId);
        const siteNameEl = document.getElementById('pix-site-name');
        if (siteNameEl) {
            siteNameEl.textContent = site ? `${site.name} (${site.domain})` : '-';
        }
        
        await this.loadConfig(siteId);
    },
    
    /**
     * Carrega configuração PIX de um site
     */
    async loadConfig(siteId) {
        try {
            const data = await Api.get(`pix-config&site_id=${siteId}`);
            
            if (data.status === 'success' && data.data) {
                document.getElementById('pix-state').value = data.data.state || '';
                document.getElementById('pix-key').value = data.data.pix_key || '';
                document.getElementById('pix-key-type').value = data.data.pix_key_type || 'random';
                document.getElementById('pix-receiver-name').value = data.data.receiver_name || 'PAGAMENTO';
                document.getElementById('pix-receiver-city').value = data.data.receiver_city || 'SAO PAULO';
            } else {
                // Limpar formulário se não há config
                document.getElementById('pix-state').value = '';
                document.getElementById('pix-key').value = '';
                document.getElementById('pix-key-type').value = 'random';
                document.getElementById('pix-receiver-name').value = 'PAGAMENTO';
                document.getElementById('pix-receiver-city').value = 'SAO PAULO';
            }
        } catch (error) {
            console.error('PIX config error:', error);
        }
    },
    
    /**
     * Salva configuração PIX
     */
    async saveConfig(e) {
        e.preventDefault();
        
        if (!this.currentSiteId) {
            alert('Selecione um site primeiro');
            return;
        }
        
        const payload = {
            state: document.getElementById('pix-state').value,
            pix_key: document.getElementById('pix-key').value,
            pix_key_type: document.getElementById('pix-key-type').value,
            receiver_name: document.getElementById('pix-receiver-name').value,
            receiver_city: document.getElementById('pix-receiver-city').value
        };
        
        try {
            const data = await Api.post(`pix-config&site_id=${this.currentSiteId}`, payload);
            
            if (data.status === 'success') {
                const status = document.getElementById('pix-save-status');
                if (status) {
                    status.classList.remove('hidden');
                    setTimeout(() => status.classList.add('hidden'), 3000);
                }
            } else {
                alert('Erro ao salvar: ' + (data.message || 'Erro desconhecido'));
            }
        } catch (error) {
            alert('Erro ao salvar configuração PIX');
            console.error(error);
        }
    },
    
    /**
     * Carrega histórico de alterações PIX
     */
    async loadHistory() {
        try {
            const data = await Api.get(`pix-history&site_id=${App.currentSiteId || ''}`);
            
            if (data.status === 'success') {
                const sitesData = Sites.getData();
                const tbody = document.getElementById('pix-history-body');
                if (!tbody) return;
                
                tbody.innerHTML = data.data.map(h => {
                    const time = h.created_at ? new Date(h.created_at).toLocaleString('pt-BR') : '-';
                    const site = sitesData.find(s => s.id == h.site_id);
                    
                    return `
                        <tr>
                            <td><small>${time}</small></td>
                            <td>${site?.name || 'Site #' + h.site_id}</td>
                            <td><span class="badge ${h.change_type === 'create' ? 'bg-success' : 'bg-warning'}">${h.change_type}</span></td>
                            <td><code>${h.old_pix_key || '-'}</code></td>
                            <td><code>${h.new_pix_key || '-'}</code></td>
                            <td>${h.changed_by_user || '-'}</td>
                            <td><small>${h.changed_by_ip || '-'}</small></td>
                        </tr>
                    `;
                }).join('') || '<tr><td colspan="7" class="text-center">Nenhum histórico</td></tr>';
            }
        } catch (error) {
            console.error('PIX History error:', error);
        }
    },
    
    /**
     * Gera código PIX EMV
     */
    generateCode(pixKey, receiverName, receiverCity, amount, description = '') {
        // Formatar valores conforme padrão EMV
        receiverName = receiverName.toUpperCase().substring(0, 25).normalize('NFD').replace(/[\u0300-\u036f]/g, '');
        receiverCity = receiverCity.toUpperCase().substring(0, 15).normalize('NFD').replace(/[\u0300-\u036f]/g, '');
        
        const merchantCategoryCode = '0000';
        const transactionCurrency = '986'; // BRL
        const countryCode = 'BR';
        
        // Função TLV
        const tlv = (id, value) => {
            const len = value.length.toString().padStart(2, '0');
            return id + len + value;
        };
        
        // Merchant Account Info (ID 26) - PIX
        let merchantAccountInfo = tlv('00', 'br.gov.bcb.pix');
        merchantAccountInfo += tlv('01', pixKey);
        if (description) {
            merchantAccountInfo += tlv('02', description.substring(0, 50));
        }
        
        // Montar payload
        let payload = '';
        payload += tlv('00', '01'); // Payload Format Indicator
        payload += tlv('26', merchantAccountInfo); // Merchant Account Info
        payload += tlv('52', merchantCategoryCode);
        payload += tlv('53', transactionCurrency);
        
        if (amount > 0) {
            payload += tlv('54', amount.toFixed(2));
        }
        
        payload += tlv('58', countryCode);
        payload += tlv('59', receiverName);
        payload += tlv('60', receiverCity);
        payload += tlv('62', tlv('05', '***')); // Additional Data - Reference Label
        
        // CRC16 placeholder
        payload += '6304';
        
        // Calcular CRC16
        const crc = this.crc16(payload);
        payload = payload.slice(0, -4) + '6304' + crc;
        
        return payload;
    },
    
    /**
     * Calcula CRC16 CCITT-FALSE
     */
    crc16(str) {
        let crc = 0xFFFF;
        for (let i = 0; i < str.length; i++) {
            crc ^= str.charCodeAt(i) << 8;
            for (let j = 0; j < 8; j++) {
                if (crc & 0x8000) {
                    crc = (crc << 1) ^ 0x1021;
                } else {
                    crc <<= 1;
                }
            }
        }
        return (crc & 0xFFFF).toString(16).toUpperCase().padStart(4, '0');
    },
    
    /**
     * Renderiza QR Code visual
     */
    renderQRCode(containerId, data) {
        const container = document.getElementById(containerId);
        container.innerHTML = '';
        
        const qr = qrcode(0, 'M');
        qr.addData(data);
        qr.make();
        
        container.innerHTML = qr.createImgTag(4, 8);
    },
    
    /**
     * Gera QR Code de teste na página de config
     */
    generateTestQrCode() {
        const pixKey = document.getElementById('pix-key').value;
        const receiverName = document.getElementById('pix-receiver-name').value || 'PAGAMENTO';
        const receiverCity = document.getElementById('pix-receiver-city').value || 'SAO PAULO';
        const amount = parseFloat(document.getElementById('pix-test-value').value) || 1.00;
        const description = document.getElementById('pix-test-description').value || '';
        
        if (!pixKey) {
            alert('Configure a chave PIX primeiro');
            return;
        }
        
        const pixCode = this.generateCode(pixKey, receiverName, receiverCity, amount, description);
        
        this.renderQRCode('pix-test-qrcode', pixCode);
        document.getElementById('pix-test-code').value = pixCode;
        document.getElementById('pix-test-value-display').textContent = Format.brl(amount);
        document.getElementById('pix-test-result').classList.remove('hidden');
    },
    
    /**
     * Copia código PIX para clipboard
     */
    copyCode() {
        const code = document.getElementById('pix-test-code');
        code.select();
        document.execCommand('copy');
        alert('Código PIX copiado!');
    },
    
    /**
     * Gera QR Code de teste no modal
     */
    generateModalTestQrCode() {
        const pixKey = document.getElementById('edit-pix-key').value;
        const receiverName = document.getElementById('edit-pix-receiver-name').value || 'PAGAMENTO';
        const receiverCity = document.getElementById('edit-pix-receiver-city').value || 'SAO PAULO';
        const amount = parseFloat(document.getElementById('modal-pix-test-value').value) || 1.00;
        const description = document.getElementById('modal-pix-test-description').value || '';
        
        if (!pixKey) {
            alert('Configure a chave PIX primeiro');
            return;
        }
        
        const pixCode = this.generateCode(pixKey, receiverName, receiverCity, amount, description);
        
        this.renderQRCode('modal-pix-test-qrcode', pixCode);
        document.getElementById('modal-pix-test-code').value = pixCode;
        document.getElementById('modal-pix-test-value-display').textContent = Format.brl(amount);
        document.getElementById('modal-pix-test-result').classList.remove('hidden');
    },
    
    /**
     * Copia código PIX do modal
     */
    copyModalCode() {
        const code = document.getElementById('modal-pix-test-code');
        code.select();
        document.execCommand('copy');
        alert('Código PIX copiado!');
    }
};

// Event listeners
document.addEventListener('DOMContentLoaded', () => {
    // Seletor de site PIX
    const pixSelector = document.getElementById('pix-site-selector');
    if (pixSelector) {
        pixSelector.addEventListener('change', (e) => PIX.onSiteChange(e.target.value));
    }
    
    // Form config PIX
    const pixForm = document.getElementById('pix-config-form');
    if (pixForm) {
        pixForm.addEventListener('submit', (e) => PIX.saveConfig(e));
    }
});
