AutoFiller_QR_Campamento/includes/functions.php
2026-06-11 16:40:36 -06:00

76 lines
2.1 KiB
PHP

<?php
function h(?string $s): string
{
return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8');
}
function redirect(string $url): never
{
header('Location: ' . $url);
exit;
}
function flash(string $type, string $message): void
{
$_SESSION['flash'] = ['type' => $type, 'message' => $message];
}
function getFlash(): ?array
{
if (!isset($_SESSION['flash'])) {
return null;
}
$flash = $_SESSION['flash'];
unset($_SESSION['flash']);
return $flash;
}
function getUbicacionByCodigo(PDO $db, string $codigo): ?array
{
$stmt = $db->prepare('
SELECT u.id, u.codigo AS ubicacion_codigo, u.nombre AS ubicacion_nombre,
m.id AS modulo_id, m.codigo AS modulo_codigo, m.nombre AS modulo_nombre
FROM ubicaciones u
JOIN modulos m ON m.id = u.modulo_id
WHERE u.codigo = ? AND u.activo = 1 AND m.activo = 1
');
$stmt->execute([$codigo]);
$row = $stmt->fetch();
return $row ?: null;
}
function formatFecha(?string $datetime): string
{
if (!$datetime) {
return '';
}
$dt = new DateTime($datetime);
return $dt->format('d/m/Y H:i');
}
function nextModuloCodigo(PDO $db): string
{
$row = $db->query("SELECT codigo FROM modulos WHERE codigo REGEXP '^MOD-[0-9]+$' ORDER BY CAST(SUBSTRING(codigo, 5) AS UNSIGNED) DESC LIMIT 1")->fetch();
$num = $row ? (int) substr($row['codigo'], 4) : 0;
return sprintf('MOD-%03d', $num + 1);
}
function nextUbicacionCodigo(PDO $db): string
{
$row = $db->query("SELECT codigo FROM ubicaciones WHERE codigo REGEXP '^UB-[0-9]+$' ORDER BY CAST(SUBSTRING(codigo, 4) AS UNSIGNED) DESC LIMIT 1")->fetch();
$num = $row ? (int) substr($row['codigo'], 4) : 0;
return sprintf('UB-%05d', $num + 1);
}
function appendUbicacionToQrCsv(string $codigo, string $modulo, string $ubicacion): void
{
$path = dirname(__DIR__) . '/qr_data.csv';
$exists = file_exists($path);
$fh = fopen($path, 'a');
if (!$exists) {
fputcsv($fh, ['codigo', 'modulo', 'ubicacion', 'url']);
}
fputcsv($fh, [$codigo, $modulo, $ubicacion, BASE_URL . '/formulario.php?u=' . $codigo]);
fclose($fh);
}