// Elements
const loginContainer = document.getElementById('loginContainer');
const dashboardContainer = document.getElementById('dashboardContainer');
const loginForm = document.getElementById('loginForm');
const loginError = document.getElementById('loginError');
const adminEmailDisplay = document.getElementById('adminEmailDisplay');
const logoutBtn = document.getElementById('logoutBtn');

// Navigation
const navItems = document.querySelectorAll('.nav-item');
const tabContents = document.querySelectorAll('.tab-content');

// Login
loginForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const email = document.getElementById('adminEmail').value;
    const password = document.getElementById('adminPassword').value;
    
    loginError.classList.remove('show');
    
    try {
        const response = await fetch('../backend/admin_login.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ email, password })
        });
        
        console.log('Response status:', response.status);
        const text = await response.text();
        console.log('Response text:', text);
        
        let data;
        try {
            data = JSON.parse(text);
        } catch (e) {
            console.error('Erro ao parsear JSON:', e);
            loginError.textContent = '❌ Erro no servidor. Resposta: ' + text.substring(0, 100);
            loginError.classList.add('show');
            return;
        }
        
        if (data.success) {
            localStorage.setItem('adminSession', 'true');
            localStorage.setItem('adminEmail', data.email);
            showDashboard();
        } else {
            loginError.textContent = '❌ ' + data.message;
            loginError.classList.add('show');
        }
    } catch (error) {
        console.error('Erro completo:', error);
        loginError.textContent = '❌ Erro ao conectar: ' + error.message;
        loginError.classList.add('show');
    }
});

// Logout
logoutBtn.addEventListener('click', () => {
    localStorage.removeItem('adminSession');
    location.reload();
});

// Check session on load
if (localStorage.getItem('adminSession') === 'true') {
    showDashboard();
}

function showDashboard() {
    loginContainer.style.display = 'none';
    dashboardContainer.style.display = 'flex';
    const email = localStorage.getItem('adminEmail') || 'Admin';
    adminEmailDisplay.textContent = email;
    loadUsers();
    loadDeposits();
    loadGameHistory();
    loadProbabilities();
}

// Navigation
navItems.forEach(item => {
    item.addEventListener('click', (e) => {
        e.preventDefault();
        const tab = item.dataset.tab;
        
        navItems.forEach(nav => nav.classList.remove('active'));
        item.classList.add('active');
        
        tabContents.forEach(content => content.classList.remove('active'));
        document.getElementById(`tab-${tab}`).classList.add('active');
        
        // Reload data when switching tabs
        if (tab === 'usuarios') loadUsers();
        if (tab === 'movimentacoes') loadDeposits();
        if (tab === 'historico') loadGameHistory();
    });
});

// Load Users
async function loadUsers() {
    console.log('Carregando usuários...');
    try {
        const response = await fetch('../backend/admin_get_users.php');
        console.log('Response status:', response.status);
        
        const text = await response.text();
        console.log('Response text:', text);
        
        const data = JSON.parse(text);
        console.log('Data parsed:', data);
        
        if (data.success) {
            const tbody = document.getElementById('usersTableBody');
            const totalUsers = document.getElementById('totalUsers');
            const totalBalance = document.getElementById('totalBalance');
            
            totalUsers.textContent = data.users.length;
            
            const total = data.users.reduce((sum, user) => sum + parseFloat(user.balance), 0);
            totalBalance.textContent = `R$ ${total.toFixed(2).replace('.', ',')}`;
            
            if (data.users.length === 0) {
                tbody.innerHTML = '<tr><td colspan="6" class="loading">Nenhum usuário encontrado</td></tr>';
                return;
            }
            
            tbody.innerHTML = data.users.map(user => `
                <tr>
                    <td>#${user.id}</td>
                    <td>${user.name}</td>
                    <td>${user.whatsapp || 'Não informado'}</td>
                    <td>R$ ${parseFloat(user.balance).toFixed(2).replace('.', ',')}</td>
                    <td>${new Date(user.created_at).toLocaleString('pt-BR')}</td>
                    <td>
                        <button class="btn-edit" onclick="openEditBalance(${user.id}, '${user.name}', ${user.balance})">
                            ✏️ Editar
                        </button>
                    </td>
                </tr>
            `).join('');
        }
    } catch (error) {
        console.error('Erro ao carregar usuários:', error);
        const tbody = document.getElementById('usersTableBody');
        tbody.innerHTML = `<tr><td colspan="6" class="loading">Erro: ${error.message}</td></tr>`;
    }
}

// Load Deposits
async function loadDeposits() {
    try {
        const response = await fetch('../backend/admin_get_deposits.php');
        const data = await response.json();
        
        if (data.success) {
            const tbody = document.getElementById('depositsTableBody');
            const totalDeposits = document.getElementById('totalDeposits');
            const totalTransactions = document.getElementById('totalTransactions');
            
            totalTransactions.textContent = data.deposits.length;
            
            const total = data.deposits.reduce((sum, dep) => sum + parseFloat(dep.amount), 0);
            totalDeposits.textContent = `R$ ${total.toFixed(2).replace('.', ',')}`;
            
            if (data.deposits.length === 0) {
                tbody.innerHTML = '<tr><td colspan="5" class="loading">Nenhum depósito encontrado</td></tr>';
                return;
            }
            
            tbody.innerHTML = data.deposits.map(dep => {
                const statusText = (dep.status === 'completed' || dep.status === 'approved') ? 'Completo' : 'Pendente';
                const statusClass = (dep.status === 'completed' || dep.status === 'approved') ? 'completed' : 'pending';
                
                return `
                    <tr>
                        <td>#${dep.id}</td>
                        <td>${dep.user_name}</td>
                        <td>R$ ${parseFloat(dep.amount).toFixed(2).replace('.', ',')}</td>
                        <td><span class="status-badge status-${statusClass}">${statusText}</span></td>
                        <td>${new Date(dep.created_at).toLocaleString('pt-BR')}</td>
                    </tr>
                `;
            }).join('');
        }
    } catch (error) {
        console.error('Erro ao carregar depósitos:', error);
    }
}

// Load Game History
async function loadGameHistory() {
    try {
        const response = await fetch('../backend/admin_get_games.php');
        const data = await response.json();
        
        if (data.success) {
            const tbody = document.getElementById('gamesTableBody');
            const totalGames = document.getElementById('totalGames');
            const avgMultiplier = document.getElementById('avgMultiplier');
            
            totalGames.textContent = data.games.length;
            
            if (data.games.length > 0) {
                const avg = data.games.reduce((sum, game) => sum + parseFloat(game.multiplier), 0) / data.games.length;
                avgMultiplier.textContent = `${avg.toFixed(2)}x`;
            }
            
            if (data.games.length === 0) {
                tbody.innerHTML = '<tr><td colspan="6" class="loading">Nenhuma jogada encontrada</td></tr>';
                return;
            }
            
            tbody.innerHTML = data.games.map(game => {
                const winAmount = parseFloat(game.win_amount || 0);
                const betAmount = parseFloat(game.bet_amount || 0);
                const profit = winAmount - betAmount;
                const profitClass = profit > 0 ? 'profit-positive' : 'profit-negative';
                const profitSign = profit > 0 ? '+' : '';
                const resultText = game.result === 'cashout' ? 'Cashout' : game.result === 'win' ? 'Ganhou' : 'Perdeu';
                
                return `
                    <tr>
                        <td>#${game.id}</td>
                        <td>${game.user_name || 'Desconhecido'}</td>
                        <td>R$ ${betAmount.toFixed(2).replace('.', ',')}</td>
                        <td>${parseFloat(game.multiplier).toFixed(2)}x</td>
                        <td class="${profitClass}">${profitSign}R$ ${Math.abs(profit).toFixed(2).replace('.', ',')} (${resultText})</td>
                        <td>${new Date(game.created_at).toLocaleString('pt-BR')}</td>
                    </tr>
                `;
            }).join('');
        }
    } catch (error) {
        console.error('Erro ao carregar histórico:', error);
    }
}

// Manipulation - Probability Sliders
const sliders = [
    document.getElementById('range1'),
    document.getElementById('range2'),
    document.getElementById('range3'),
    document.getElementById('range4')
];

const values = [
    document.getElementById('value1'),
    document.getElementById('value2'),
    document.getElementById('value3'),
    document.getElementById('value4')
];

const totalFill = document.getElementById('totalFill');
const totalPercentage = document.getElementById('totalPercentage');
const statusBadge = document.getElementById('statusBadge');
const saveProbabilities = document.getElementById('saveProbabilities');

sliders.forEach((slider, index) => {
    slider.addEventListener('input', () => {
        values[index].textContent = slider.value;
        updateTotal();
    });
});

function updateTotal() {
    const total = sliders.reduce((sum, slider) => sum + parseInt(slider.value), 0);
    totalPercentage.textContent = total;
    
    const percentage = Math.min(total, 100);
    totalFill.style.width = `${percentage}%`;
    
    if (total === 100) {
        totalFill.classList.remove('invalid');
        statusBadge.textContent = '✓ Válido';
        statusBadge.className = 'status-badge status-completed';
        saveProbabilities.disabled = false;
    } else {
        totalFill.classList.add('invalid');
        statusBadge.textContent = '✗ Inválido';
        statusBadge.className = 'status-badge status-pending';
        saveProbabilities.disabled = true;
    }
}

// Load current probabilities
async function loadProbabilities() {
    try {
        const response = await fetch('../backend/admin_get_probabilities.php');
        const data = await response.json();
        
        if (data.success && data.probabilities) {
            sliders[0].value = data.probabilities.range_0_1_5;
            sliders[1].value = data.probabilities.range_1_5_3;
            sliders[2].value = data.probabilities.range_3_6;
            sliders[3].value = data.probabilities.range_6_15;
            
            sliders.forEach((slider, index) => {
                values[index].textContent = slider.value;
            });
            
            updateTotal();
        }
    } catch (error) {
        console.error('Erro ao carregar probabilidades:', error);
    }
}

// Save probabilities
saveProbabilities.addEventListener('click', async () => {
    const probabilities = {
        range_0_1_5: parseInt(sliders[0].value),
        range_1_5_3: parseInt(sliders[1].value),
        range_3_6: parseInt(sliders[2].value),
        range_6_15: parseInt(sliders[3].value)
    };
    
    try {
        const response = await fetch('../backend/admin_save_probabilities.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(probabilities)
        });
        
        const data = await response.json();
        
        if (data.success) {
            alert('✓ Probabilidades salvas com sucesso!');
        } else {
            alert('✗ Erro ao salvar: ' + data.message);
        }
    } catch (error) {
        console.error('Erro ao salvar probabilidades:', error);
        alert('✗ Erro ao salvar probabilidades');
    }
});

// Modal de Editar Saldo
const editBalanceModal = document.getElementById('editBalanceModal');
const closeEditModal = document.getElementById('closeEditModal');
const cancelEditBtn = document.getElementById('cancelEditBtn');
const confirmEditBtn = document.getElementById('confirmEditBtn');
const newBalanceInput = document.getElementById('newBalance');

let currentEditUserId = null;

function openEditBalance(userId, userName, currentBalance) {
    currentEditUserId = userId;
    document.getElementById('editUserId').textContent = userId;
    document.getElementById('editUserName').textContent = userName;
    document.getElementById('editCurrentBalance').textContent = `R$ ${parseFloat(currentBalance).toFixed(2).replace('.', ',')}`;
    newBalanceInput.value = parseFloat(currentBalance).toFixed(2);
    editBalanceModal.classList.add('show');
}

function closeEditBalanceModal() {
    editBalanceModal.classList.remove('show');
    currentEditUserId = null;
    newBalanceInput.value = '';
}

closeEditModal.addEventListener('click', closeEditBalanceModal);
cancelEditBtn.addEventListener('click', closeEditBalanceModal);

editBalanceModal.addEventListener('click', (e) => {
    if (e.target === editBalanceModal) {
        closeEditBalanceModal();
    }
});

confirmEditBtn.addEventListener('click', async () => {
    const newBalance = parseFloat(newBalanceInput.value);
    
    if (isNaN(newBalance) || newBalance < 0) {
        alert('Por favor, insira um valor válido');
        return;
    }
    
    if (!confirm(`Confirma alterar o saldo para R$ ${newBalance.toFixed(2).replace('.', ',')}?`)) {
        return;
    }
    
    try {
        confirmEditBtn.disabled = true;
        confirmEditBtn.textContent = 'Salvando...';
        
        const response = await fetch('../backend/admin_update_balance.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                user_id: currentEditUserId,
                new_balance: newBalance
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            alert('✓ Saldo atualizado com sucesso!');
            closeEditBalanceModal();
            loadUsers(); // Recarregar lista
        } else {
            alert('✗ Erro: ' + data.message);
        }
    } catch (error) {
        console.error('Erro ao atualizar saldo:', error);
        alert('✗ Erro ao atualizar saldo');
    } finally {
        confirmEditBtn.disabled = false;
        confirmEditBtn.textContent = 'Salvar';
    }
});

// Initialize
updateTotal();
