// /telefonia/js/webphone.js

const API_URL = 'api/webphone_api.php';

let sipSession = null;
let userAgent = null;

const numberInput = document.getElementById('numberInput');
const connectionLed = document.getElementById('connectionLed');
const connectionText = document.getElementById('connectionText');
const balanceEl = document.getElementById('balance');
const callBtn = document.getElementById('callBtn');
const hangupBtn = document.getElementById('hangupBtn');
const callInfo = document.getElementById('callInfo');
const timerEl = document.getElementById('timer');
const callStatus = document.getElementById('callStatus');
const tenantInfo = document.getElementById('tenantInfo');

let currentNumber = '';
let callStartTime = null;
let timerInterval = null;
let isInCall = false;
let currentCallId = null;

async function apiRequest(action, method = 'GET', data = null) {
    const url = `${API_URL}?acao=${action}`;
    const options = {
        method: method,
        credentials: 'same-origin',
        headers: { 'Content-Type': 'application/json' }
    };
    
    if (data) options.body = JSON.stringify(data);
    
    try {
        const response = await fetch(url, options);
        const text = await response.text();
        try {
            return JSON.parse(text);
        } catch (e) {
            console.error('Resposta não é JSON:', text.substring(0, 200));
            throw new Error('Resposta inválida do servidor');
        }
    } catch (error) {
        console.error('Erro na API:', error);
        throw error;
    }
}

async function init() {
    try {
        updateConnectionStatus(false, 'Conectando...');
        
        const config = await apiRequest('config');
        
        if (!config.success) {
            throw new Error(config.error || 'Falha ao carregar configurações');
        }
        
        tenantInfo.innerHTML = `
            <i class="fas fa-user"></i> ${config.config.nome_usuario} |
            <i class="fas fa-phone"></i> ${config.config.bina} |
            <i class="fas fa-qrcode"></i> Ramal: ${config.config.ramal}
        `;
        
        const saldoFormatado = 'R$ ' + (config.config.saldo_raw || 0).toFixed(2).replace('.', ',');
        balanceEl.textContent = saldoFormatado;
        
        updateConnectionStatus(true, 'Conectado');
        callBtn.disabled = false;
        
        loadHistory();
        console.log('✅ Webphone inicializado');
        
    } catch (error) {
        console.error('Erro na inicialização:', error);
        updateConnectionStatus(false, 'Erro');
        tenantInfo.innerHTML = `<i class="fas fa-exclamation-triangle"></i> Erro ao carregar`;
    }
}

function updateConnectionStatus(connected, text) {
    if (connected) {
        connectionLed.className = 'led connected';
        connectionText.textContent = text || 'Conectado';
    } else {
        connectionLed.className = 'led';
        connectionText.textContent = text || 'Desconectado';
    }
}

function addDigit(digit) {
    if (isInCall) return;
    currentNumber += digit;
    numberInput.value = currentNumber;
}

function formatNumber(number) {
    let cleaned = number.replace(/\D/g, '');
    if (number.startsWith('+')) return number;
    if (cleaned.length === 10 || cleaned.length === 11) return '+55' + cleaned;
    return '+' + cleaned;
}

async function makeCall() {
    if (!currentNumber) {
        alert('Digite um número');
        return;
    }
    
    const formattedNumber = formatNumber(currentNumber);
    currentCallId = 'call_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    
    try {
        await apiRequest('registrar', 'POST', {
            numero_destino: formattedNumber,
            duracao: 0,
            status: 'iniciada',
            call_id: currentCallId
        });
        
        isInCall = true;
        callStartTime = Date.now();
        callInfo.classList.add('active');
        callStatus.textContent = 'Chamando...';
        updateConnectionStatus(true, 'Chamando');
        connectionLed.className = 'led calling';
        callBtn.disabled = true;
        hangupBtn.disabled = false;
        
        startTimer();
        simulateCall(formattedNumber);
        
    } catch (error) {
        console.error('Erro ao fazer chamada:', error);
        alert('Erro ao fazer chamada: ' + error.message);
        resetCall();
    }
}

function simulateCall(number) {
    setTimeout(() => {
        if (isInCall) {
            callStatus.textContent = 'Em andamento';
            updateConnectionStatus(true, 'Em chamada');
            connectionLed.className = 'led in-call';
        }
    }, 3000);
    
    setTimeout(() => {
        if (isInCall) hangup();
    }, 10000);
}

function startTimer() {
    if (timerInterval) clearInterval(timerInterval);
    
    timerInterval = setInterval(() => {
        if (!isInCall || !callStartTime) return;
        
        const duration = Math.floor((Date.now() - callStartTime) / 1000);
        const minutes = Math.floor(duration / 60);
        const seconds = duration % 60;
        timerEl.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    }, 1000);
}

async function hangup() {
    if (!isInCall || !callStartTime) {
        resetCall();
        return;
    }
    
    try {
        const duration = Math.floor((Date.now() - callStartTime) / 1000);
        
        const result = await apiRequest('registrar', 'POST', {
            numero_destino: formatNumber(currentNumber),
            duracao: duration,
            status: duration > 2 ? 'realizada' : 'nao_atendida',
            call_id: currentCallId
        });
        
        if (result.success) {
            const saldo = await apiRequest('saldo');
            if (saldo.success) {
                balanceEl.textContent = 'R$ ' + (saldo.saldo_raw || 0).toFixed(2).replace('.', ',');
            }
        }
        
        loadHistory();
        
    } catch (error) {
        console.error('Erro ao registrar chamada:', error);
    } finally {
        resetCall();
    }
}

function resetCall() {
    isInCall = false;
    callStartTime = null;
    currentNumber = '';
    numberInput.value = '';
    currentCallId = null;
    
    callInfo.classList.remove('active');
    callBtn.disabled = false;
    hangupBtn.disabled = true;
    timerEl.textContent = '00:00';
    
    updateConnectionStatus(true, 'Conectado');
    connectionLed.className = 'led connected';
    
    if (timerInterval) {
        clearInterval(timerInterval);
        timerInterval = null;
    }
}

async function loadHistory() {
    try {
        const data = await apiRequest('historico', 'GET');
        const historyList = document.getElementById('historyList');
        
        if (!data.success || !data.chamadas || data.chamadas.length === 0) {
            historyList.innerHTML = '<div class="loading">Nenhuma chamada recente</div>';
            return;
        }
        
        let html = '';
        data.chamadas.slice(0, 10).forEach(call => {
            const date = new Date(call.data_hora_inicio);
            const formattedDate = date.toLocaleDateString('pt-BR') + ' ' + date.toLocaleTimeString('pt-BR');
            
            let statusClass = 'missed';
            let statusText = call.status;
            
            if (call.status === 'realizada') {
                statusClass = 'answered';
                statusText = 'Atendida';
            } else if (call.status === 'nao_atendida') {
                statusText = 'Não atendida';
            } else if (call.status === 'ocupado') {
                statusText = 'Ocupado';
            } else if (call.status === 'falhada') {
                statusText = 'Falha';
            }
            
            html += `
                <div class="history-item">
                    <div>
                        <div class="number">${call.numero_destino}</div>
                        <div class="date">${formattedDate}</div>
                    </div>
                    <div>
                        <span class="duration">${call.duracao}s</span>
                        <span class="status-badge ${statusClass}">${statusText}</span>
                    </div>
                </div>
            `;
        });
        
        historyList.innerHTML = html;
        
    } catch (error) {
        console.error('Erro ao carregar histórico:', error);
        document.getElementById('historyList').innerHTML = '<div class="loading">Erro ao carregar histórico</div>';
    }
}

document.addEventListener('keydown', (e) => {
    if (isInCall) return;
    
    if (e.key >= '0' && e.key <= '9') {
        addDigit(e.key);
    } else if (e.key === '*') {
        addDigit('*');
    } else if (e.key === '#') {
        addDigit('#');
    } else if (e.key === 'Backspace') {
        currentNumber = currentNumber.slice(0, -1);
        numberInput.value = currentNumber;
    } else if (e.key === 'Enter') {
        makeCall();
    }
});

window.onload = init;