<?php include('./includes/header.php'); ?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Painel de Mensagens - Launcher</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        .message-card {
            transition: all 0.3s ease;
            margin-bottom: 15px;
        }
        .message-card:hover {
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .device-info {
            font-size: 0.85rem;
            color: #6c757d;
        }
        .timestamp {
            font-size: 0.8rem;
            color: #6c757d;
        }
        .unread {
            border-left: 4px solid #0d6efd;
        }
        #refresh-btn {
            cursor: pointer;
        }
        .loading-spinner {
            display: none;
        }
        .btn-clear-all {
            margin-left: 10px;
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="h3">
                <i class="bi bi-chat-left-text"></i> Mensagens Recebidas
            </h1>
            <div>
                <span id="refresh-btn" class="me-2" title="Atualizar">
                    <i class="bi bi-arrow-clockwise"></i>
                </span>
                <span class="loading-spinner text-primary">
                    <i class="bi bi-arrow-repeat"></i> Carregando...
                </span>
            </div>
        </div>

        <div class="row mb-3">
            <div class="col-md-6">
                <div class="input-group">
                    <input type="text" id="search-input" class="form-control" placeholder="Pesquisar mensagens...">
                    <button class="btn btn-outline-secondary" type="button" id="search-btn">
                        <i class="bi bi-search"></i>
                    </button>
                </div>
            </div>
            <div class="col-md-6 text-end">
                <div class="btn-group">
                    <button class="btn btn-outline-primary btn-sm" id="filter-all">Todas</button>
                    <button class="btn btn-outline-primary btn-sm" id="filter-unread">Não lidas</button>
                    <button id="clear-all-btn" class="btn btn-outline-danger btn-sm btn-clear-all" title="Limpar todas as mensagens">
                        <i class="bi bi-trash"></i> Limpar Tudo
                    </button>
                </div>
            </div>
        </div>

        <div id="messages-container">
            <!-- As mensagens serão carregadas aqui via JavaScript -->
        </div>

        <div class="text-center mt-4" id="no-messages" style="display: none;">
            <div class="alert alert-info">
                Nenhuma mensagem encontrada.
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Elementos DOM
            const messagesContainer = document.getElementById('messages-container');
            const noMessages = document.getElementById('no-messages');
            const refreshBtn = document.getElementById('refresh-btn');
            const clearAllBtn = document.getElementById('clear-all-btn');
            const loadingSpinner = document.querySelector('.loading-spinner');
            const searchInput = document.getElementById('search-input');
            const searchBtn = document.getElementById('search-btn');
            const filterAll = document.getElementById('filter-all');
            const filterUnread = document.getElementById('filter-unread');

            // Variáveis de estado
            let allMessages = [];
            let currentFilter = 'all';
            let currentSearch = '';

            // Carregar mensagens
            function loadMessages() {
                showLoading(true);
                
                fetch('https://launcher.painelmaster.lol/reports.json')
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Erro ao carregar mensagens');
                        }
                        return response.json();
                    })
                    .then(data => {
                        // Verifica se data.reports existe, caso contrário usa o array diretamente
                        allMessages = Array.isArray(data) ? data : (data.reports || []);
                        renderMessages();
                        showLoading(false);
                    })
                    .catch(error => {
                        console.error('Erro:', error);
                        messagesContainer.innerHTML = `
                            <div class="alert alert-danger">
                                Erro ao carregar mensagens: ${error.message}
                            </div>
                        `;
                        showLoading(false);
                    });
            }

            // Função para limpar todas as mensagens
            function clearAllMessages() {
                if (allMessages.length === 0) {
                    alert('Não há mensagens para limpar!');
                    return;
                }

                if (confirm('Tem certeza que deseja limpar TODAS as mensagens? Esta ação não pode ser desfeita.')) {
                    showLoading(true);
                    
                    fetch('clear_messages.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        }
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Erro ao limpar mensagens');
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data.success) {
                            allMessages = [];
                            renderMessages();
                            alert(data.message);
                        } else {
                            throw new Error(data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Erro:', error);
                        alert('Erro ao limpar mensagens: ' + error.message);
                    })
                    .finally(() => {
                        showLoading(false);
                    });
                }
            }

            // Renderizar mensagens com filtros
            function renderMessages() {
                let filteredMessages = [...allMessages];
                
                // Aplicar filtro
                if (currentFilter === 'unread') {
                    filteredMessages = filteredMessages.filter(msg => msg.status === 'unread');
                }
                
                // Aplicar busca
                if (currentSearch) {
                    const searchTerm = currentSearch.toLowerCase();
                    filteredMessages = filteredMessages.filter(msg => 
                        msg.message.toLowerCase().includes(searchTerm) ||
                        (msg.device_model && msg.device_model.toLowerCase().includes(searchTerm)) ||
                        (msg.device_id && msg.device_id.toLowerCase().includes(searchTerm))
                    );
                }
                
                // Ordenar por timestamp (mais recente primeiro)
                filteredMessages.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
                
                // Renderizar
                if (filteredMessages.length === 0) {
                    messagesContainer.innerHTML = '';
                    noMessages.style.display = 'block';
                } else {
                    noMessages.style.display = 'none';
                    messagesContainer.innerHTML = filteredMessages.map(msg => `
                        <div class="card message-card ${msg.status === 'unread' ? 'unread' : ''}">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <p class="card-text">${msg.message}</p>
                                        <div class="device-info">
                                            ${msg.device_model || 'Dispositivo desconhecido'} 
                                            (${msg.device_id || 'ID desconhecido'})
                                        </div>
                                    </div>
                                    <div class="timestamp">
                                        ${formatDate(msg.timestamp)}
                                    </div>
                                </div>
                            </div>
                        </div>
                    `).join('');
                }
            }

            // Formatador de data
            function formatDate(timestamp) {
                if (!timestamp) return '';
                const date = new Date(timestamp);
                return date.toLocaleString('pt-BR');
            }

            // Mostrar/ocultar loading
            function showLoading(show) {
                if (show) {
                    loadingSpinner.style.display = 'inline-block';
                    refreshBtn.style.display = 'none';
                    clearAllBtn.disabled = true;
                    filterAll.disabled = true;
                    filterUnread.disabled = true;
                } else {
                    loadingSpinner.style.display = 'none';
                    refreshBtn.style.display = 'inline-block';
                    clearAllBtn.disabled = false;
                    filterAll.disabled = false;
                    filterUnread.disabled = false;
                }
            }

            // Event Listeners
            refreshBtn.addEventListener('click', loadMessages);
            
            clearAllBtn.addEventListener('click', clearAllMessages);
            
            searchBtn.addEventListener('click', () => {
                currentSearch = searchInput.value.trim();
                renderMessages();
            });
            
            searchInput.addEventListener('keyup', (e) => {
                if (e.key === 'Enter') {
                    currentSearch = searchInput.value.trim();
                    renderMessages();
                }
            });
            
            filterAll.addEventListener('click', () => {
                currentFilter = 'all';
                filterAll.classList.add('active');
                filterUnread.classList.remove('active');
                renderMessages();
            });
            
            filterUnread.addEventListener('click', () => {
                currentFilter = 'unread';
                filterUnread.classList.add('active');
                filterAll.classList.remove('active');
                renderMessages();
            });

            // Inicializar
            filterAll.classList.add('active');
            loadMessages();
        });
    </script>
    <?php include('./includes/footer.php'); ?>
</body>
</html>