feat: contactos editáveis, equipa com título/aptidões, mensalidades e reviews Google

- Contactos: nova página no backoffice (fitme3070_info) e 964 201 137 como
  telefone principal; o telefone secundário só aparece quando existe.
- Equipa: título, aptidões/funções e formações; o cartão mostra foto, nome e
  título e abre um cartão horizontal de detalhe (hover no desktop, toque no
  telemóvel) sem mexer na grelha.
- Mensalidades: cartões editáveis com um destaque, modal de inscrição que
  guarda o pedido (RGPD + estado + campos reservados para o CRM) e avisa o
  ginásio por e-mail; lista de pedidos com estados, notas e CSV.
- Reviews Google via Places API (New), filtradas por classificação mínima e
  em cache configurável; página de configuração com pesquisa do Place ID.
- Assets com ?v=<mtime>: site/assets é servido com cache imutável de 1 ano.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andreandClaude Opus 5.5 committed 2026-09-24 14:58:57 +01:00
1 parent 8a494d59a5
commit f95c9ebc52
27 files changed
+2063 -16

No files matched your search

+1
View File
@@ -36,6 +36,7 @@ RewriteRule ^home/modalidades/?$ site/modalidades.php [L,QSA]
RewriteRule ^home/horario/?$ site/horario.php [L,QSA]
RewriteRule ^home/contactos/?$ site/contactos.php [L,QSA]
RewriteRule ^home/agendar/?$ site/agendar.php [L,QSA]
RewriteRule ^home/inscricao/?$ site/inscricao.php [L,QSA]
RewriteRule ^home/crossfit/?$ site/crossfit.php [L,QSA]
RewriteRule ^home/privacidade/?$ site/privacidade.php [L,QSA]
RewriteRule ^evento/([a-zA-Z0-9-]+)/?$ site/evento.php?slug=$1 [L,QSA]
+10 -2
View File
@@ -9,11 +9,19 @@ if (!defined('SITE_INCLUDES')) {
}
// <script src> / <link rel=stylesheet> tag builders (CI4 html helper).
// site/assets is served with a one-year immutable Cache-Control, so local files
// carry their mtime as ?v= — an edited style.css/main.js gets a new URL instead
// of staying stuck in returning visitors' caches.
function _asset_versioned(string $path): string {
$file = dirname(__DIR__) . '/' . ltrim($path, '/');
if (strpos($path, '?') !== false || preg_match('~^https?://~', $path) || !is_file($file)) return base_url($path);
return base_url($path) . '?v=' . filemtime($file);
}
function script_tag(string $src): string {
return '<script src="' . htmlspecialchars(base_url($src), ENT_QUOTES) . '"></script>' . "\n";
return '<script src="' . htmlspecialchars(_asset_versioned($src), ENT_QUOTES) . '"></script>' . "\n";
}
function link_tag(string $href, string $rel = 'stylesheet'): string {
return '<link rel="' . $rel . '" href="' . htmlspecialchars(base_url($href), ENT_QUOTES) . '">' . "\n";
return '<link rel="' . $rel . '" href="' . htmlspecialchars(_asset_versioned($href), ENT_QUOTES) . '">' . "\n";
}
function site_url(string $path = ''): string { return base_url($path); }
+3
View File
@@ -31,6 +31,9 @@ require_once __DIR__ . '/functions_galerias.php'; // galleries + images CRU
require_once __DIR__ . '/functions_work_hours.php'; // work hours CRUD
require_once __DIR__ . '/functions_horario.php'; // class schedule CRUD
require_once __DIR__ . '/functions_events.php'; // time-limited events + landing pages + leads
require_once __DIR__ . '/functions_info.php'; // contactos (fitme3070_info) editor
require_once __DIR__ . '/functions_memberships.php'; // mensalidades + pedidos de inscrição
require_once __DIR__ . '/functions_reviews.php'; // reviews Google (Places API) + cache
// ─── DB-backed settings → legacy constants ───────────────────────────────────
// Resolved once from the settings cache so call sites read plain constants.
+58
View File
@@ -0,0 +1,58 @@
<?php
// ─── Contactos (fitme3070_info, linha id=1) ───────────────────────────────────
// Single-row table read by site_info() (functions_site.php) — contact section,
// footer, mobile "Ligar" bar, WhatsApp button and the SEO JSON-LD all take their
// values from here, so one save updates every place.
// Used by views/admin/info/edit.php.
// field => [label, max length, input type]. Order is the form order.
function info_fields(): array {
return [
'name' => ['Nome do ginásio', 200, 'text'],
'adress' => ['Morada', 200, 'text'],
'phone' => ['Telefone principal', 25, 'tel'],
'telephone' => ['Telefone secundário', 25, 'tel'],
'whatsapp' => ['WhatsApp (só dígitos, ex.: 351964201137)', 13, 'text'],
'email' => ['E-mail', 100, 'email'],
'website' => ['Website', 100, 'text'],
'instagram' => ['Instagram (URL)', 200, 'url'],
'facebook' => ['Facebook (URL)', 200, 'url'],
'messenger' => ['Messenger (URL)', 200, 'url'],
'google_maps_link' => ['Google Maps — link', 255, 'url'],
'google_maps' => ['Google Maps — código embed (iframe)', 0, 'textarea'],
];
}
function info_from_post(array $post, array &$errors): array {
$data = [];
foreach (info_fields() as $key => [$label, $max, $type]) {
$v = trim((string) ($post[$key] ?? ''));
if ($key === 'whatsapp') $v = preg_replace('/\D+/', '', $v);
if ($max > 0 && mb_strlen($v) > $max) $errors[] = "«{$label}» tem mais de {$max} caracteres.";
if ($v !== '' && $type === 'email' && !filter_var($v, FILTER_VALIDATE_EMAIL)) $errors[] = 'O e-mail não é válido.';
if ($v !== '' && $type === 'url' && !preg_match('~^https?://~i', $v)) $errors[] = "«{$label}» tem de começar por https://";
$data[$key] = $v;
}
// Only a Google Maps iframe survives; anything else is dropped here rather
// than stored and filtered on every page view.
$data['google_maps'] = clean_map_embed($data['google_maps']);
if ($data['name'] === '') $errors[] = 'O nome é obrigatório.';
if ($data['phone'] === '') $errors[] = 'O telefone principal é obrigatório.';
return $data;
}
function db_info_save(PDO $pdo, array $data): bool {
$cols = array_keys(info_fields());
$exists = (bool) $pdo->query("SELECT COUNT(*) FROM fitme3070_info WHERE id = 1")->fetchColumn();
$vals = array_map(fn($c) => $data[$c] ?? '', $cols);
if ($exists) {
$sets = implode(', ', array_map(fn($c) => "`$c` = ?", $cols));
$stmt = $pdo->prepare("UPDATE fitme3070_info SET $sets, updated_at = NOW() WHERE id = 1");
} else {
$names = implode(', ', array_map(fn($c) => "`$c`", $cols));
$marks = implode(', ', array_fill(0, count($cols), '?'));
$stmt = $pdo->prepare("INSERT INTO fitme3070_info (id, $names, updated_at) VALUES (1, $marks, NOW())");
}
$stmt->execute($vals);
return $stmt->rowCount() > 0;
}
+191
View File
@@ -0,0 +1,191 @@
<?php
// ─── Mensalidades (cartões de preço) + pedidos de inscrição ───────────────────
// Soft-delete via deleted_at. Only one card may be featured at a time — enforced
// here, on save, rather than in the schema.
// Used by views/admin/memberships/*.php, site/index.php and site/inscricao.php.
function memberships_defaults(): array {
return [
'name' => '', 'subtitle' => '', 'price' => '', 'is_addon' => 0,
'price_suffix' => '/mês', 'features' => '', 'is_featured' => 0,
'featured_label' => 'Mais popular', 'cta_label' => 'Inscrever',
'item_order' => 0, 'is_active' => 1,
];
}
function db_memberships_list(PDO $pdo, bool $include_deleted = false): array {
$sql = "SELECT * FROM memberships";
if (!$include_deleted) $sql .= " WHERE deleted_at IS NULL";
$sql .= " ORDER BY deleted_at IS NOT NULL, item_order, name";
return $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
}
// Public list: active, not deleted. Defensive — the table may not exist yet on
// an install that hasn't run the migration.
function site_memberships(PDO $pdo): array {
try {
return $pdo->query(
"SELECT * FROM memberships WHERE deleted_at IS NULL AND is_active = 1 ORDER BY item_order, name"
)->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) { return []; }
}
function db_memberships_get(PDO $pdo, int $id): ?array {
$stmt = $pdo->prepare("SELECT * FROM memberships WHERE id = ? LIMIT 1");
$stmt->execute([$id]);
return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
}
// Normalise raw POST into the row shape; appends messages to $errors.
function memberships_from_post(array $post, array &$errors): array {
$price = str_replace([' ', '€'], '', trim((string) ($post['price'] ?? '')));
$price = str_replace(',', '.', $price);
$data = [
'name' => mb_substr(trim((string) ($post['name'] ?? '')), 0, 100),
'subtitle' => mb_substr(trim((string) ($post['subtitle'] ?? '')), 0, 255),
'price' => $price,
'is_addon' => !empty($post['is_addon']) ? 1 : 0,
'price_suffix' => mb_substr(trim((string) ($post['price_suffix'] ?? '')), 0, 60),
'features' => trim((string) ($post['features'] ?? '')),
'is_featured' => !empty($post['is_featured']) ? 1 : 0,
'featured_label' => mb_substr(trim((string) ($post['featured_label'] ?? '')), 0, 40),
'cta_label' => mb_substr(trim((string) ($post['cta_label'] ?? '')), 0, 40),
'item_order' => (int) ($post['item_order'] ?? 0),
'is_active' => !empty($post['is_active']) ? 1 : 0,
];
if ($data['name'] === '') $errors[] = 'O nome é obrigatório.';
if ($price !== '' && (!is_numeric($price) || (float) $price < 0)) $errors[] = 'Preço inválido — usa um número, ex.: 34,90.';
if ($data['featured_label'] === '') $data['featured_label'] = 'Mais popular';
if ($data['cta_label'] === '') $data['cta_label'] = 'Inscrever';
return $data;
}
function _memberships_params(array $d): array {
return [
$d['name'], $d['subtitle'],
$d['price'] === '' || $d['price'] === null ? null : number_format((float) $d['price'], 2, '.', ''),
$d['is_addon'], $d['price_suffix'], $d['features'] !== '' ? $d['features'] : null,
$d['is_featured'], $d['featured_label'], $d['cta_label'], $d['item_order'], $d['is_active'],
];
}
function _memberships_clear_featured(PDO $pdo, int $except): void {
$pdo->prepare("UPDATE memberships SET is_featured = 0 WHERE id <> ? AND is_featured = 1")->execute([$except]);
}
function db_memberships_create(PDO $pdo, array $d): int {
$pdo->beginTransaction();
$stmt = $pdo->prepare("
INSERT INTO memberships (name, subtitle, price, is_addon, price_suffix, features,
is_featured, featured_label, cta_label, item_order, is_active,
created_at, updated_at)
VALUES (?,?,?,?,?,?,?,?,?,?,?, NOW(), NOW())
");
$stmt->execute(_memberships_params($d));
$id = (int) $pdo->lastInsertId();
if ($d['is_featured']) _memberships_clear_featured($pdo, $id);
$pdo->commit();
return $id;
}
function db_memberships_update(PDO $pdo, int $id, array $d): bool {
$pdo->beginTransaction();
$stmt = $pdo->prepare("
UPDATE memberships SET name = ?, subtitle = ?, price = ?, is_addon = ?, price_suffix = ?,
features = ?, is_featured = ?, featured_label = ?, cta_label = ?, item_order = ?,
is_active = ?, updated_at = NOW()
WHERE id = ?
");
$params = _memberships_params($d);
$params[] = $id;
$stmt->execute($params);
$changed = $stmt->rowCount() > 0;
if ($d['is_featured']) _memberships_clear_featured($pdo, $id);
$pdo->commit();
return $changed;
}
function db_memberships_delete(PDO $pdo, int $id): bool {
$stmt = $pdo->prepare("UPDATE memberships SET deleted_at = NOW(), is_featured = 0 WHERE id = ? AND deleted_at IS NULL");
$stmt->execute([$id]);
return $stmt->rowCount() > 0;
}
function db_memberships_restore(PDO $pdo, int $id): bool {
$stmt = $pdo->prepare("UPDATE memberships SET deleted_at = NULL WHERE id = ? AND deleted_at IS NOT NULL");
$stmt->execute([$id]);
return $stmt->rowCount() > 0;
}
// "34,90 €" / "+10 €" / "Sob consulta" — PT formatting, drops ",00".
function membership_price_label(array $m): string {
if ($m['price'] === null || $m['price'] === '') return 'Sob consulta';
$p = (float) $m['price'];
$s = number_format($p, floor($p) == $p ? 0 : 2, ',', ' ');
return (!empty($m['is_addon']) ? '+' : '') . $s . ' €';
}
// Non-empty trimmed lines of a textarea — used for features, skills, formações.
function text_lines(?string $text): array {
$out = [];
foreach (preg_split('/\R/', (string) $text) as $line) {
$line = trim($line, " \t-•");
if ($line !== '') $out[] = $line;
}
return $out;
}
// ─── Pedidos de inscrição (leads) ─────────────────────────────────────────────
function membership_lead_statuses(): array {
return ['novo' => 'Novo', 'contactado' => 'Contactado', 'inscrito' => 'Inscrito', 'descartado' => 'Descartado'];
}
function db_membership_leads_list(PDO $pdo, string $status = ''): array {
$sql = "SELECT * FROM membership_leads";
$args = [];
if ($status !== '' && isset(membership_lead_statuses()[$status])) { $sql .= " WHERE status = ?"; $args[] = $status; }
$sql .= " ORDER BY created_at DESC, id DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($args);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
function db_membership_leads_count_new(PDO $pdo): int {
try { return (int) $pdo->query("SELECT COUNT(*) FROM membership_leads WHERE status = 'novo'")->fetchColumn(); }
catch (Throwable $e) { return 0; }
}
function db_membership_lead_create(PDO $pdo, array $d): int {
$stmt = $pdo->prepare("
INSERT INTO membership_leads (membership_id, membership_name, name, email, phone, message,
consent, consent_text, ip, user_agent, created_at, updated_at)
VALUES (?,?,?,?,?,?,?,?,?,?, NOW(), NOW())
");
$stmt->execute([
$d['membership_id'] ?: null,
mb_substr((string) ($d['membership_name'] ?? ''), 0, 100),
mb_substr(trim((string) ($d['name'] ?? '')), 0, 150),
mb_substr(trim((string) ($d['email'] ?? '')), 0, 190),
mb_substr(trim((string) ($d['phone'] ?? '')), 0, 40),
mb_substr(trim((string) ($d['message'] ?? '')), 0, 1000),
!empty($d['consent']) ? 1 : 0,
mb_substr((string) ($d['consent_text'] ?? ''), 0, 255),
mb_substr((string) ($d['ip'] ?? ''), 0, 45),
mb_substr((string) ($d['user_agent'] ?? ''), 0, 255),
]);
return (int) $pdo->lastInsertId();
}
function db_membership_lead_update(PDO $pdo, int $id, string $status, string $notes): bool {
if (!isset(membership_lead_statuses()[$status])) return false;
$stmt = $pdo->prepare("UPDATE membership_leads SET status = ?, admin_notes = ?, updated_at = NOW() WHERE id = ?");
$stmt->execute([$status, $notes !== '' ? $notes : null, $id]);
return $stmt->rowCount() > 0;
}
function db_membership_lead_delete(PDO $pdo, int $id): bool {
$stmt = $pdo->prepare("DELETE FROM membership_leads WHERE id = ?");
$stmt->execute([$id]);
return $stmt->rowCount() > 0;
}
+200
View File
@@ -0,0 +1,200 @@
<?php
// ─── Reviews Google (Places API — New) ────────────────────────────────────────
// The homepage shows the gym's best Google reviews, pulled live from Place
// Details. Configured in the backoffice (views/admin/reviews/index.php):
//
// google_places_api_key — encrypted at rest (.env GOOGLE_PLACES_API_KEY wins)
// google_place_id — the gym's Place ID
// google_reviews_min_rating — only reviews with at least this many stars (default 4)
// google_reviews_max — how many to show (default 3)
// google_reviews_cache_hours — how long a fetch is reused (default 24)
//
// Two limits of the API shape the section:
// - Place Details returns at most 5 reviews, chosen by Google ("most
// relevant"). There is no "only positive" query: we filter those 5 by
// rating, so on a bad week fewer than `max` may qualify.
// - Reviews are a billed Enterprise + Atmosphere field. Without the cache every
// page view would be one billed call; with it, one call per cache window.
//
// The cache is a PHP array literal under config/cache/ (like the settings
// cache): read via include, served from opcache, never over HTTP. A failed
// refresh keeps serving the previous copy so a key/quota problem never blanks
// the section — the error is kept for the backoffice page to show.
const REVIEWS_FIELD_MASK = 'displayName,rating,userRatingCount,googleMapsUri,reviews';
function reviews_config(): array {
return [
'api_key' => setting_secret('google_places_api_key', 'GOOGLE_PLACES_API_KEY'),
'place_id' => trim((string) setting('google_place_id', '')),
'min_rating' => max(1, min(5, (int) setting('google_reviews_min_rating', 4))),
'max' => max(1, min(5, (int) setting('google_reviews_max', 3))),
'cache_hours' => max(1, (int) setting('google_reviews_cache_hours', 24)),
];
}
function reviews_configured(): bool {
$c = reviews_config();
return $c['api_key'] !== '' && $c['place_id'] !== '';
}
function _reviews_cache_path(): string {
return __DIR__ . '/cache/google_reviews.cache.php';
}
function reviews_cache_read(): ?array {
$path = _reviews_cache_path();
if (!is_file($path)) return null;
$data = @include $path;
return is_array($data) ? $data : null;
}
function _reviews_cache_write(array $data): void {
$path = _reviews_cache_path();
if (!is_dir(dirname($path))) @mkdir(dirname($path), 0775, true);
$tmp = $path . '.' . bin2hex(random_bytes(4)) . '.tmp';
if (@file_put_contents($tmp, "<?php\nreturn " . var_export($data, true) . ";\n", LOCK_EX) === false) return;
@rename($tmp, $path);
if (function_exists('opcache_invalidate')) @opcache_invalidate($path, true);
}
function reviews_cache_clear(): void {
$path = _reviews_cache_path();
if (is_file($path)) @unlink($path);
}
// Low-level GET/POST against places.googleapis.com. Returns [status, decoded|null, error].
function _places_request(string $method, string $url, string $apiKey, string $fieldMask, ?array $body = null): array {
if (!function_exists('curl_init')) return [0, null, 'cURL indisponível nesta instalação.'];
$ch = curl_init($url);
$headers = ['X-Goog-Api-Key: ' . $apiKey, 'X-Goog-FieldMask: ' . $fieldMask, 'Accept: application/json'];
if ($body !== null) {
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
}
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 3,
CURLOPT_TIMEOUT => 5,
]);
$raw = curl_exec($ch);
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
$cerr = curl_error($ch);
curl_close($ch);
if ($raw === false) return [0, null, 'Sem ligação à Google: ' . $cerr];
$json = json_decode((string) $raw, true);
if ($status !== 200) {
$msg = is_array($json) ? (string) ($json['error']['message'] ?? '') : '';
return [$status, $json, 'Google respondeu ' . $status . ($msg !== '' ? ': ' . $msg : '')];
}
return [$status, is_array($json) ? $json : null, is_array($json) ? '' : 'Resposta inválida da Google.'];
}
// Fetch Place Details now and rewrite the cache. Returns the cache array.
function reviews_refresh(): array {
$c = reviews_config();
$old = reviews_cache_read() ?? [];
if ($c['api_key'] === '' || $c['place_id'] === '') {
return $old + ['error' => 'Falta a chave da API ou o Place ID.'];
}
$url = 'https://places.googleapis.com/v1/places/' . rawurlencode($c['place_id']) . '?languageCode=pt-PT';
[$status, $json, $err] = _places_request('GET', $url, $c['api_key'], REVIEWS_FIELD_MASK);
if ($err !== '') {
// Keep serving the previous copy; retry after an hour, not a full window.
$data = $old;
$data['error'] = $err;
$data['error_at'] = time();
$data['fetched_at'] = time() - max(0, $c['cache_hours'] * 3600 - 3600);
_reviews_cache_write($data);
error_log('[reviews] ' . $err);
return $data;
}
$reviews = [];
foreach ((array) ($json['reviews'] ?? []) as $r) {
$reviews[] = [
'rating' => (int) ($r['rating'] ?? 0),
'text' => (string) ($r['text']['text'] ?? $r['originalText']['text'] ?? ''),
'relative' => (string) ($r['relativePublishTimeDescription'] ?? ''),
'published' => (string) ($r['publishTime'] ?? ''),
'author' => (string) ($r['authorAttribution']['displayName'] ?? ''),
'author_uri' => (string) ($r['authorAttribution']['uri'] ?? ''),
'author_photo' => (string) ($r['authorAttribution']['photoUri'] ?? ''),
'uri' => (string) ($r['googleMapsUri'] ?? ''),
];
}
$data = [
'fetched_at' => time(),
'name' => (string) ($json['displayName']['text'] ?? ''),
'rating' => isset($json['rating']) ? (float) $json['rating'] : null,
'total' => (int) ($json['userRatingCount'] ?? 0),
'maps_uri' => (string) ($json['googleMapsUri'] ?? ''),
'reviews' => $reviews,
'error' => '',
];
_reviews_cache_write($data);
return $data;
}
// Cached data, refreshed when older than the cache window. The refresh is
// serialised with a non-blocking lock so a burst of visitors at expiry makes
// one Google call, not one each — the others just serve the stale copy.
function reviews_get(): array {
$c = reviews_config();
$cache = reviews_cache_read();
$fresh = $cache && (time() - (int) ($cache['fetched_at'] ?? 0)) < $c['cache_hours'] * 3600;
if ($fresh || !reviews_configured()) return $cache ?? [];
$lock = @fopen(_reviews_cache_path() . '.lock', 'c');
if ($lock && flock($lock, LOCK_EX | LOCK_NB)) {
$cache = reviews_refresh();
flock($lock, LOCK_UN);
}
if ($lock) fclose($lock);
return $cache ?? [];
}
// What the homepage renders: summary + the best qualifying reviews, or null
// when there is nothing worth showing (not configured, no qualifying review).
function site_reviews(): ?array {
try { $data = reviews_get(); } catch (Throwable $e) { error_log('[reviews] ' . $e->getMessage()); return null; }
if (!$data || empty($data['reviews'])) return null;
$c = reviews_config();
$picked = array_values(array_filter($data['reviews'], fn($r) => $r['rating'] >= $c['min_rating'] && trim($r['text']) !== ''));
// Highest rating first; Google's relevance order breaks ties (usort is stable).
usort($picked, fn($a, $b) => $b['rating'] <=> $a['rating']);
$picked = array_slice($picked, 0, $c['max']);
if (!$picked) return null;
return [
'rating' => $data['rating'],
'total' => $data['total'],
'maps_uri' => $data['maps_uri'],
'write_uri' => 'https://search.google.com/local/writereview?placeid=' . rawurlencode($c['place_id']),
'reviews' => $picked,
];
}
// Backoffice helper: find the Place ID from a free-text query (Text Search,
// IDs + name + address only — the cheapest field set).
function reviews_find_place(string $query, string $apiKey): array {
[$status, $json, $err] = _places_request(
'POST', 'https://places.googleapis.com/v1/places:searchText', $apiKey,
'places.id,places.displayName,places.formattedAddress,places.rating,places.userRatingCount',
['textQuery' => $query, 'languageCode' => 'pt-PT', 'regionCode' => 'PT']
);
if ($err !== '') return ['error' => $err, 'places' => []];
$out = [];
foreach ((array) ($json['places'] ?? []) as $p) {
$out[] = [
'id' => (string) ($p['id'] ?? ''),
'name' => (string) ($p['displayName']['text'] ?? ''),
'address' => (string) ($p['formattedAddress'] ?? ''),
'rating' => $p['rating'] ?? null,
'total' => (int) ($p['userRatingCount'] ?? 0),
];
}
return ['error' => '', 'places' => $out];
}
+1
View File
@@ -30,6 +30,7 @@ function site_navbar(): array {
'Equipa' => '#equipa',
'Modalidades' => '#modalidades',
'Horário' => '#horario',
'Mensalidades' => '#mensalidades',
'Contactos' => '#contactos',
'CrossFit' => 'home/crossfit', // separate page, navbar styles it specially
];
+10 -3
View File
@@ -18,28 +18,35 @@ function db_team_get(PDO $pdo, int $id): ?array {
function db_team_create(PDO $pdo, array $data): int {
$stmt = $pdo->prepare("
INSERT INTO team (name, birthday, `at`, status, description, photo, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())
INSERT INTO team (name, title, birthday, `at`, status, description, skills, certifications, photo, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
");
$stmt->execute([
$data['name'],
$data['title'] ?? '',
$data['birthday'] ?: null,
$data['at'] ?: null,
$data['status'] ?? 'ativo',
$data['description'] ?? null,
($data['skills'] ?? '') !== '' ? $data['skills'] : null,
($data['certifications'] ?? '') !== '' ? $data['certifications'] : null,
$data['photo'] ?? null,
]);
return (int) $pdo->lastInsertId();
}
function db_team_update(PDO $pdo, int $id, array $data, ?string $photo = null): bool {
$sets = ["name = ?", "birthday = ?", "`at` = ?", "status = ?", "description = ?", "updated_at = NOW()"];
$sets = ["name = ?", "title = ?", "birthday = ?", "`at` = ?", "status = ?", "description = ?",
"skills = ?", "certifications = ?", "updated_at = NOW()"];
$params = [
$data['name'],
$data['title'] ?? '',
$data['birthday'] ?: null,
$data['at'] ?: null,
$data['status'] ?? 'ativo',
$data['description'] ?? null,
($data['skills'] ?? '') !== '' ? $data['skills'] : null,
($data['certifications'] ?? '') !== '' ? $data['certifications'] : null,
];
if ($photo !== null) {
$sets[] = "photo = ?";
@@ -0,0 +1,8 @@
-- ─── Contactos: novo número principal ────────────────────────────────────────
-- 964 201 137 passa a ser o telefone principal (phone), substituindo o número
-- anterior, que sai do site. O telefone secundário (telephone) não muda.
-- A partir daqui os contactos editam-se no backoffice (Gestão → Contactos).
UPDATE `fitme3070_info`
SET `phone` = '964 201 137', `updated_at` = NOW()
WHERE `id` = 1;
@@ -0,0 +1,60 @@
-- ─── Mensalidades + pedidos de inscrição ────────────────────────────────────
-- memberships: cartões de mensalidade editáveis no backoffice. Um só pode estar
-- em destaque (garantido na aplicação). is_addon = acresce à mensalidade base
-- (mostra "+X €").
-- membership_leads: pedidos do modal "Inscrever". Guarda o consentimento RGPD
-- (texto + IP + UA), o estado de acompanhamento e, reservado para a futura
-- integração com o CRM do ginásio, crm_ref / crm_synced_at.
-- Safe to re-run.
CREATE TABLE IF NOT EXISTS `memberships` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`subtitle` VARCHAR(255) NOT NULL DEFAULT '',
`price` DECIMAL(8,2) DEFAULT NULL,
`is_addon` TINYINT(1) NOT NULL DEFAULT 0,
`price_suffix` VARCHAR(60) NOT NULL DEFAULT '/mês',
`features` TEXT DEFAULT NULL,
`is_featured` TINYINT(1) NOT NULL DEFAULT 0,
`featured_label` VARCHAR(40) NOT NULL DEFAULT 'Mais popular',
`cta_label` VARCHAR(40) NOT NULL DEFAULT 'Inscrever',
`item_order` INT(11) NOT NULL DEFAULT 0,
`is_active` TINYINT(1) NOT NULL DEFAULT 1,
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`deleted_at` DATETIME DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_memberships_list` (`deleted_at`, `is_active`, `item_order`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `membership_leads` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`membership_id` INT(11) DEFAULT NULL,
`membership_name` VARCHAR(100) NOT NULL DEFAULT '',
`name` VARCHAR(150) NOT NULL,
`email` VARCHAR(190) NOT NULL DEFAULT '',
`phone` VARCHAR(40) NOT NULL DEFAULT '',
`message` VARCHAR(1000) NOT NULL DEFAULT '',
`status` ENUM('novo','contactado','inscrito','descartado') NOT NULL DEFAULT 'novo',
`admin_notes` TEXT DEFAULT NULL,
`consent` TINYINT(1) NOT NULL DEFAULT 0,
`consent_text` VARCHAR(255) NOT NULL DEFAULT '',
`ip` VARCHAR(45) NOT NULL DEFAULT '',
`user_agent` VARCHAR(255) NOT NULL DEFAULT '',
`crm_ref` VARCHAR(100) DEFAULT NULL,
`crm_synced_at` DATETIME DEFAULT NULL,
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_membership_leads_status` (`status`, `created_at`),
KEY `idx_membership_leads_crm` (`crm_synced_at`),
CONSTRAINT `fk_membership_leads_membership`
FOREIGN KEY (`membership_id`) REFERENCES `memberships` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Cartão de exemplo (o preço fica por definir no backoffice).
INSERT INTO `memberships` (`name`, `subtitle`, `price`, `is_addon`, `price_suffix`, `features`, `item_order`)
SELECT 'Off-hours', 'Mensalidade para as horas baixas do ginásio.', NULL, 1, 'acresce à mensalidade',
'Acesso nas horas de menor afluência\nSala de musculação e cardio', 10
FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `memberships`);
@@ -0,0 +1,9 @@
-- ─── Equipa: título, aptidões/funções e formações ───────────────────────────
-- O cartão público mostra foto + nome + título; aptidões e formações (uma por
-- linha) aparecem no cartão de detalhe ao passar o rato / tocar.
-- Safe to re-run.
ALTER TABLE `team`
ADD COLUMN IF NOT EXISTS `title` VARCHAR(100) NOT NULL DEFAULT '' AFTER `name`,
ADD COLUMN IF NOT EXISTS `skills` TEXT DEFAULT NULL AFTER `description`,
ADD COLUMN IF NOT EXISTS `certifications` TEXT DEFAULT NULL AFTER `skills`;
+12
View File
@@ -130,6 +130,18 @@ $app_name = defined('APP_NAME') ? APP_NAME : 'FitMe 3070';
<a class="nav-link<?= (strpos($_SERVER['SCRIPT_NAME'] ?? '', '/views/admin/horario/') !== false) ? ' active' : '' ?>"
href="<?= base_url('views/admin/horario/index.php') ?>"><i class="bi bi-calendar-week-fill"></i>Horário de Aulas</a>
</li>
<li class="nav-item">
<a class="nav-link<?= (strpos($_SERVER['SCRIPT_NAME'] ?? '', '/views/admin/memberships/') !== false) ? ' active' : '' ?>"
href="<?= base_url('views/admin/memberships/index.php') ?>"><i class="bi bi-credit-card-2-front-fill"></i>Mensalidades</a>
</li>
<li class="nav-item">
<a class="nav-link<?= (strpos($_SERVER['SCRIPT_NAME'] ?? '', '/views/admin/reviews/') !== false) ? ' active' : '' ?>"
href="<?= base_url('views/admin/reviews/index.php') ?>"><i class="bi bi-star-fill"></i>Reviews Google</a>
</li>
<li class="nav-item">
<a class="nav-link<?= (strpos($_SERVER['SCRIPT_NAME'] ?? '', '/views/admin/info/') !== false) ? ' active' : '' ?>"
href="<?= base_url('views/admin/info/edit.php') ?>"><i class="bi bi-telephone-fill"></i>Contactos</a>
</li>
</ul>
<?php endif; ?>
+543 -1
View File
@@ -2204,6 +2204,11 @@ section[id] {
margin-bottom: .5rem;
}
/* Short titles (e.g. "Modalidades") would otherwise sit on the eyebrow's line. */
.section-title.deco .section-eyebrow {
display: block;
}
.section-title.deco h2 {
position: relative;
display: inline-block;
@@ -2913,4 +2918,541 @@ section[id] {
.event-consent a { color: var(--fitme-accent-dark); text-decoration: underline; }
@media (max-width: 575px) {
.event-form-grid { grid-template-columns: 1fr; }
}
}
/* ══════════════════════════════════════════════════════════════════════════
Equipa — título + cartão de detalhe horizontal
Default card = photo + name + title. The detail card is laid OVER the grid
(absolute), so opening it never reflows the team wall. Desktop (fine pointer)
opens it on hover / keyboard focus; touch opens it on tap (.is-open, main.js),
where it becomes a centred fixed card with its own close button.
══════════════════════════════════════════════════════════════════════════ */
/* content-visibility:auto implies paint containment, which would clip the
overlay at the section edge and trap position:fixed inside the section. */
#equipa.trainers-section {
content-visibility: visible;
contain: none;
position: relative;
z-index: 3; /* hover card may overhang the next section */
}
/* While a card is open on touch, lift the whole section over the navbar and
the mobile CTA bar so the dimmed backdrop covers everything. */
#equipa.trainers-section.has-open-detail {
z-index: 1100;
}
/* The global scroll-reveal keeps transform:translateY(0) applied (fill
forwards), and any transform makes an element the containing block for
position:fixed descendants — which would pin the mobile detail card inside
its own tile. Reveal the team with opacity only. */
#equipa.revealed,
#equipa .trainer-item.revealed {
animation-name: fitmeFadeOnly;
}
@keyframes fitmeFadeOnly {
from { opacity: 0; }
to { opacity: 1; }
}
.trainer-item {
position: relative;
}
/* The name used to be the tile's last child and got its size from the
`.trainer-item>*:last-child` rule; pin it so it stays the same whether or
not a title / "Saber mais" follows it. */
.trainers-section .trainer-item h4 {
font-size: .9rem;
}
/* …and keep that same rule (white, .9rem) off the detail card when it is the
last child. */
.trainers-section .trainer-item>.trainer-detail {
color: var(--fitme-text);
font-size: 1rem;
}
.trainers-section .trainer-item p.trainer-title {
margin: 0;
font-size: .85rem;
font-weight: 600;
letter-spacing: .04em;
color: var(--fitme-accent);
}
.trainer-item.has-detail {
cursor: pointer;
outline: none;
}
.trainer-more {
display: inline-flex;
align-items: center;
gap: 6px;
margin-top: .55rem;
font-size: .72rem;
font-weight: 700;
letter-spacing: .12em;
text-transform: uppercase;
color: var(--fitme-ash);
transition: color var(--fitme-transition);
}
.trainer-more i { font-size: .65rem; }
.trainer-item.has-detail:hover .trainer-more,
.trainer-item.has-detail:focus-visible .trainer-more,
.trainer-item.has-detail.is-open .trainer-more {
color: var(--fitme-accent);
}
.trainer-detail {
position: absolute;
z-index: 30;
top: -10px;
left: 50%;
width: min(560px, calc(100vw - 32px));
transform: translateX(calc(-50% + var(--td-shift, 0px))) translateY(8px);
display: flex;
text-align: left;
background: #fff;
color: var(--fitme-text);
border-radius: 6px;
border-left: 4px solid var(--fitme-accent);
box-shadow: 0 24px 60px rgba(0, 0, 0, .45);
overflow: hidden;
opacity: 0;
visibility: hidden;
pointer-events: none;
transition: opacity .2s ease, transform .2s ease, visibility 0s linear .2s;
}
.trainer-item.is-open .trainer-detail {
opacity: 1;
visibility: visible;
pointer-events: auto;
transform: translateX(calc(-50% + var(--td-shift, 0px))) translateY(0);
transition: opacity .2s ease, transform .2s ease, visibility 0s;
}
@media (hover: hover) and (pointer: fine) {
.trainer-item.has-detail:hover .trainer-detail,
.trainer-item.has-detail:focus-within .trainer-detail {
opacity: 1;
visibility: visible;
pointer-events: auto;
transform: translateX(calc(-50% + var(--td-shift, 0px))) translateY(0);
transition: opacity .2s ease .12s, transform .2s ease .12s, visibility 0s .12s;
}
.trainer-item.has-detail:hover { z-index: 31; }
}
.trainer-item.is-open { z-index: 31; }
.td-photo {
flex: 0 0 38%;
max-width: 210px;
background: var(--fitme-dark-2);
}
.td-photo img {
width: 100%;
height: 100%;
min-height: 220px;
object-fit: cover;
object-position: top;
display: block;
}
.td-body {
flex: 1 1 auto;
padding: 18px 22px 18px 20px;
max-height: 340px;
overflow-y: auto;
}
.td-name {
display: block;
font-size: 1.15rem;
font-weight: 800;
color: var(--fitme-dark);
padding-right: 20px;
}
.td-title {
display: block;
font-size: .82rem;
font-weight: 700;
color: var(--fitme-accent-dark);
margin-bottom: .6rem;
}
.td-bio {
font-size: .88rem;
color: var(--fitme-text-soft);
margin-bottom: .6rem;
}
.td-bio p:last-child { margin-bottom: 0; }
.td-block + .td-block { margin-top: .55rem; }
.td-label {
display: block;
font-size: .68rem;
font-weight: 800;
letter-spacing: .14em;
text-transform: uppercase;
color: var(--fitme-text-muted);
margin-bottom: .25rem;
}
.td-block ul {
list-style: none;
padding: 0;
margin: 0;
}
.td-block li {
position: relative;
padding-left: 14px;
font-size: .87rem;
line-height: 1.45;
color: var(--fitme-text);
}
.td-block li:before {
content: '';
position: absolute;
left: 0;
top: .55em;
width: 6px;
height: 6px;
border-radius: 1px;
background: var(--fitme-accent);
}
.td-close {
position: absolute;
top: 6px;
right: 10px;
z-index: 2;
background: transparent;
border: 0;
font-size: 1.6rem;
line-height: 1;
color: var(--fitme-text-muted);
cursor: pointer;
display: none;
}
/* Touch / small screens: a centred fixed card over a dimmed page. */
@media (max-width: 767px), (hover: none) {
.trainer-detail {
position: fixed;
top: 50%;
left: 16px;
right: 16px;
width: auto;
max-width: 560px;
margin: 0 auto;
transform: translateY(-46%);
max-height: calc(100vh - 48px);
}
.trainer-item.is-open .trainer-detail { transform: translateY(-50%); }
.trainer-item.is-open:after {
content: '';
position: fixed;
inset: 0;
z-index: 29;
background: rgba(0, 0, 0, .55);
}
.td-close { display: block; }
.td-photo { flex-basis: 34%; }
.td-photo img { min-height: 180px; }
.td-body { max-height: calc(100vh - 48px); padding: 16px 16px 16px 14px; }
}
@media (max-width: 339px) {
.trainer-detail { flex-direction: column; }
.td-photo { max-width: none; flex-basis: auto; }
.td-photo img { min-height: 0; height: 160px; }
}
/* ══════════════════════════════════════════════════════════════════════════
Mensalidades — cartões de preço
══════════════════════════════════════════════════════════════════════════ */
.pricing-section {
padding: 90px 0 70px;
background: var(--fitme-surface);
}
.pricing-grid {
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: stretch;
gap: 24px;
}
.price-card {
position: relative;
flex: 0 1 270px;
display: flex;
flex-direction: column;
background: #fff;
border: 1px solid var(--fitme-surface-2);
border-radius: 6px;
padding: 30px 26px 26px;
box-shadow: var(--fitme-shadow);
transition: transform var(--fitme-transition), box-shadow var(--fitme-transition);
}
.price-card:hover {
transform: translateY(-4px);
box-shadow: var(--fitme-shadow-lg);
}
.price-card.is-featured {
background: var(--fitme-dark-2);
border: 2px solid var(--fitme-accent);
color: var(--fitme-ash);
box-shadow: 0 18px 50px rgba(var(--fitme-dark-rgb), .28);
}
@media (min-width: 992px) {
.price-card.is-featured { transform: scale(1.04); }
.price-card.is-featured:hover { transform: scale(1.04) translateY(-4px); }
}
.pc-badge {
position: absolute;
top: 0;
left: 50%;
transform: translate(-50%, -50%);
white-space: nowrap;
background: var(--fitme-accent);
color: var(--fitme-dark);
font-size: .72rem;
font-weight: 800;
letter-spacing: .12em;
text-transform: uppercase;
padding: 6px 14px;
border-radius: 999px;
}
.pc-badge i { font-size: .65rem; }
.price-card .pc-name {
font-size: 1.35rem;
font-weight: 900;
margin: 0 0 .35rem;
color: var(--fitme-dark);
}
.price-card.is-featured .pc-name { color: #fff; }
.pc-sub {
font-size: .9rem;
line-height: 1.45;
color: var(--fitme-text-muted);
margin: 0 0 1rem;
}
.price-card.is-featured .pc-sub { color: var(--fitme-ash); }
.pc-price {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 4px 8px;
padding: .9rem 0 1rem;
border-top: 1px solid var(--fitme-surface-2);
border-bottom: 1px solid var(--fitme-surface-2);
margin-bottom: 1rem;
}
.price-card.is-featured .pc-price { border-color: rgba(255, 255, 255, .12); }
.pc-amount {
font-size: 2.3rem;
font-weight: 900;
line-height: 1;
color: var(--fitme-dark);
}
.pc-amount.is-text { font-size: 1.35rem; }
.price-card.is-featured .pc-amount { color: var(--fitme-accent); }
.pc-suffix {
font-size: .88rem;
color: var(--fitme-text-muted);
}
.price-card.is-featured .pc-suffix { color: var(--fitme-ash); }
.pc-features {
list-style: none;
padding: 0;
margin: 0 0 1.4rem;
flex: 1 1 auto;
}
.pc-features li {
display: flex;
gap: 10px;
font-size: .92rem;
line-height: 1.4;
padding: 4px 0;
color: var(--fitme-text-soft);
}
.price-card.is-featured .pc-features li { color: #fff; }
.pc-features i {
color: var(--fitme-accent-dark);
margin-top: 3px;
font-size: .8rem;
}
.price-card.is-featured .pc-features i { color: var(--fitme-accent); }
.price-card .pc-cta {
width: 100%;
border: none;
margin-top: auto;
}
.price-card:not(.is-featured) .pc-cta {
background: var(--fitme-dark-2);
color: var(--fitme-accent);
}
.price-card:not(.is-featured) .pc-cta:hover {
background: var(--fitme-dark-3);
box-shadow: none;
}
@media (max-width: 575px) {
.pricing-section { padding: 60px 0 50px; }
.price-card { flex-basis: 100%; }
}
/* ══════════════════════════════════════════════════════════════════════════
Reviews Google
══════════════════════════════════════════════════════════════════════════ */
.reviews-section {
padding: 90px 0 60px;
background: var(--fitme-dark);
color: var(--fitme-ash);
}
.reviews-section .section-title h2 { color: #fff; }
.reviews-summary {
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
gap: 6px 12px;
margin: 1rem 0 0;
color: var(--fitme-ash);
}
.reviews-summary strong {
font-size: 1.8rem;
font-weight: 900;
color: #fff;
line-height: 1;
}
.rv-stars {
color: #FBBC04;
letter-spacing: 2px;
font-size: .95rem;
}
.reviews-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
gap: 22px;
}
.review-card {
display: flex;
flex-direction: column;
margin: 0;
background: var(--fitme-dark-2);
border: 1px solid var(--fitme-dark-3);
border-radius: 6px;
padding: 24px;
}
.rv-text {
flex: 1 1 auto;
margin: .8rem 0 1.2rem;
font-size: .95rem;
line-height: 1.6;
color: #fff;
display: -webkit-box;
-webkit-line-clamp: 7;
-webkit-box-orient: vertical;
overflow: hidden;
}
.rv-author {
display: flex;
align-items: center;
gap: 12px;
}
.rv-author img {
width: 40px;
height: 40px;
border-radius: 50%;
object-fit: cover;
}
.rv-author span {
display: flex;
flex-direction: column;
font-weight: 700;
color: #fff;
}
.rv-author a { color: #fff; }
.rv-author a:hover { color: var(--fitme-accent); }
.rv-author small {
font-weight: 400;
color: var(--fitme-ash);
}
.reviews-actions {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 12px;
margin-top: 2rem;
}
.reviews-section .site-btn.sb-line {
border-color: #fff;
color: #fff;
}
.reviews-section .site-btn.sb-line:hover {
background: #fff;
color: var(--fitme-dark);
}
.reviews-attribution {
margin: 1.2rem 0 0;
text-align: center;
font-size: .75rem;
color: var(--fitme-ash);
opacity: .8;
}
+78
View File
@@ -222,3 +222,81 @@ document.addEventListener('DOMContentLoaded', function () {
var t;
window.addEventListener('resize', function () { clearTimeout(t); t = setTimeout(sync, 150); }, { passive: true });
});
/* ── Equipa: horizontal detail card ─────────────────────────────────────────
Desktop (fine pointer) opens it on hover purely in CSS; this handles tap /
click / keyboard (.is-open, one at a time; Esc, the × and outside clicks
close) and nudges the absolutely-positioned card sideways (--td-shift) so an
edge column's card stays inside the viewport. On small / touch screens the
CSS turns it into a centred fixed card, so no shift is applied there. */
document.addEventListener('DOMContentLoaded', function () {
var items = document.querySelectorAll('.trainer-item.has-detail');
if (!items.length) return;
var floating = window.matchMedia('(max-width: 767px), (hover: none)');
function place(item) {
var card = item.querySelector('.trainer-detail');
if (!card) return;
card.style.setProperty('--td-shift', '0px');
if (floating.matches) return;
var r = card.getBoundingClientRect();
var itemR = item.getBoundingClientRect();
// Where the card would sit centred on the item (ignoring its current transform).
var left = itemR.left + itemR.width / 2 - r.width / 2;
var right = left + r.width;
var gutter = 16, vw = document.documentElement.clientWidth, shift = 0;
if (left < gutter) shift = gutter - left;
else if (right > vw - gutter) shift = (vw - gutter) - right;
card.style.setProperty('--td-shift', Math.round(shift) + 'px');
}
var section = document.getElementById('equipa');
function setOpen(item, open) {
item.classList.toggle('is-open', open);
item.setAttribute('aria-expanded', open ? 'true' : 'false');
if (section) section.classList.toggle('has-open-detail', !!section.querySelector('.trainer-item.is-open'));
}
function closeAll(except) {
items.forEach(function (it) { if (it !== except) setOpen(it, false); });
}
items.forEach(function (item) {
item.addEventListener('mouseenter', function () { place(item); });
item.addEventListener('focus', function () { place(item); });
item.addEventListener('click', function (e) {
e.stopPropagation();
if (e.target.closest('.td-close')) { setOpen(item, false); return; }
// Clicks inside an open card (e.g. scrolling / selecting text) keep it open.
if (e.target.closest('.trainer-detail') && item.classList.contains('is-open')) return;
// Tapping the dimmed backdrop (the item's ::after) closes it.
if (floating.matches && item.classList.contains('is-open') && !e.target.closest('.trainer-detail')) {
setOpen(item, false); return;
}
closeAll(item);
place(item);
setOpen(item, !item.classList.contains('is-open'));
});
item.addEventListener('keydown', function (e) {
if (e.key === 'Enter' || e.key === ' ' || e.key === 'Spacebar') {
if (e.target !== item) return;
e.preventDefault();
closeAll(item); place(item);
setOpen(item, !item.classList.contains('is-open'));
} else if (e.key === 'Escape') {
setOpen(item, false);
item.blur();
}
});
});
document.addEventListener('click', function () { closeAll(null); });
document.addEventListener('keydown', function (e) { if (e.key === 'Escape') closeAll(null); });
});
/* ── Mensalidades: pre-select the clicked card in the sign-up modal ───────── */
document.addEventListener('DOMContentLoaded', function () {
var select = document.querySelector('#joinModal select[name="membership_id"]');
if (!select) return;
document.querySelectorAll('[data-target="#joinModal"][data-membership]').forEach(function (btn) {
btn.addEventListener('click', function () { select.value = btn.getAttribute('data-membership'); });
});
});
+200 -6
View File
@@ -11,6 +11,8 @@ $modalidades = site_modalidades($pdo);
$horario = site_horario($pdo);
$whours = site_work_hours($pdo);
$events = site_active_events($pdo); // time-limited events, banner below the hero
$memberships = site_memberships($pdo);
$reviews = site_reviews(); // null when not configured / nothing qualifies
// ── Hero section ────────────────────────────────────────────────────────────────
?>
@@ -118,15 +120,46 @@ if ($team):
</div>
<div class="section-title text-center">
<div class="row auto-grid" id="powerRotation">
<?php foreach ($team as $d): if ($d['status'] == 'ativo'): ?>
<?php foreach ($team as $d): if ($d['status'] == 'ativo'):
// Default card: photo + name + title. The horizontal detail card
// (hover on desktop, tap on touch) only exists when there is
// something extra to show, so a bare member stays a plain card.
$t_title = trim((string) ($d['title'] ?? ''));
$t_skills = text_lines($d['skills'] ?? '');
$t_certs = text_lines($d['certifications'] ?? '');
$t_bio = trim(strip_tags((string) ($d['description'] ?? ''))) !== '' ? clean_richtext((string) $d['description']) : '';
$t_detail = $t_skills || $t_certs || $t_bio !== '';
$t_img = site_img_url($d['photo'], 'uploads/team/foto');
$t_id = 'td-' . (int) $d['id'];
?>
<div class="col-6 col-md-4 col-lg-3" style="margin-top: 20px;">
<div class="trainer-item">
<div class="trainer-item<?= $t_detail ? ' has-detail' : '' ?>"<?= $t_detail ? ' tabindex="0" role="button" aria-expanded="false" aria-controls="' . $t_id . '" aria-label="Ver detalhes de ' . htmlspecialchars((string) $d['name']) . '"' : '' ?>>
<div class="trainer-pic">
<img loading="lazy" src="<?= site_img_url($d['photo'], 'uploads/team/foto') ?>" alt="<?= htmlspecialchars((string) $d['name']) ?>">
<img loading="lazy" src="<?= $t_img ?>" alt="<?= htmlspecialchars((string) $d['name']) ?>">
</div>
<h4><?= htmlspecialchars((string) $d['name']) ?></h4>
<?php if ($t_title !== ''): ?><p class="trainer-title"><?= htmlspecialchars($t_title) ?></p><?php endif; ?>
<?php if ($t_detail): ?>
<span class="trainer-more" aria-hidden="true">Saber mais <i class="fas fa-plus"></i></span>
<div class="trainer-detail" id="<?= $t_id ?>">
<button type="button" class="td-close" aria-label="Fechar">&times;</button>
<div class="td-photo"><img loading="lazy" src="<?= $t_img ?>" alt=""></div>
<div class="td-body">
<strong class="td-name"><?= htmlspecialchars((string) $d['name']) ?></strong>
<?php if ($t_title !== ''): ?><span class="td-title"><?= htmlspecialchars($t_title) ?></span><?php endif; ?>
<?php if ($t_bio !== ''): ?><div class="td-bio"><?= $t_bio ?></div><?php endif; ?>
<?php if ($t_skills): ?>
<div class="td-block"><span class="td-label">Aptidões / Funções</span>
<ul><?php foreach ($t_skills as $x): ?><li><?= htmlspecialchars($x) ?></li><?php endforeach; ?></ul></div>
<?php endif; ?>
<?php if ($t_certs): ?>
<div class="td-block"><span class="td-label">Formações</span>
<ul><?php foreach ($t_certs as $x): ?><li><?= htmlspecialchars($x) ?></li><?php endforeach; ?></ul></div>
<?php endif; ?>
</div>
</div>
<?php endif; ?>
</div>
<?= htmlspecialchars((string) $d['description']) ?>
</div>
<?php endif; endforeach; ?>
</div>
@@ -387,6 +420,108 @@ if (!in_array($default_day, $week_values, true)) { $default_day = $week_values[0
</script>
<?php endif; ?>
<?php
// ── Mensalidades ────────────────────────────────────────────────────────────────
// Cards come from the backoffice (Gestão → Mensalidades); one may be featured.
// "Inscrever" opens #joinModal pre-set to that card (site/inscricao.php stores
// the request as a lead and emails the gym).
if ($memberships):
?>
<section id="mensalidades" class="pricing-section">
<div class="container">
<div class="row justify-content-md-center mb-4">
<div class="col-lg-8">
<div class="section-title text-center deco">
<span class="section-eyebrow">Mensalidades</span>
<h2>Escolhe o teu plano</h2>
<p class="section-subtitle">Encontra a mensalidade que encaixa na tua rotina.</p>
</div>
</div>
</div>
<?php if (($_GET['inscricao'] ?? '') === 'ok'): ?>
<div class="alert alert-success text-center" role="alert">Pedido de inscrição enviado! Vamos entrar em contacto contigo muito em breve.</div>
<?php elseif (($_GET['inscricao'] ?? '') === 'erro'): ?>
<div class="alert alert-danger text-center" role="alert">Não foi possível enviar o pedido. Verifica os dados e tenta novamente.</div>
<?php endif; ?>
<div class="pricing-grid">
<?php foreach ($memberships as $m): $features = text_lines($m['features']); ?>
<article class="price-card<?= $m['is_featured'] ? ' is-featured' : '' ?>">
<?php if ($m['is_featured']): ?><span class="pc-badge"><i class="fas fa-star"></i> <?= htmlspecialchars($m['featured_label']) ?></span><?php endif; ?>
<h3 class="pc-name"><?= htmlspecialchars($m['name']) ?></h3>
<?php if ($m['subtitle'] !== ''): ?><p class="pc-sub"><?= htmlspecialchars($m['subtitle']) ?></p><?php endif; ?>
<div class="pc-price">
<span class="pc-amount<?= $m['price'] === null ? ' is-text' : '' ?>"><?= htmlspecialchars(membership_price_label($m)) ?></span>
<?php if ($m['price'] !== null && $m['price_suffix'] !== ''): ?><span class="pc-suffix"><?= htmlspecialchars($m['price_suffix']) ?></span><?php endif; ?>
</div>
<?php if ($features): ?>
<ul class="pc-features">
<?php foreach ($features as $f): ?><li><i class="fas fa-check" aria-hidden="true"></i><?= htmlspecialchars($f) ?></li><?php endforeach; ?>
</ul>
<?php endif; ?>
<button type="button" class="site-btn pc-cta" data-toggle="modal" data-target="#joinModal"
data-membership="<?= (int) $m['id'] ?>"><?= htmlspecialchars($m['cta_label']) ?></button>
</article>
<?php endforeach; ?>
</div>
</div>
</section>
<?php endif; ?>
<?php
// ── Reviews Google ──────────────────────────────────────────────────────────────
// Live from the Places API (functions_reviews.php), cached; only reviews at or
// above the backoffice minimum rating. Hidden when nothing qualifies.
if ($reviews):
$stars = static function (float $r): string {
$out = '';
for ($i = 1; $i <= 5; $i++) {
$cls = $r >= $i ? 'fas fa-star' : ($r >= $i - 0.5 ? 'fas fa-star-half-alt' : 'far fa-star');
$out .= '<i class="' . $cls . '" aria-hidden="true"></i>';
}
return $out;
};
?>
<section id="reviews" class="reviews-section">
<div class="container">
<div class="row justify-content-md-center mb-4">
<div class="col-lg-8">
<div class="section-title text-center deco">
<span class="section-eyebrow">Reviews</span>
<h2>O que dizem de nós</h2>
<?php if ($reviews['rating'] !== null): ?>
<p class="reviews-summary">
<strong><?= number_format((float) $reviews['rating'], 1, ',', '') ?></strong>
<span class="rv-stars" role="img" aria-label="<?= number_format((float) $reviews['rating'], 1, ',', '') ?> de 5 estrelas"><?= $stars((float) $reviews['rating']) ?></span>
<span><?= (int) $reviews['total'] ?> avaliações no Google</span>
</p>
<?php endif; ?>
</div>
</div>
</div>
<div class="reviews-grid">
<?php foreach ($reviews['reviews'] as $r): ?>
<figure class="review-card">
<div class="rv-stars" role="img" aria-label="<?= (int) $r['rating'] ?> de 5 estrelas"><?= $stars((float) $r['rating']) ?></div>
<blockquote class="rv-text"><?= nl2br(htmlspecialchars($r['text'])) ?></blockquote>
<figcaption class="rv-author">
<?php if ($r['author_photo'] !== ''): ?><img src="<?= htmlspecialchars($r['author_photo']) ?>" alt="" loading="lazy" referrerpolicy="no-referrer" width="40" height="40"><?php endif; ?>
<span>
<?php if ($r['author_uri'] !== ''): ?><a href="<?= htmlspecialchars($r['author_uri']) ?>" target="_blank" rel="noopener nofollow"><?= htmlspecialchars($r['author']) ?></a><?php else: ?><?= htmlspecialchars($r['author']) ?><?php endif; ?>
<small><?= htmlspecialchars($r['relative']) ?></small>
</span>
</figcaption>
</figure>
<?php endforeach; ?>
</div>
<div class="reviews-actions">
<?php if ($reviews['maps_uri'] !== ''): ?><a class="site-btn sb-line" href="<?= htmlspecialchars($reviews['maps_uri']) ?>" target="_blank" rel="noopener">Ver todas no Google</a><?php endif; ?>
<a class="site-btn" href="<?= htmlspecialchars($reviews['write_uri']) ?>" target="_blank" rel="noopener">Deixa a tua review</a>
</div>
<p class="reviews-attribution">Reviews via Google Maps</p>
</div>
</section>
<?php endif; ?>
<?php
// ── Contactos + Horário de Funcionamento + Mapa ────────────────────────────────
$assunto = '';
@@ -436,9 +571,11 @@ $session = session();
<a href="tel:<?= htmlspecialchars(str_replace(' ', '', $info['phone'] ?? '')) ?>">
<p><?= htmlspecialchars($info['phone'] ?? '') ?></p>
</a>
<a href="tel:<?= htmlspecialchars(str_replace(' ', '', $info['telephone'] ?? '')) ?>">
<p><?= htmlspecialchars($info['telephone'] ?? '') ?></p>
<?php if (($info['telephone'] ?? '') !== ''): ?>
<a href="tel:<?= htmlspecialchars(str_replace(' ', '', $info['telephone'])) ?>">
<p><?= htmlspecialchars($info['telephone']) ?></p>
</a>
<?php endif; ?>
</div>
</div>
</div>
@@ -618,6 +755,63 @@ $work_hours_days = ['Segunda-Sexta'=>'segunda','Sábado'=>'sabado','Domingo/Feri
<script>document.addEventListener('DOMContentLoaded',function(){if(window.jQuery){jQuery('#trialModal').modal('show');}});</script>
<?php endif; ?>
<?php
// ── Inscrição (mensalidades) modal ──────────────────────────────────────────
// The select is pre-set by main.js from the clicked card's data-membership;
// without JS it still works as a plain chooser.
if ($memberships):
?>
<div class="modal fade trial-modal-wrap" id="joinModal" tabindex="-1" role="dialog" aria-labelledby="joinModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content trial-modal">
<div class="trial-modal-head">
<span class="section-eyebrow"><?= htmlspecialchars($info['name'] !== '' ? $info['name'] : APP_NAME) ?></span>
<h3 id="joinModalLabel">Inscreve-te</h3>
<p>Deixa os teus contactos e entramos em contacto para concluir a inscrição.</p>
<button type="button" class="trial-close" data-dismiss="modal" aria-label="Fechar">&times;</button>
</div>
<form class="trial-form" method="post" action="<?= base_url('home/inscricao') ?>">
<?= csrf_field() ?>
<input type="text" name="website" class="event-hp" tabindex="-1" autocomplete="off" aria-hidden="true">
<div class="form-row">
<div class="col-12 mb-3">
<select name="membership_id" aria-label="Mensalidade" required>
<?php foreach ($memberships as $m): ?>
<option value="<?= (int) $m['id'] ?>"<?= $m['is_featured'] ? ' selected' : '' ?>><?= htmlspecialchars($m['name'] . ' — ' . membership_price_label($m)) ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="col-12 col-md-6 mb-3">
<input type="text" name="nome" required maxlength="150" placeholder="Nome *" aria-label="Nome">
</div>
<div class="col-12 col-md-6 mb-3">
<input type="tel" name="telefone" required maxlength="40" placeholder="Telemóvel *" aria-label="Telemóvel">
</div>
<div class="col-12 mb-3">
<input type="email" name="email" maxlength="190" placeholder="E-mail" aria-label="E-mail">
</div>
<div class="col-12 mb-3">
<textarea name="mensagem" rows="3" maxlength="1000" placeholder="Alguma dúvida ou objetivo? (opcional)" aria-label="Mensagem"></textarea>
</div>
<div class="col-12">
<label class="consent-check">
<input type="checkbox" name="consent" value="1" required>
<span>Autorizo o contacto e o tratamento dos meus dados para efeitos desta inscrição, nos termos da <a href="<?= base_url('home/privacidade') ?>" target="_blank" rel="noopener">Política de Privacidade</a>.</span>
</label>
</div>
<div class="col-12">
<button type="submit" class="site-btn w-100">Enviar pedido</button>
</div>
</div>
</form>
</div>
</div>
</div>
<?php if (($_GET['inscricao'] ?? '') === 'erro'): ?>
<script>document.addEventListener('DOMContentLoaded',function(){if(window.jQuery){jQuery('#joinModal').modal('show');}});</script>
<?php endif; ?>
<?php endif; ?>
<?php
// ── Newsletter + Footer ───────────────────────────────────────────────────────
echo view('newsletter');
+93
View File
@@ -0,0 +1,93 @@
<?php
// POST handler for the membership "Inscrever" modal on the homepage.
// Stores the request in membership_leads (backoffice: Mensalidades → Pedidos de
// inscrição), emails the gym like the trial-class modal does, then redirects
// back to #mensalidades with ?inscricao=ok|erro for the homepage to render.
// The lead is saved before the email is attempted, so a mail failure never
// loses a request.
//
// Reached via .htaccess: ^home/inscricao/?$ → site/inscricao.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/functions.php';
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
header('Location: ' . base_url('home#mensalidades'));
exit;
}
csrf_check(); // 403s and exits on a bad/missing token
function inscricao_redirect(string $status): void {
header('Location: ' . base_url('home?inscricao=' . $status . '#mensalidades'));
exit;
}
// Honeypot: a filled "website" field means a bot — pretend success, store nothing.
if (trim((string) ($_POST['website'] ?? '')) !== '') inscricao_redirect('ok');
$consent_text = 'Autorizo o contacto e o tratamento dos meus dados para efeitos desta inscrição, nos termos da Política de Privacidade.';
$membership = db_memberships_get($pdo, (int) ($_POST['membership_id'] ?? 0));
if ($membership && ($membership['deleted_at'] !== null || !$membership['is_active'])) $membership = null;
$lead = [
'membership_id' => $membership ? (int) $membership['id'] : null,
'membership_name' => $membership ? $membership['name'] : '',
'name' => trim((string) ($_POST['nome'] ?? '')),
'phone' => trim((string) ($_POST['telefone'] ?? '')),
'email' => trim((string) ($_POST['email'] ?? '')),
'message' => trim((string) ($_POST['mensagem'] ?? '')),
'consent' => !empty($_POST['consent']) ? 1 : 0,
'consent_text' => $consent_text,
// First hop of X-Forwarded-For (behind the reverse proxy), else peer.
'ip' => trim(explode(',', (string) ($_SERVER['HTTP_X_FORWARDED_FOR'] ?? ''))[0]) ?: ($_SERVER['REMOTE_ADDR'] ?? ''),
'user_agent' => (string) ($_SERVER['HTTP_USER_AGENT'] ?? ''),
];
if ($lead['name'] === '' || $lead['phone'] === '' || !$lead['consent']
|| ($lead['email'] !== '' && !filter_var($lead['email'], FILTER_VALIDATE_EMAIL))) {
inscricao_redirect('erro');
}
try {
db_membership_lead_create($pdo, $lead);
} catch (Throwable $e) {
error_log('[inscricao] ' . $e->getMessage());
inscricao_redirect('erro');
}
// Notify the gym. Best effort: the request is already stored.
try {
$info = site_info($pdo);
$to = $info['email'] !== '' ? $info['email'] : EMAIL_FROM;
$e = static fn($v) => htmlspecialchars((string) $v, ENT_QUOTES, 'UTF-8');
$rows = [
'Mensalidade' => $lead['membership_name'],
'Nome' => $lead['name'],
'Telemóvel' => $lead['phone'],
'E-mail' => $lead['email'],
'Mensagem' => $lead['message'],
];
$body = '<h2 style="margin:0 0 16px;">Novo pedido de inscrição</h2><table cellpadding="6" style="border-collapse:collapse;font-family:Arial,sans-serif;font-size:14px;">';
$alt = "Novo pedido de inscrição\n\n";
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>';
$alt .= "$label: $value\n";
}
$body .= '</table><p style="font-family:Arial,sans-serif;font-size:13px;color:#666;margin-top:18px;">'
. 'Pedido guardado no backoffice (Mensalidades → Pedidos de inscrição).</p>';
$id = enqueue_email([
'to_address' => $to,
'to_name' => $info['name'] !== '' ? $info['name'] : APP_NAME,
'subject' => 'Pedido de inscrição' . ($lead['membership_name'] !== '' ? ' (' . $lead['membership_name'] . ')' : '') . ' — ' . $lead['name'],
'body' => $body,
'alt_body' => $alt,
'context_type' => 'fitme_inscricao',
]);
flush_message($id);
} catch (Throwable $e) {
error_log('[inscricao] email: ' . $e->getMessage());
}
inscricao_redirect('ok');
+28
View File
@@ -7,6 +7,7 @@ $user = require_admin();
$counts = [
'clientes' => (int) $pdo->query("SELECT COUNT(*) FROM users WHERE role = 'client'")->fetchColumn(),
'equipa' => (int) $pdo->query("SELECT COUNT(*) FROM users WHERE role IN ('admin','staff')")->fetchColumn(),
'leads_novos' => db_membership_leads_count_new($pdo),
];
$page_title = 'Painel';
@@ -81,6 +82,33 @@ include __DIR__ . '/../../includes/header.php';
</div>
</a>
</div>
<div class="col-sm-6 col-lg-4">
<a class="card text-decoration-none border-primary shadow-sm h-100" href="<?= base_url('views/admin/memberships/index.php') ?>">
<div class="card-body">
<i class="bi bi-credit-card-2-front-fill fs-3 text-primary mb-2 d-block"></i>
<strong>Mensalidades</strong><?php if ($counts['leads_novos']): ?> <span class="badge bg-danger"><?= $counts['leads_novos'] ?> novo<?= $counts['leads_novos'] > 1 ? 's' : '' ?></span><?php endif; ?>
<p class="text-muted small mb-0">Cartões de preço e pedidos de inscrição</p>
</div>
</a>
</div>
<div class="col-sm-6 col-lg-4">
<a class="card text-decoration-none border-primary shadow-sm h-100" href="<?= base_url('views/admin/reviews/index.php') ?>">
<div class="card-body">
<i class="bi bi-star-fill fs-3 text-primary mb-2 d-block"></i>
<strong>Reviews Google</strong>
<p class="text-muted small mb-0">Reviews do Google na página inicial</p>
</div>
</a>
</div>
<div class="col-sm-6 col-lg-4">
<a class="card text-decoration-none border-primary shadow-sm h-100" href="<?= base_url('views/admin/info/edit.php') ?>">
<div class="card-body">
<i class="bi bi-telephone-fill fs-3 text-primary mb-2 d-block"></i>
<strong>Contactos</strong>
<p class="text-muted small mb-0">Telefone, e-mail, morada e redes sociais</p>
</div>
</a>
</div>
</div>
</div></div>
+52
View File
@@ -0,0 +1,52 @@
<?php
require __DIR__ . '/../../../config/db.php';
require __DIR__ . '/../../../config/functions.php';
$user = require_admin();
$errors = [];
$data = site_info($pdo);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
csrf_check();
$data = info_from_post($_POST, $errors);
if (!$errors) {
$changed = db_info_save($pdo, $data);
session()->setFlashdata($changed ? 'success' : 'warning', $changed ? 'Contactos atualizados.' : 'Nenhuma alteração.');
header('Location: ' . base_url('views/admin/info/edit.php'));
exit;
}
}
$page_title = 'Contactos';
include __DIR__ . '/../../../includes/header.php';
?>
<div class="container" style="max-width:800px;">
<div class="d-flex justify-content-between align-items-center mb-4">
<h1 class="h3 mb-0">Contactos</h1>
<a class="btn btn-outline-secondary btn-sm" href="<?= base_url('home#contactos') ?>" target="_blank" rel="noopener"><i class="bi bi-box-arrow-up-right me-1"></i>Ver no site</a>
</div>
<p class="text-muted small">Estes dados alimentam a secção de contactos, o rodapé, o botão «Ligar» no telemóvel, o botão de WhatsApp e os dados para o Google (SEO). Campos vazios não aparecem no site.</p>
<?php foreach ($errors as $e): ?><div class="alert alert-danger"><?= htmlspecialchars($e) ?></div><?php endforeach; ?>
<form method="POST" class="card shadow-sm"><div class="card-body">
<?= csrf_field() ?>
<div class="row g-3">
<?php foreach (info_fields() as $key => [$label, $max, $type]): $req = in_array($key, ['name', 'phone'], true); ?>
<?php if ($type === 'textarea'): ?>
<div class="col-12"><label class="form-label" for="f_<?= $key ?>"><?= htmlspecialchars($label) ?></label>
<textarea class="form-control font-monospace small" id="f_<?= $key ?>" name="<?= $key ?>" rows="4"><?= htmlspecialchars((string) ($data[$key] ?? '')) ?></textarea>
<div class="form-text">No Google Maps: Partilhar → Incorporar um mapa → Copiar HTML. Só é aceite um iframe do Google Maps.</div></div>
<?php else: ?>
<div class="col-md-6"><label class="form-label" for="f_<?= $key ?>"><?= htmlspecialchars($label) ?><?= $req ? ' <span class="text-danger">*</span>' : '' ?></label>
<input class="form-control" id="f_<?= $key ?>" type="<?= $type ?>" name="<?= $key ?>"<?= $max ? ' maxlength="' . $max . '"' : '' ?><?= $req ? ' required' : '' ?>
value="<?= htmlspecialchars((string) ($data[$key] ?? '')) ?>"></div>
<?php endif; ?>
<?php endforeach; ?>
</div>
<div class="mt-4 d-flex gap-2">
<button type="submit" class="btn btn-primary">Guardar</button>
<a class="btn btn-outline-secondary" href="<?= base_url('views/admin/dashboard.php') ?>">Cancelar</a>
</div>
</div></form>
</div>
<?php include __DIR__ . '/../../../includes/footer.php'; ?>
+63
View File
@@ -0,0 +1,63 @@
<?php
// Shared membership form fields, rendered inside the <form> of create.php and
// edit.php. Expects $data (see memberships_defaults()).
$price_val = ($data['price'] ?? '') === null ? '' : (string) ($data['price'] ?? '');
if ($price_val !== '' && is_numeric($price_val)) {
$p = (float) $price_val;
$price_val = number_format($p, floor($p) == $p ? 0 : 2, ',', '');
}
?>
<div class="row g-3">
<div class="col-md-8">
<label class="form-label">Nome <span class="text-danger">*</span></label>
<input class="form-control" name="name" required maxlength="100" placeholder="ex.: Off-hours" value="<?= htmlspecialchars($data['name'] ?? '') ?>">
</div>
<div class="col-md-4">
<label class="form-label">Ordem</label>
<input type="number" class="form-control" name="item_order" value="<?= (int) ($data['item_order'] ?? 0) ?>">
<div class="form-text">Menor aparece primeiro.</div>
</div>
<div class="col-12">
<label class="form-label">Descrição curta</label>
<input class="form-control" name="subtitle" maxlength="255" placeholder="ex.: Mensalidade para as horas baixas do ginásio." value="<?= htmlspecialchars($data['subtitle'] ?? '') ?>">
</div>
<div class="col-md-4">
<label class="form-label">Preço (€)</label>
<input class="form-control" name="price" inputmode="decimal" placeholder="ex.: 34,90" value="<?= htmlspecialchars($price_val) ?>">
<div class="form-text">Vazio = «Sob consulta».</div>
</div>
<div class="col-md-5">
<label class="form-label">Texto do preço</label>
<input class="form-control" name="price_suffix" maxlength="60" placeholder="/mês" value="<?= htmlspecialchars($data['price_suffix'] ?? '') ?>">
<div class="form-text">ex.: «/mês» ou «acresce à mensalidade».</div>
</div>
<div class="col-md-3 d-flex align-items-center">
<div class="form-check mt-3">
<input class="form-check-input" type="checkbox" name="is_addon" id="is_addon" value="1" <?= !empty($data['is_addon']) ? 'checked' : '' ?>>
<label class="form-check-label" for="is_addon">Acresce à mensalidade <span class="text-muted small">(mostra «+»)</span></label>
</div>
</div>
<div class="col-12">
<label class="form-label">Incluído</label>
<textarea class="form-control" name="features" rows="5" placeholder="Um ponto por linha"><?= htmlspecialchars($data['features'] ?? '') ?></textarea>
</div>
<div class="col-md-4">
<label class="form-label">Texto do botão</label>
<input class="form-control" name="cta_label" maxlength="40" value="<?= htmlspecialchars($data['cta_label'] ?? 'Inscrever') ?>">
</div>
<div class="col-md-4">
<label class="form-label">Selo do destaque</label>
<input class="form-control" name="featured_label" maxlength="40" value="<?= htmlspecialchars($data['featured_label'] ?? 'Mais popular') ?>">
</div>
<div class="col-md-4 d-flex flex-column justify-content-end gap-1">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="is_featured" id="is_featured" value="1" <?= !empty($data['is_featured']) ? 'checked' : '' ?>>
<label class="form-check-label" for="is_featured">Em destaque</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" name="is_active" id="is_active" value="1" <?= !empty($data['is_active']) ? 'checked' : '' ?>>
<label class="form-check-label" for="is_active">Visível no site</label>
</div>
</div>
<div class="col-12"><div class="form-text mt-0">Só um cartão pode estar em destaque — ao marcar este, o anterior deixa de estar.</div></div>
</div>
+38
View File
@@ -0,0 +1,38 @@
<?php
require __DIR__ . '/../../../config/db.php';
require __DIR__ . '/../../../config/functions.php';
$user = require_admin();
$errors = [];
$data = memberships_defaults();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
csrf_check();
$data = memberships_from_post($_POST, $errors);
if (!$errors) {
db_memberships_create($pdo, $data);
session()->setFlashdata('success', 'Mensalidade criada.');
header('Location: ' . base_url('views/admin/memberships/index.php'));
exit;
}
}
$page_title = 'Nova Mensalidade';
include __DIR__ . '/../../../includes/header.php';
?>
<div class="container" style="max-width:800px;">
<div class="d-flex justify-content-between align-items-center mb-4">
<h1 class="h3 mb-0">Nova Mensalidade</h1>
<a class="btn btn-outline-secondary btn-sm" href="index.php"><i class="bi bi-arrow-left me-1"></i>Voltar</a>
</div>
<?php foreach ($errors as $e): ?><div class="alert alert-danger"><?= htmlspecialchars($e) ?></div><?php endforeach; ?>
<form method="POST" class="card shadow-sm"><div class="card-body">
<?= csrf_field() ?>
<?php include __DIR__ . '/_form.php'; ?>
<div class="mt-4 d-flex gap-2">
<button type="submit" class="btn btn-primary">Criar</button>
<a class="btn btn-outline-secondary" href="index.php">Cancelar</a>
</div>
</div></form>
</div>
<?php include __DIR__ . '/../../../includes/footer.php'; ?>
+42
View File
@@ -0,0 +1,42 @@
<?php
require __DIR__ . '/../../../config/db.php';
require __DIR__ . '/../../../config/functions.php';
$user = require_admin();
$id = (int) ($_GET['id'] ?? 0);
$item = $id ? db_memberships_get($pdo, $id) : null;
if (!$item) { header('Location: index.php'); exit; }
$errors = [];
$data = $item;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
csrf_check();
$data = memberships_from_post($_POST, $errors);
if (!$errors) {
$changed = db_memberships_update($pdo, $id, $data);
session()->setFlashdata($changed ? 'success' : 'warning', $changed ? 'Mensalidade atualizada.' : 'Nenhuma alteração.');
header('Location: ' . base_url('views/admin/memberships/edit.php?id=' . $id));
exit;
}
}
$page_title = 'Editar Mensalidade';
include __DIR__ . '/../../../includes/header.php';
?>
<div class="container" style="max-width:800px;">
<div class="d-flex justify-content-between align-items-center mb-4">
<h1 class="h3 mb-0">Editar Mensalidade</h1>
<a class="btn btn-outline-secondary btn-sm" href="index.php"><i class="bi bi-arrow-left me-1"></i>Voltar</a>
</div>
<?php foreach ($errors as $e): ?><div class="alert alert-danger"><?= htmlspecialchars($e) ?></div><?php endforeach; ?>
<form method="POST" class="card shadow-sm"><div class="card-body">
<?= csrf_field() ?>
<?php include __DIR__ . '/_form.php'; ?>
<div class="mt-4 d-flex gap-2">
<button type="submit" class="btn btn-primary">Atualizar</button>
<a class="btn btn-outline-secondary" href="index.php">Cancelar</a>
</div>
</div></form>
</div>
<?php include __DIR__ . '/../../../includes/footer.php'; ?>
+70
View File
@@ -0,0 +1,70 @@
<?php
require __DIR__ . '/../../../config/db.php';
require __DIR__ . '/../../../config/functions.php';
$user = require_admin();
// Delete / restore are POST + CSRF (csrf_check() only guards POST).
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
csrf_check();
if (isset($_POST['delete'])) {
db_memberships_delete($pdo, (int) $_POST['delete']);
session()->setFlashdata('success', 'Mensalidade apagada.');
} elseif (isset($_POST['restore'])) {
db_memberships_restore($pdo, (int) $_POST['restore']);
session()->setFlashdata('success', 'Mensalidade restaurada.');
}
header('Location: ' . base_url('views/admin/memberships/index.php'));
exit;
}
$items = db_memberships_list($pdo, true);
$new_leads = db_membership_leads_count_new($pdo);
$page_title = 'Mensalidades';
include __DIR__ . '/../../../includes/header.php';
?>
<div class="container">
<div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-4">
<h1 class="h3 mb-0">Mensalidades</h1>
<div class="d-flex gap-2">
<a class="btn btn-outline-primary" href="<?= base_url('views/admin/memberships/leads.php') ?>">
<i class="bi bi-inbox me-1"></i>Pedidos de inscrição<?php if ($new_leads): ?> <span class="badge bg-danger"><?= $new_leads ?></span><?php endif; ?>
</a>
<a class="btn btn-primary" href="<?= base_url('views/admin/memberships/create.php') ?>"><i class="bi bi-plus-lg me-1"></i>Adicionar</a>
</div>
</div>
<div class="card shadow-sm"><div class="card-body p-0">
<form method="POST" class="mb-0"><?= csrf_field() ?>
<table class="table table-hover align-middle mb-0">
<thead class="table-light"><tr>
<th>Nome</th><th>Preço</th><th>Estado</th><th>Ordem</th><th style="width:120px">Ações</th>
</tr></thead>
<tbody>
<?php if (!$items): ?>
<tr><td colspan="5" class="text-center text-muted py-4">Nenhuma mensalidade.</td></tr>
<?php else: foreach ($items as $m): $deleted = $m['deleted_at'] !== null; ?>
<tr class="<?= $deleted ? 'text-muted' : '' ?>">
<td><strong><?= htmlspecialchars($m['name']) ?></strong>
<?php if ($m['is_featured']): ?><span class="badge bg-warning text-dark ms-1"><i class="bi bi-star-fill"></i> Destaque</span><?php endif; ?>
<?php if ($m['subtitle'] !== ''): ?><div class="small text-muted"><?= htmlspecialchars($m['subtitle']) ?></div><?php endif; ?></td>
<td class="text-nowrap"><?= htmlspecialchars(membership_price_label($m)) ?> <span class="small text-muted"><?= htmlspecialchars($m['price_suffix']) ?></span></td>
<td><?php if ($deleted): ?><span class="badge bg-secondary">Apagada</span>
<?php elseif ($m['is_active']): ?><span class="badge bg-success">Visível</span>
<?php else: ?><span class="badge bg-light text-dark border">Oculta</span><?php endif; ?></td>
<td><?= (int) $m['item_order'] ?></td>
<td class="text-nowrap">
<?php if ($deleted): ?>
<button class="btn btn-sm btn-outline-info" name="restore" value="<?= (int) $m['id'] ?>">Restaurar</button>
<?php else: ?>
<a class="btn btn-sm btn-outline-primary" href="edit.php?id=<?= (int) $m['id'] ?>"><i class="bi bi-pencil"></i></a>
<button class="btn btn-sm btn-outline-danger" name="delete" value="<?= (int) $m['id'] ?>" onclick="return confirm('Apagar esta mensalidade?')"><i class="bi bi-trash"></i></button>
<?php endif; ?>
</td>
</tr>
<?php endforeach; endif; ?>
</tbody>
</table>
</form>
</div></div>
</div>
<?php include __DIR__ . '/../../../includes/footer.php';
+105
View File
@@ -0,0 +1,105 @@
<?php
require __DIR__ . '/../../../config/db.php';
require __DIR__ . '/../../../config/functions.php';
$user = require_admin();
$statuses = membership_lead_statuses();
$filter = (string) ($_GET['status'] ?? '');
if (!isset($statuses[$filter])) $filter = '';
$self = base_url('views/admin/memberships/leads.php' . ($filter !== '' ? '?status=' . $filter : ''));
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
csrf_check();
if (isset($_POST['delete'])) {
db_membership_lead_delete($pdo, (int) $_POST['delete']);
session()->setFlashdata('success', 'Pedido apagado.');
} elseif (isset($_POST['save'])) {
$id = (int) $_POST['save'];
db_membership_lead_update($pdo, $id, (string) ($_POST['status'][$id] ?? ''), trim((string) ($_POST['notes'][$id] ?? '')));
session()->setFlashdata('success', 'Pedido atualizado.');
}
header('Location: ' . $self);
exit;
}
$leads = db_membership_leads_list($pdo, $filter);
// CSV export of the current filter (Excel-friendly: UTF-8 BOM + ';').
if (isset($_GET['csv'])) {
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="pedidos-inscricao-' . date('Y-m-d') . '.csv"');
$out = fopen('php://output', 'w');
fwrite($out, "\xEF\xBB\xBF");
fputcsv($out, ['Data', 'Mensalidade', 'Nome', 'Telemóvel', 'E-mail', 'Mensagem', 'Estado', 'Notas', 'Consentimento'], ';', '"', '');
foreach ($leads as $l) {
fputcsv($out, [$l['created_at'], $l['membership_name'], $l['name'], $l['phone'], $l['email'], $l['message'],
$statuses[$l['status']] ?? $l['status'], (string) $l['admin_notes'], $l['consent'] ? 'sim' : 'não'], ';', '"', '');
}
exit;
}
$badge = ['novo' => 'bg-danger', 'contactado' => 'bg-info text-dark', 'inscrito' => 'bg-success', 'descartado' => 'bg-secondary'];
$page_title = 'Pedidos de inscrição';
include __DIR__ . '/../../../includes/header.php';
?>
<div class="container">
<div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3">
<h1 class="h3 mb-0">Pedidos de inscrição</h1>
<div class="d-flex gap-2">
<a class="btn btn-outline-secondary" href="<?= $self . ($filter !== '' ? '&' : '?') ?>csv=1"><i class="bi bi-filetype-csv me-1"></i>Exportar CSV</a>
<a class="btn btn-outline-secondary" href="<?= base_url('views/admin/memberships/index.php') ?>"><i class="bi bi-arrow-left me-1"></i>Mensalidades</a>
</div>
</div>
<p class="text-muted small">Pedidos enviados pelo botão de inscrição dos cartões de mensalidade. Cada pedido também é enviado por e-mail para o endereço dos Contactos.</p>
<ul class="nav nav-pills mb-3">
<li class="nav-item"><a class="nav-link<?= $filter === '' ? ' active' : '' ?>" href="?">Todos</a></li>
<?php foreach ($statuses as $k => $label): ?>
<li class="nav-item"><a class="nav-link<?= $filter === $k ? ' active' : '' ?>" href="?status=<?= $k ?>"><?= $label ?></a></li>
<?php endforeach; ?>
</ul>
<form method="POST" class="card shadow-sm"><div class="card-body p-0">
<?= csrf_field() ?>
<div class="table-responsive">
<table class="table align-middle mb-0">
<thead class="table-light"><tr>
<th>Data</th><th>Mensalidade</th><th>Contacto</th><th>Mensagem</th><th style="min-width:220px">Estado / notas</th><th></th>
</tr></thead>
<tbody>
<?php if (!$leads): ?>
<tr><td colspan="6" class="text-center text-muted py-4">Sem pedidos.</td></tr>
<?php else: foreach ($leads as $l): $id = (int) $l['id']; ?>
<tr>
<td class="small text-nowrap"><?= htmlspecialchars(date('d/m/Y H:i', strtotime($l['created_at']))) ?></td>
<td><?= htmlspecialchars($l['membership_name'] !== '' ? $l['membership_name'] : '—') ?></td>
<td class="small">
<strong><?= htmlspecialchars($l['name']) ?></strong>
<?php if ($l['phone'] !== ''): ?><div><a href="tel:<?= htmlspecialchars(preg_replace('/\s+/', '', $l['phone'])) ?>"><?= htmlspecialchars($l['phone']) ?></a></div><?php endif; ?>
<?php if ($l['email'] !== ''): ?><div><a href="mailto:<?= htmlspecialchars($l['email']) ?>"><?= htmlspecialchars($l['email']) ?></a></div><?php endif; ?>
<?php if ($l['consent']): ?><span class="badge bg-success mt-1" title="<?= htmlspecialchars($l['consent_text'] . ' · IP ' . $l['ip']) ?>">RGPD <i class="bi bi-check-lg"></i></span><?php endif; ?>
</td>
<td class="small" style="max-width:260px;"><?= $l['message'] !== '' ? nl2br(htmlspecialchars($l['message'])) : '<span class="text-muted">—</span>' ?></td>
<td>
<div class="d-flex gap-1 mb-1">
<select class="form-select form-select-sm" name="status[<?= $id ?>]">
<?php foreach ($statuses as $k => $label): ?>
<option value="<?= $k ?>" <?= $l['status'] === $k ? 'selected' : '' ?>><?= $label ?></option>
<?php endforeach; ?>
</select>
<span class="badge <?= $badge[$l['status']] ?? 'bg-secondary' ?> align-self-center"><?= htmlspecialchars($statuses[$l['status']] ?? $l['status']) ?></span>
</div>
<textarea class="form-control form-control-sm" name="notes[<?= $id ?>]" rows="2" placeholder="Notas internas"><?= htmlspecialchars((string) $l['admin_notes']) ?></textarea>
</td>
<td class="text-nowrap">
<button class="btn btn-sm btn-outline-primary" name="save" value="<?= $id ?>" title="Guardar"><i class="bi bi-check-lg"></i></button>
<button class="btn btn-sm btn-outline-danger" name="delete" value="<?= $id ?>" title="Apagar" onclick="return confirm('Apagar este pedido?')"><i class="bi bi-trash"></i></button>
</td>
</tr>
<?php endforeach; endif; ?>
</tbody>
</table>
</div>
</div></form>
</div>
<?php include __DIR__ . '/../../../includes/footer.php';
+161
View File
@@ -0,0 +1,161 @@
<?php
require __DIR__ . '/../../../config/db.php';
require __DIR__ . '/../../../config/functions.php';
$user = require_admin();
$search = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
csrf_check();
$uid = (int) ($user['id'] ?? 0) ?: null;
$action = (string) ($_POST['action'] ?? '');
if ($action === 'save') {
// Key: blank keeps the stored one; the "remover" box clears it.
$key = trim((string) ($_POST['google_places_api_key'] ?? ''));
if (!empty($_POST['clear_key'])) {
db_update_setting($pdo, 'google_places_api_key', '', $uid);
} elseif ($key !== '') {
db_update_setting($pdo, 'google_places_api_key', secret_encrypt($key), $uid);
}
db_update_setting($pdo, 'google_place_id', trim((string) ($_POST['google_place_id'] ?? '')), $uid);
db_update_setting($pdo, 'google_reviews_min_rating', (string) max(1, min(5, (int) ($_POST['min_rating'] ?? 4))), $uid);
db_update_setting($pdo, 'google_reviews_max', (string) max(1, min(5, (int) ($_POST['max'] ?? 3))), $uid);
db_update_setting($pdo, 'google_reviews_cache_hours', (string) max(1, (int) ($_POST['cache_hours'] ?? 24)), $uid);
reviews_cache_clear(); // new settings → next view fetches fresh
session()->setFlashdata('success', 'Definições guardadas.');
header('Location: ' . base_url('views/admin/reviews/index.php'));
exit;
}
if ($action === 'refresh') {
$r = reviews_refresh();
session()->setFlashdata(!empty($r['error']) ? 'error' : 'success',
!empty($r['error']) ? 'Falhou: ' . $r['error'] : 'Reviews atualizadas (' . count($r['reviews'] ?? []) . ' recebidas da Google).');
header('Location: ' . base_url('views/admin/reviews/index.php'));
exit;
}
if ($action === 'search') {
$apiKey = reviews_config()['api_key'];
$q = trim((string) ($_POST['query'] ?? ''));
$search = ($apiKey === '') ? ['error' => 'Guarda primeiro a chave da API.', 'places' => []]
: ($q === '' ? ['error' => 'Escreve o nome do ginásio.', 'places' => []] : reviews_find_place($q, $apiKey));
}
}
$cfg = reviews_config();
$env_key = (string) env('GOOGLE_PLACES_API_KEY', '') !== '';
$cache = reviews_cache_read();
$preview = site_reviews();
$info = site_info($pdo);
$page_title = 'Reviews Google';
include __DIR__ . '/../../../includes/header.php';
?>
<div class="container" style="max-width:900px;">
<div class="d-flex justify-content-between align-items-center mb-3">
<h1 class="h3 mb-0">Reviews Google</h1>
<a class="btn btn-outline-secondary btn-sm" href="<?= base_url('home#reviews') ?>" target="_blank" rel="noopener"><i class="bi bi-box-arrow-up-right me-1"></i>Ver no site</a>
</div>
<p class="text-muted small">A secção mostra as melhores reviews do ginásio no Google, obtidas pela Places API. A Google devolve no máximo 5 reviews (escolhidas por relevância); o site mostra as que têm a classificação mínima definida. Se nenhuma se qualificar, a secção fica escondida.</p>
<div class="card shadow-sm mb-4"><div class="card-body">
<h2 class="h5 mb-3">Configuração</h2>
<form method="POST">
<?= csrf_field() ?>
<input type="hidden" name="action" value="save">
<div class="row g-3">
<div class="col-md-7">
<label class="form-label">Chave da API (Places API — New)</label>
<?php if ($env_key): ?>
<input class="form-control" disabled value="Definida no .env (GOOGLE_PLACES_API_KEY)">
<?php else: ?>
<input class="form-control font-monospace" type="password" name="google_places_api_key" autocomplete="off"
placeholder="<?= $cfg['api_key'] !== '' ? 'Guardada — deixa vazio para manter' : 'AIza…' ?>">
<?php if ($cfg['api_key'] !== ''): ?>
<div class="form-check mt-1"><input class="form-check-input" type="checkbox" name="clear_key" id="clear_key" value="1">
<label class="form-check-label small" for="clear_key">Remover chave guardada</label></div>
<?php endif; ?>
<?php if (!secrets_available()): ?><div class="form-text text-warning">Sem chave de encriptação no .env — a chave fica guardada sem encriptação.</div><?php endif; ?>
<?php endif; ?>
<div class="form-text">Google Cloud Console → ativar «Places API (New)» → Credenciais. Restringe a chave a essa API.</div>
</div>
<div class="col-md-5">
<label class="form-label">Place ID</label>
<input class="form-control font-monospace" name="google_place_id" value="<?= htmlspecialchars($cfg['place_id']) ?>" placeholder="ChIJ…">
<div class="form-text">Não sabes? Usa a pesquisa abaixo.</div>
</div>
<div class="col-md-4">
<label class="form-label">Classificação mínima</label>
<select class="form-select" name="min_rating">
<?php for ($i = 5; $i >= 1; $i--): ?><option value="<?= $i ?>" <?= $cfg['min_rating'] === $i ? 'selected' : '' ?>><?= $i ?> ★<?= $i < 5 ? ' ou mais' : '' ?></option><?php endfor; ?>
</select>
</div>
<div class="col-md-4">
<label class="form-label">Número de reviews</label>
<input type="number" class="form-control" name="max" min="1" max="5" value="<?= $cfg['max'] ?>">
</div>
<div class="col-md-4">
<label class="form-label">Atualizar a cada (horas)</label>
<input type="number" class="form-control" name="cache_hours" min="1" value="<?= $cfg['cache_hours'] ?>">
<div class="form-text">Cada atualização é um pedido pago à Google.</div>
</div>
</div>
<button class="btn btn-primary mt-3">Guardar</button>
</form>
</div></div>
<div class="card shadow-sm mb-4"><div class="card-body">
<h2 class="h5 mb-3">Encontrar o Place ID</h2>
<form method="POST" class="d-flex gap-2">
<?= csrf_field() ?>
<input type="hidden" name="action" value="search">
<input class="form-control" name="query" value="<?= htmlspecialchars((string) ($_POST['query'] ?? trim($info['name'] . ' ' . $info['adress']))) ?>">
<button class="btn btn-outline-primary text-nowrap"><i class="bi bi-search me-1"></i>Procurar</button>
</form>
<?php if ($search !== null): ?>
<?php if ($search['error'] !== ''): ?><div class="alert alert-danger mt-3 mb-0"><?= htmlspecialchars($search['error']) ?></div>
<?php elseif (!$search['places']): ?><div class="alert alert-warning mt-3 mb-0">Sem resultados.</div>
<?php else: ?>
<ul class="list-group mt-3">
<?php foreach ($search['places'] as $p): ?>
<li class="list-group-item d-flex justify-content-between align-items-center gap-2">
<div><strong><?= htmlspecialchars($p['name']) ?></strong>
<?php if ($p['rating'] !== null): ?><span class="small text-muted"> · <?= htmlspecialchars((string) $p['rating']) ?> ★ (<?= (int) $p['total'] ?>)</span><?php endif; ?>
<div class="small text-muted"><?= htmlspecialchars($p['address']) ?></div>
<code class="small"><?= htmlspecialchars($p['id']) ?></code></div>
<button type="button" class="btn btn-sm btn-outline-success text-nowrap" onclick="document.querySelector('[name=google_place_id]').value='<?= htmlspecialchars($p['id'], ENT_QUOTES) ?>';window.scrollTo(0,0);">Usar</button>
</li>
<?php endforeach; ?>
</ul>
<div class="form-text">Depois de «Usar», carrega em Guardar.</div>
<?php endif; ?>
<?php endif; ?>
</div></div>
<div class="card shadow-sm"><div class="card-body">
<div class="d-flex justify-content-between align-items-center mb-3">
<h2 class="h5 mb-0">Estado</h2>
<form method="POST" class="mb-0"><?= csrf_field() ?><input type="hidden" name="action" value="refresh">
<button class="btn btn-sm btn-outline-primary" <?= reviews_configured() ? '' : 'disabled' ?>><i class="bi bi-arrow-clockwise me-1"></i>Atualizar agora</button></form>
</div>
<?php if (!reviews_configured()): ?>
<p class="text-muted mb-0">Por configurar — a secção não aparece no site.</p>
<?php else: ?>
<p class="small mb-2">
Última atualização: <?= !empty($cache['fetched_at']) ? date('d/m/Y H:i', (int) $cache['fetched_at']) : '—' ?>
<?php if (isset($cache['rating'])): ?> · <?= htmlspecialchars(number_format((float) $cache['rating'], 1, ',', '')) ?> ★ em <?= (int) ($cache['total'] ?? 0) ?> avaliações<?php endif; ?>
</p>
<?php if (!empty($cache['error'])): ?><div class="alert alert-danger small">Último erro: <?= htmlspecialchars($cache['error']) ?></div><?php endif; ?>
<?php if ($preview): ?>
<p class="small text-muted mb-2">No site aparecem <?= count($preview['reviews']) ?>:</p>
<?php foreach ($preview['reviews'] as $r): ?>
<div class="border rounded p-2 mb-2 small">
<strong><?= htmlspecialchars($r['author']) ?></strong> · <?= str_repeat('★', $r['rating']) ?> · <span class="text-muted"><?= htmlspecialchars($r['relative']) ?></span>
<div><?= nl2br(htmlspecialchars(mb_strimwidth($r['text'], 0, 240, '…'))) ?></div>
</div>
<?php endforeach; ?>
<?php else: ?>
<p class="text-muted small mb-0">Nenhuma review qualifica neste momento — a secção está escondida.</p>
<?php endif; ?>
<?php endif; ?>
</div></div>
</div>
<?php include __DIR__ . '/../../../includes/footer.php';
+14 -2
View File
@@ -4,7 +4,8 @@ require __DIR__ . '/../../../config/functions.php';
$user = require_admin();
$errors = [];
$data = ['name' => '', 'birthday' => '', 'at' => '', 'status' => 'ativo', 'description' => ''];
$data = ['name' => '', 'title' => '', 'birthday' => '', 'at' => '', 'status' => 'ativo', 'description' => '',
'skills' => '', 'certifications' => ''];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
csrf_check();
@@ -14,6 +15,9 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
'at' => trim($_POST['at'] ?? ''),
'status' => $_POST['status'] ?? 'ativo',
'description' => trim($_POST['description'] ?? ''),
'title' => mb_substr(trim($_POST['title'] ?? ''), 0, 100),
'skills' => trim($_POST['skills'] ?? ''),
'certifications' => trim($_POST['certifications'] ?? ''),
];
if ($data['name'] === '') $errors[] = 'O nome é obrigatório.';
@@ -70,7 +74,15 @@ include __DIR__ . '/../../../includes/header.php';
</select></div>
<div class="col-md-4"><label class="form-label">Foto</label>
<input type="file" class="form-control" name="photo" accept=".jpg,.jpeg,.png,.gif,.webp"></div>
<div class="col-12"><label class="form-label">Descrição</label>
<div class="col-12"><label class="form-label">Título</label>
<input class="form-control" name="title" maxlength="100" placeholder="ex.: Personal Trainer · Coach CrossFit" value="<?= htmlspecialchars($data['title'] ?? '') ?>">
<div class="form-text">Aparece no site por baixo do nome.</div></div>
<div class="col-md-6"><label class="form-label">Aptidões / Funções</label>
<textarea class="form-control" name="skills" rows="5" placeholder="Uma por linha"><?= htmlspecialchars($data['skills'] ?? '') ?></textarea></div>
<div class="col-md-6"><label class="form-label">Formações</label>
<textarea class="form-control" name="certifications" rows="5" placeholder="Uma por linha"><?= htmlspecialchars($data['certifications'] ?? '') ?></textarea></div>
<div class="col-12"><div class="form-text mt-0">Aptidões e formações aparecem no cartão de detalhe do site (hover no computador, toque no telemóvel).</div></div>
<div class="col-12"><label class="form-label">Descrição <span class="text-muted small">(opcional — aparece no cartão de detalhe)</span></label>
<textarea class="form-control js-wysiwyg" data-wysiwyg-height="200" name="description" rows="3"><?= htmlspecialchars($data['description']) ?></textarea></div>
</div>
<div class="mt-4 d-flex gap-2">
+12 -1
View File
@@ -29,6 +29,9 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
'at' => trim($_POST['at'] ?? ''),
'status' => $_POST['status'] ?? 'ativo',
'description' => trim($_POST['description'] ?? ''),
'title' => mb_substr(trim($_POST['title'] ?? ''), 0, 100),
'skills' => trim($_POST['skills'] ?? ''),
'certifications' => trim($_POST['certifications'] ?? ''),
];
if ($data['name'] === '') $errors[] = 'O nome é obrigatório.';
@@ -92,7 +95,15 @@ include __DIR__ . '/../../../includes/header.php';
<?php endif; ?>
<input type="file" class="form-control" name="photo" accept=".jpg,.jpeg,.png,.gif,.webp">
</div>
<div class="col-12"><label class="form-label">Descrição</label>
<div class="col-12"><label class="form-label">Título</label>
<input class="form-control" name="title" maxlength="100" placeholder="ex.: Personal Trainer · Coach CrossFit" value="<?= htmlspecialchars($data['title'] ?? '') ?>">
<div class="form-text">Aparece no site por baixo do nome.</div></div>
<div class="col-md-6"><label class="form-label">Aptidões / Funções</label>
<textarea class="form-control" name="skills" rows="5" placeholder="Uma por linha"><?= htmlspecialchars($data['skills'] ?? '') ?></textarea></div>
<div class="col-md-6"><label class="form-label">Formações</label>
<textarea class="form-control" name="certifications" rows="5" placeholder="Uma por linha"><?= htmlspecialchars($data['certifications'] ?? '') ?></textarea></div>
<div class="col-12"><div class="form-text mt-0">Aptidões e formações aparecem no cartão de detalhe do site (hover no computador, toque no telemóvel).</div></div>
<div class="col-12"><label class="form-label">Descrição <span class="text-muted small">(opcional — aparece no cartão de detalhe)</span></label>
<textarea class="form-control js-wysiwyg" data-wysiwyg-height="200" name="description" rows="3"><?= htmlspecialchars($data['description'] ?? '') ?></textarea></div>
</div>
<div class="mt-4 d-flex gap-2">
+1 -1
View File
@@ -53,7 +53,7 @@ include __DIR__ . '/../../../includes/header.php';
<?php foreach ($items as $item): ?>
<tr>
<td><?php if ($item['photo']): ?><img src="<?= base_url('uploads/team/foto/' . $item['photo']) ?>" alt="" style="width:40px;height:40px;object-fit:cover;border-radius:50%"><?php else: ?><span style="width:40px;height:40px;border-radius:50%;background:#dee2e6;display:inline-flex;align-items:center;justify-content:center"><i class="bi bi-person text-muted"></i></span><?php endif; ?></td>
<td><strong><?= htmlspecialchars($item['name']) ?></strong></td>
<td><strong><?= htmlspecialchars($item['name']) ?></strong><?php if (!empty($item['title'])): ?><div class="small text-muted"><?= htmlspecialchars($item['title']) ?></div><?php endif; ?></td>
<td><?= htmlspecialchars($item['at'] ?? '—') ?></td>
<td><span class="badge <?= $item['status'] === 'ativo' ? 'bg-success' : 'bg-secondary' ?>"><?= htmlspecialchars($item['status']) ?></span>
<?php if ($item['deleted_at']): ?><span class="badge bg-danger ms-1">apagado</span><?php endif; ?></td>