<?php
session_start();
require_once __DIR__ . '/../config/databaseNexa.php';
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/* =====================================================
FUNÇÕES
===================================================== */
function h($valor)
{
return htmlspecialchars((string)$valor, ENT_QUOTES, 'UTF-8');
}
function normalizarTelefone($telefone)
{
return preg_replace('/[^0-9]/', '', $telefone);
}
if (empty($_SESSION['csrf_visitante'])) {
$_SESSION['csrf_visitante'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_visitante'];
$mensagem = '';
$tipoMensagem = '';
/* =====================================================
MENSAGENS
===================================================== */
if (!empty($_SESSION['flash_visitante'])) {
$mensagem = $_SESSION['flash_visitante']['mensagem'];
$tipoMensagem = $_SESSION['flash_visitante']['tipo'];
unset($_SESSION['flash_visitante']);
}
/* =====================================================
PROCESSAMENTO DOS FORMULÁRIOS
===================================================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (
empty($_POST['csrf']) ||
!hash_equals($csrf, $_POST['csrf'])
) {
die('Token de segurança inválido.');
}
$acao = $_POST['acao'] ?? '';
/* =============================================
CADASTRAR / ATUALIZAR
============================================= */
if ($acao === 'salvar') {
$id = (int)($_POST['id'] ?? 0);
$nome = trim($_POST['nome'] ?? '');
$telefone = normalizarTelefone($_POST['telefone'] ?? '');
$email = trim($_POST['email'] ?? '');
$idUsuario = trim($_POST['id_usuario'] ?? '');
$situacao = $_POST['situacao'] ?? 'ativo';
$idUsuario = ($idUsuario !== '')
? (int)$idUsuario
: null;
if (strlen($telefone) < 8 || strlen($telefone) > 20) {
$_SESSION['flash_visitante'] = [
'mensagem' => 'Informe um telefone válido.',
'tipo' => 'erro'
];
} elseif (
$email !== '' &&
!filter_var($email, FILTER_VALIDATE_EMAIL)
) {
$_SESSION['flash_visitante'] = [
'mensagem' => 'Informe um e-mail válido.',
'tipo' => 'erro'
];
} elseif (!in_array($situacao, ['ativo', 'inativo', 'bloqueado'], true)) {
$_SESSION['flash_visitante'] = [
'mensagem' => 'Situação inválida.',
'tipo' => 'erro'
];
} else {
try {
// Verifica telefone duplicado
$sql = "SELECT id FROM visitante
WHERE telefone = :telefone";
if ($id > 0) {
$sql .= " AND id <> :id";
}
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':telefone', $telefone);
if ($id > 0) {
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
}
$stmt->execute();
if ($stmt->fetch()) {
$_SESSION['flash_visitante'] = [
'mensagem' => 'Já existe um visitante cadastrado com este telefone.',
'tipo' => 'erro'
];
} else {
if ($id > 0) {
// Atualização
$sql = "UPDATE visitante SET
nome = :nome,
telefone = :telefone,
email = :email,
id_usuario = :id_usuario,
situacao = :situacao,
atualizadoEm = NOW()
WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
} else {
// Novo cadastro
$sql = "INSERT INTO visitante (
nome,
telefone,
email,
id_usuario,
situacao,
dataCadastro
) VALUES (
:nome,
:telefone,
:email,
:id_usuario,
:situacao,
NOW()
)";
$stmt = $pdo->prepare($sql);
}
$stmt->bindValue(':nome', $nome);
$stmt->bindValue(':telefone', $telefone);
$stmt->bindValue(
':email',
$email !== '' ? $email : null,
$email !== '' ? PDO::PARAM_STR : PDO::PARAM_NULL
);
$stmt->bindValue(
':id_usuario',
$idUsuario,
$idUsuario !== null ? PDO::PARAM_INT : PDO::PARAM_NULL
);
$stmt->bindValue(':situacao', $situacao);
$stmt->execute();
$_SESSION['flash_visitante'] = [
'mensagem' => $id > 0
? 'Visitante atualizado com sucesso!'
: 'Visitante cadastrado com sucesso!',
'tipo' => 'sucesso'
];
}
} catch (PDOException $e) {
error_log('Erro visitante: ' . $e->getMessage());
$_SESSION['flash_visitante'] = [
'mensagem' => 'Erro ao salvar o visitante. Verifique os dados.',
'tipo' => 'erro'
];
}
}
header('Location: index.php');
exit;
}
/* =============================================
EXCLUIR
============================================= */
if ($acao === 'excluir') {
$id = (int)($_POST['id'] ?? 0);
try {
if ($id > 0) {
$stmt = $pdo->prepare(
"DELETE FROM visitante WHERE id = :id"
);
$stmt->execute([':id' => $id]);
$_SESSION['flash_visitante'] = [
'mensagem' => 'Visitante excluído com sucesso.',
'tipo' => 'sucesso'
];
}
} catch (PDOException $e) {
error_log('Erro ao excluir visitante: ' . $e->getMessage());
$_SESSION['flash_visitante'] = [
'mensagem' => 'Não foi possível excluir. Verifique se existem registros vinculados.',
'tipo' => 'erro'
];
}
header('Location: index.php');
exit;
}
}
/* =====================================================
PARÂMETROS DE PESQUISA E PAGINAÇÃO
===================================================== */
$busca = trim($_GET['busca'] ?? '');
$pagina = max(1, (int)($_GET['pagina'] ?? 1));
$porPagina = 20;
$offset = ($pagina - 1) * $porPagina;
/* =====================================================
VISITANTE EM EDIÇÃO
===================================================== */
$visitanteEdicao = null;
if (!empty($_GET['editar'])) {
$idEditar = (int)$_GET['editar'];
$stmt = $pdo->prepare(
"SELECT * FROM visitante WHERE id = :id"
);
$stmt->execute([':id' => $idEditar]);
$visitanteEdicao = $stmt->fetch(PDO::FETCH_ASSOC);
}
/* =====================================================
TOTAL DE REGISTROS
===================================================== */
$sqlCount = "SELECT COUNT(*) FROM visitante WHERE 1=1";
$parametros = [];
if ($busca !== '') {
$sqlCount .= " AND (
nome LIKE :busca
OR telefone LIKE :busca
OR email LIKE :busca
)";
$parametros[':busca'] = '%' . $busca . '%';
}
$stmt = $pdo->prepare($sqlCount);
$stmt->execute($parametros);
$totalRegistros = (int)$stmt->fetchColumn();
$totalPaginas = max(
1,
(int)ceil($totalRegistros / $porPagina)
);
if ($pagina > $totalPaginas) {
$pagina = $totalPaginas;
$offset = ($pagina - 1) * $porPagina;
}
/* =====================================================
LISTAGEM
===================================================== */
$sql = "SELECT *
FROM visitante
WHERE 1=1";
if ($busca !== '') {
$sql .= " AND (
nome LIKE :busca
OR telefone LIKE :busca
OR email LIKE :busca
)";
}
$sql .= " ORDER BY id DESC LIMIT :limite OFFSET :offset";
$stmt = $pdo->prepare($sql);
if ($busca !== '') {
$stmt->bindValue(':busca', '%' . $busca . '%');
}
$stmt->bindValue(':limite', $porPagina, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$visitantes = $stmt->fetchAll(PDO::FETCH_ASSOC);
/* =====================================================
ESTATÍSTICAS
===================================================== */
$estatisticas = $pdo->query("
SELECT
COUNT(*) AS total,
SUM(CASE WHEN situacao = 'ativo' THEN 1 ELSE 0 END) AS ativos,
SUM(CASE WHEN id_usuario IS NOT NULL THEN 1 ELSE 0 END) AS convertidos
FROM visitante
")->fetch(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visitantes - CCMBR</title>
<style>
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 20px;
background: #f4f6f9;
font-family: Arial, sans-serif;
color: #333;
}
.container {
max-width: 1100px;
margin: auto;
}
.painel {
background: #fff;
padding: 22px;
border-radius: 10px;
margin-bottom: 20px;
box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}
h1 {
margin-top: 0;
font-size: 25px;
}
h2 {
font-size: 19px;
margin-top: 0;
}
.estatisticas {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 15px;
}
.estatistica {
padding: 16px;
background: #f4f6f9;
border-radius: 8px;
}
.estatistica strong {
display: block;
font-size: 24px;
color: #2463a6;
margin-top: 8px;
}
.form-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 15px;
}
.campo {
display: flex;
flex-direction: column;
gap: 6px;
}
.campo label {
font-weight: bold;
font-size: 13px;
}
input, select {
width: 100%;
padding: 11px;
border: 1px solid #ccc;
border-radius: 6px;
font-size: 14px;
}
.acoes {
display: flex;
gap: 8px;
margin-top: 18px;
flex-wrap: wrap;
}
button, .botao {
display: inline-block;
padding: 10px 16px;
border: none;
border-radius: 6px;
cursor: pointer;
text-decoration: none;
font-size: 14px;
color: #fff;
background: #2874b9;
}
.botao-secundario {
background: #6c757d;
}
.botao-editar {
background: #e09b24;
padding: 7px 11px;
}
.botao-excluir {
background: #dc3545;
padding: 7px 11px;
}
.alerta {
padding: 13px;
border-radius: 6px;
margin-bottom: 18px;
}
.sucesso {
background: #d4edda;
color: #155724;
}
.erro {
background: #f8d7da;
color: #721c24;
}
.pesquisa {
display: flex;
gap: 10px;
margin-bottom: 18px;
}
.pesquisa input {
flex: 1;
}
.tabela-responsiva {
width: 100%;
overflow-x: auto;
}
table {
width: 100%;
border-collapse: collapse;
min-width: 750px;
}
th, td {
padding: 12px 10px;
text-align: left;
border-bottom: 1px solid #eee;
font-size: 13px;
}
th {
background: #f4f6f9;
}
.status {
display: inline-block;
padding: 5px 9px;
border-radius: 15px;
font-size: 11px;
font-weight: bold;
}
.status-ativo {
background: #d4edda;
color: #155724;
}
.status-inativo {
background: #e2e3e5;
color: #383d41;
}
.status-bloqueado {
background: #f8d7da;
color: #721c24;
}
.acoes-tabela {
display: flex;
gap: 6px;
align-items: center;
}
.acoes-tabela form {
margin: 0;
}
.paginacao {
display: flex;
gap: 6px;
margin-top: 20px;
flex-wrap: wrap;
}
.paginacao a,
.paginacao span {
padding: 8px 12px;
background: #f0f0f0;
color: #333;
text-decoration: none;
border-radius: 5px;
font-size: 13px;
}
.paginacao .atual {
background: #2874b9;
color: #fff;
}
.vazio {
text-align: center;
color: #777;
padding: 25px;
}
@media (max-width: 650px) {
body {
padding: 10px;
}
.painel {
padding: 15px;
}
.form-grid {
grid-template-columns: 1fr;
}
.estatisticas {
grid-template-columns: 1fr;
}
.pesquisa {
flex-direction: column;
}
}
</style>
</head>
<body>
<div class="container">
<h1>Cadastro de Visitantes</h1>
<p>Gerenciamento dos visitantes e contatos das IAs do CCMBR.</p>
<?php if ($mensagem): ?>
<div class="alerta <?= h($tipoMensagem) ?>">
<?= h($mensagem) ?>
</div>
<?php endif; ?>
<!-- ESTATÍSTICAS -->
<div class="painel">
<div class="estatisticas">
<div class="estatistica">
Total de visitantes
<strong><?= (int)$estatisticas['total'] ?></strong>
</div>
<div class="estatistica">
Visitantes ativos
<strong><?= (int)$estatisticas['ativos'] ?></strong>
</div>
<div class="estatistica">
Vinculados ao CCMBR
<strong><?= (int)$estatisticas['convertidos'] ?></strong>
</div>
</div>
</div>
<!-- FORMULÁRIO -->
<div class="painel" id="formulario">
<h2>
<?= $visitanteEdicao
? 'Editar Visitante'
: 'Novo Visitante' ?>
</h2>
<form method="POST" action="index.php">
<input type="hidden" name="csrf"
value="<?= h($csrf) ?>">
<input type="hidden" name="acao" value="salvar">
<input type="hidden" name="id"
value="<?= (int)($visitanteEdicao['id'] ?? 0) ?>">
<div class="form-grid">
<div class="campo">
<label>Nome</label>
<input type="text"
name="nome"
maxlength="150"
value="<?= h($visitanteEdicao['nome'] ?? '') ?>"
placeholder="Nome do visitante">
</div>
<div class="campo">
<label>Telefone / WhatsApp *</label>
<input type="text"
name="telefone"
maxlength="25"
required
value="<?= h($visitanteEdicao['telefone'] ?? '') ?>"
placeholder="DDD + número">
</div>
<div class="campo">
<label>E-mail</label>
<input type="email"
name="email"
maxlength="150"
value="<?= h($visitanteEdicao['email'] ?? '') ?>"
placeholder="E-mail do visitante">
</div>
<div class="campo">
<label>ID Usuário CCMBR</label>
<input type="number"
name="id_usuario"
min="1"
value="<?= h($visitanteEdicao['id_usuario'] ?? '') ?>"
placeholder="Opcional">
</div>
<div class="campo">
<label>Situação</label>
<select name="situacao">
<?php
$situacaoAtual = $visitanteEdicao['situacao'] ?? 'ativo';
?>
<option value="ativo"
<?= $situacaoAtual === 'ativo' ? 'selected' : '' ?>>
Ativo
</option>
<option value="inativo"
<?= $situacaoAtual === 'inativo' ? 'selected' : '' ?>>
Inativo
</option>
<option value="bloqueado"
<?= $situacaoAtual === 'bloqueado' ? 'selected' : '' ?>>
Bloqueado
</option>
</select>
</div>
</div>
<div class="acoes">
<button type="submit">
<?= $visitanteEdicao ? 'Atualizar Visitante' : 'Cadastrar Visitante' ?>
</button>
<?php if ($visitanteEdicao): ?>
<a href="index.php" class="botao botao-secundario">
Cancelar
</a>
<?php endif; ?>
</div>
</form>
</div>
<!-- LISTAGEM -->
<div class="painel">
<h2>Visitantes cadastrados</h2>
<form method="GET" class="pesquisa">
<input type="text"
name="busca"
value="<?= h($busca) ?>"
placeholder="Pesquisar por nome, telefone ou e-mail">
<button type="submit">Pesquisar</button>
<a href="index.php" class="botao botao-secundario">
Limpar
</a>
</form>
<div class="tabela-responsiva">
<table>
<thead>
<tr>
<th>ID</th>
<th>Visitante</th>
<th>Telefone</th>
<th>E-mail</th>
<th>CCMBR</th>
<th>Situação</th>
<th>Cadastro</th>
<th>Ações</th>
</tr>
</thead>
<tbody>
<?php if (count($visitantes) > 0): ?>
<?php foreach ($visitantes as $v): ?>
<tr>
<td><?= (int)$v['id'] ?></td>
<td>
<strong><?= h($v['nome'] ?: 'Não informado') ?></strong>
</td>
<td><?= h($v['telefone']) ?></td>
<td><?= h($v['email'] ?: '-') ?></td>
<td>
<?= !empty($v['id_usuario'])
? 'Usuário #' . (int)$v['id_usuario']
: 'Visitante' ?>
</td>
<td>
<span class="status status-<?= h($v['situacao']) ?>">
<?= h(ucfirst($v['situacao'])) ?>
</span>
</td>
<td>
<?= !empty($v['dataCadastro'])
? date('d/m/Y', strtotime($v['dataCadastro']))
: '-' ?>
</td>
<td>
<div class="acoes-tabela">
<a href="editar.php?id=<?= (int)$v['id'] ?>"
class="botao botao-editar">
Editar
</a>
<form method="POST"
action="index.php"
onsubmit="return confirm('Deseja realmente excluir este visitante?');">
<input type="hidden" name="csrf"
value="<?= h($csrf) ?>">
<input type="hidden" name="acao"
value="excluir">
<input type="hidden" name="id"
value="<?= (int)$v['id'] ?>">
<button type="submit"
class="botao-excluir">
Excluir
</button>
</form>
</div>
</td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="8" class="vazio">
Nenhum visitante encontrado.
</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
<!-- PAGINAÇÃO -->
<?php if ($totalPaginas > 1): ?>
<div class="paginacao">
<?php for ($i = 1; $i <= $totalPaginas; $i++): ?>
<a href=""
class="<?= $i === $pagina ? 'atual' : '' ?>">
<?= $i ?>
</a>
<?php endfor; ?>
</div>
<?php endif; ?>
<p style="color:#777;font-size:13px;margin-top:15px;">
Exibindo <?= count($visitantes) ?> de
<?= $totalRegistros ?> visitante(s).
</p>
</div>
</div>
</body>
</html>
Nilton Romani