File: /home/onlyfibr/public_html/cadastro/admin/exportar_precadastros_pdf.php
<?php
// HABILITAR ERROS PARA DEBUG - REMOVER/COMENTAR EM PRODUÇÃO!
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// ---------------------------------------------------------
// Defina um limite de memória maior, DomPDF pode precisar
ini_set('memory_limit', '256M');
session_start();
require_once '../config.php'; // Para $pdo
require_once '../vendor/autoload.php'; // Carrega o Autoloader do Composer (incluindo Dompdf)
use Dompdf\Dompdf;
use Dompdf\Options;
// CRÍTICO: ADICIONE AQUI SUA LÓGICA DE AUTENTICAÇÃO !!!
// Exemplo MUITO BÁSICO (NÃO SEGURO PARA PRODUÇÃO):
/*
if (!isset($_SESSION['usuario_logado']) || $_SESSION['tipo_usuario'] !== 'admin') {
http_response_code(403); // Forbidden
echo "Acesso negado.";
exit;
}
*/
// --- Busca dos Dados ---
$lista_precadastros = [];
$erro_busca_db = '';
if ($pdo) {
try {
// Busca todos os dados relevantes para o PDF
$sql = "SELECT id, nome, email, celular, cpf_cnpj, cidade, estado, status_processamento, data_envio
FROM precadastros
ORDER BY data_envio DESC, id DESC";
$stmt = $pdo->query($sql);
$lista_precadastros = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (\PDOException $e) {
$erro_busca_db = "Erro ao buscar dados para PDF: " . $e->getMessage();
error_log("Erro DB PDF Export: " . $e->getMessage());
}
} else {
$erro_busca_db = "Erro crítico: Conexão com banco de dados falhou.";
}
// --- Geração do HTML para o PDF ---
$html = '<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<title>Relatório de Pré-Cadastros</title>
<style>
body { font-family: sans-serif; font-size: 10px; }
table { width: 100%; border-collapse: collapse; margin-bottom: 15px; }
th, td { border: 1px solid #ddd; padding: 6px; text-align: left; }
th { background-color: #f2f2f2; font-weight: bold; }
h1 { text-align: center; margin-bottom: 20px; font-size: 16px; }
.status-pendente { background-color: #fff3cd; }
.status-processado_sucesso { background-color: #d1e7dd; }
.status-processado_erro { background-color: #f8d7da; }
.status-contatado { background-color: #cfe2ff; }
.status-cancelado { background-color: #e2e3e5; }
.status-instalado { background-color: #cff4fc; }
.footer { text-align: center; font-size: 8px; color: #777; position: fixed; bottom: 0; width:100%; }
@page { margin: 20mm 15mm; } /* Margens da página */
</style>
</head>
<body>
<h1>Relatório de Pré-Cadastros - ' . date('d/m/Y H:i') . '</h1>';
if (!empty($lista_precadastros)) {
$html .= '<table>
<thead>
<tr>
<th>ID</th>
<th>Nome</th>
<th>Contato</th>
<th>CPF/CNPJ</th>
<th>Cidade/UF</th>
<th>Status</th>
<th>Data</th>
</tr>
</thead>
<tbody>';
foreach ($lista_precadastros as $cadastro) {
$html .= '<tr>
<td>' . htmlspecialchars($cadastro['id']) . '</td>
<td>' . htmlspecialchars($cadastro['nome']) . '</td>
<td>' . htmlspecialchars($cadastro['email']) . '<br>' . htmlspecialchars($cadastro['celular']) . '</td>
<td>' . htmlspecialchars($cadastro['cpf_cnpj']) . '</td>
<td>' . htmlspecialchars($cadastro['cidade'] . '/' . $cadastro['estado']) . '</td>
<td class="status-' . htmlspecialchars($cadastro['status_processamento']) . '">' . ucwords(str_replace('_', ' ', htmlspecialchars($cadastro['status_processamento']))) . '</td>
<td>' . (isset($cadastro['data_envio']) ? htmlspecialchars(date('d/m/Y H:i', strtotime($cadastro['data_envio']))) : 'N/A') . '</td>
</tr>';
}
$html .= '</tbody></table>';
} else {
$html .= '<p style="text-align: center;">Nenhum pré-cadastro encontrado.</p>';
}
if ($erro_busca_db) {
$html .= '<p style="color: red; text-align: center;">Erro ao gerar relatório: ' . htmlspecialchars($erro_busca_db) . '</p>';
}
$html .= '<div class="footer">Relatório gerado pelo '.htmlspecialchars(NOME_PORTAL).' | © ' . date('Y') . ' '.htmlspecialchars(NOME_EMPRESA).'</div>';
$html .= '</body></html>';
// --- Instanciar e Usar Dompdf ---
$options = new Options();
$options->set('isHtml5ParserEnabled', true);
$options->set('isRemoteEnabled', false); // Desabilita acesso a URLs externas por segurança
$options->set('defaultFont', 'sans-serif');
$dompdf = new Dompdf($options);
$dompdf->loadHtml($html);
// (Opcional) Definir tamanho do papel e orientação (A4 retrato é o padrão)
$dompdf->setPaper('A4', 'portrait'); // ou 'landscape' para paisagem
// Renderizar o HTML como PDF
$dompdf->render();
// Definir nome do arquivo para download
$filename = "precadastros_" . date('Ymd_His') . ".pdf";
// Enviar o PDF para o browser para download
// Use 'attachment' para forçar download, 'inline' para tentar exibir no navegador
$dompdf->stream($filename, ["Attachment" => true]);
exit; // Termina o script após enviar o PDF
?>