Files
fitme3070.pt/site/agendar.php
andreandClaude Opus 5.5 04c8c83e66 feat: aulas experimentais guardadas, anti-spam partilhado nos formulários, audit das escritas
- Pedido de aula experimental passa a ficar em trial_leads (por ginásio)
  ANTES do email: sem SMTP o visitante já não vê «erro» e o pedido não se
  perde. Gestão → Aulas experimentais: estados, notas, CSV (auditado),
  apagar para a lixeira; aviso «sem email» quando o aviso não saiu.
- Aula experimental, inscrição e eventos usam o anti-spam do platform-tools
  (honeypot, carimbo assinado com tempo mínimo, prova de JS, limite por IP,
  pontuação de conteúdo) e o bloqueio de IP, em vez de honeypots locais.
  Recusas ficam em blocked_submissions; resposta igual à de sucesso.
  Falha aberto se o módulo rebentar.
- Checkbox de consentimento da aula experimental passa a ser guardada.
- Audit das escritas de conteúdo: criar/editar equipa, modalidades,
  eventos, mensalidades, pedidos de inscrição, galerias, horário (incl.
  arrastar no calendário), horas, contactos e ginásios, com antes/depois
  campo a campo (audit_row/audit_change). Exportação CSV de inscrições
  auditada.
- .table-responsive em todas as tabelas do backoffice.
- Migração: database/migration_20260926_trial_leads.sql (só cria tabelas).

Testado numa cópia da BD de produção: 63/63 verificações HTTP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:33:24 +01:00

120 lines
4.8 KiB
PHP

<?php
// POST handler for the "aula experimental" (trial class) modal on the homepage.
// Builds a booking-request email and relays it to id.andmore.pt's centralized
// mail service via the enqueue_email()/flush_message() façade, then redirects
// back to #contactos with an ?agendar=ok|erro flag the homepage renders.
//
// Reached via .htaccess: ^home/agendar/?$ → site/agendar.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/functions.php';
// The gym comes from the URL folder (/<slug>/agendar); the old /home/agendar
// route has no ?gym and falls back to the default gym.
$gym = site_gym($pdo) ?? db_gyms_default($pdo) ?? gym_fallback();
$GLOBALS['_gym'] = $gym;
// Only POST is meaningful here; anything else just goes to the gym's page.
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
header('Location: ' . gym_url($gym));
exit;
}
csrf_check(); // 403s and exits on a bad/missing token
function agendar_redirect(string $status): void {
header('Location: ' . gym_url(current_gym(), '?agendar=' . $status . '#contactos'));
exit;
}
$nome = trim((string) ($_POST['nome'] ?? ''));
$email = trim((string) ($_POST['email'] ?? ''));
$telefone = trim((string) ($_POST['telefone'] ?? ''));
$data = trim((string) ($_POST['data'] ?? ''));
$periodo = trim((string) ($_POST['periodo'] ?? ''));
$mensagem = trim((string) ($_POST['mensagem'] ?? ''));
if ($nome === '' || $telefone === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
agendar_redirect('erro');
}
// Anti-spam partilhado (config/functions_forms.php). Recusado = mesma resposta
// de sucesso; fica em blocked_submissions.
if (public_form_screen($pdo, 'trial', 'trial_leads', $nome, $mensagem) !== null) {
agendar_redirect('ok');
}
// Pretty-print the preferred date if it parses; otherwise leave it blank.
$data_fmt = '';
if ($data !== '') {
$d = DateTime::createFromFormat('Y-m-d', $data);
$data_fmt = ($d && $d->format('Y-m-d') === $data) ? $d->format('d/m/Y') : '';
}
// O pedido fica guardado ANTES do email: sem SMTP (ou com ele em baixo) o
// pedido já não se perde — aparece em Gestão → Aulas experimentais.
$consent_text = 'Li e aceito a Política de Privacidade.';
$leadId = 0;
try {
$leadId = db_trial_lead_create($pdo, [
'gym_id' => (int) $gym['id'],
'name' => $nome,
'email' => $email,
'phone' => $telefone,
'preferred_date' => $data_fmt !== '' ? $data : '',
'period' => $periodo,
'message' => $mensagem,
'consent' => !empty($_POST['consent']),
'consent_text' => !empty($_POST['consent']) ? $consent_text : '',
'ip' => client_ip(),
'user_agent' => (string) ($_SERVER['HTTP_USER_AGENT'] ?? ''),
]);
} catch (Throwable $e) {
// Tabela por migrar: segue só por email, como antes.
error_log('[agendar] ' . $e->getMessage());
}
$info = site_info($pdo, (int) $gym['id']);
$to = $info['email'] !== '' ? $info['email'] : EMAIL_FROM;
$e = static fn($v) => htmlspecialchars((string) $v, ENT_QUOTES, 'UTF-8');
$rows = [
'Nome' => $nome,
'Telemóvel' => $telefone,
'E-mail' => $email,
'Dia preferido' => $data_fmt,
'Período preferido'=> $periodo,
'Mensagem' => $mensagem,
];
$body = '<h2 style="margin:0 0 16px;">Novo pedido de aula experimental</h2><table cellpadding="6" style="border-collapse:collapse;font-family:Arial,sans-serif;font-size:14px;">';
foreach ($rows as $label => $value) {
if (trim((string) $value) === '') continue;
$body .= '<tr><td style="font-weight:bold;vertical-align:top;">' . $e($label)
. ':</td><td>' . nl2br($e($value)) . '</td></tr>';
}
$body .= '</table><p style="font-family:Arial,sans-serif;font-size:13px;color:#666;margin-top:18px;">'
. 'Pedido enviado através do formulário do site ' . $e($gym['name']) . '. Responde diretamente a '
. $e($email) . ' ou liga para ' . $e($telefone) . '.</p>';
$alt = "Novo pedido de aula experimental\n\n";
foreach ($rows as $label => $value) {
if (trim((string) $value) === '') continue;
$alt .= "$label: $value\n";
}
$id = enqueue_email([
'to_address' => $to,
'to_name' => $info['name'] !== '' ? $info['name'] : $gym['name'],
'subject' => 'Pedido de aula experimental — ' . $nome,
'body' => $body,
'alt_body' => $alt,
'context_type' => 'fitme_trial',
]);
$sent = false;
try { $sent = flush_message($id); } catch (Throwable $e) { error_log('[agendar] email: ' . $e->getMessage()); }
if ($sent && $leadId) db_trial_lead_mark_emailed($pdo, $leadId);
// Guardado = sucesso para o visitante, mesmo que o email falhe (fica na fila e
// o pedido está no backoffice). Só é erro se não ficou em lado nenhum.
agendar_redirect(($leadId || $sent) ? 'ok' : 'erro');