<?php
declare(strict_types=1);

/** Carrega o sistema. Incluído pelas páginas (public/) e pelos scripts de linha de comando (bin/). */

require __DIR__ . '/config.php';
require __DIR__ . '/texto.php';
require __DIR__ . '/xlsx_leitor.php';
require __DIR__ . '/xlsx_gravador.php';
require __DIR__ . '/banco.php';
require __DIR__ . '/seguranca.php';
require __DIR__ . '/classificacao.php';
require __DIR__ . '/validacao.php';
require __DIR__ . '/envios.php';
require __DIR__ . '/pagina.php';

date_default_timezone_set((string) Config::get('fuso'));
ini_set('display_errors', '0');
ini_set('log_errors', '1');
error_reporting(E_ALL);

/** Escapa texto para HTML. */
function h(mixed $s): string
{
    return htmlspecialchars((string) $s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

/** Resposta JSON e fim. */
function responde_json(array $dados, int $status = 200): never
{
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($dados, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
    exit;
}

/** Redireciona (depois de um POST, para o F5 não reenviar o formulário). */
function redireciona(string $url): never
{
    header('Location: ' . $url, true, 303);
    exit;
}

/** Mensagem que aparece uma vez, na próxima página. */
function aviso(string $tipo, string $texto): void
{
    $_SESSION['avisos'][] = ['tipo' => $tipo, 'texto' => $texto];
}

/** @return list<array{tipo:string, texto:string}> */
function pega_avisos(): array
{
    $a = $_SESSION['avisos'] ?? [];
    unset($_SESSION['avisos']);
    return is_array($a) ? $a : [];
}

/** 1234.5 -> "1.234,50" */
function num_br(float|int $n, int $casas = 2): string
{
    return number_format((float) $n, $casas, ',', '.');
}

/** "2026-10" -> "out/2026" (pt) ou "oct/2026" (es) */
function mes_curto(string $ym, string $lingua = 'pt'): string
{
    if (!preg_match('/^(\d{4})-(\d{2})$/', $ym, $m)) {
        return $ym;
    }
    $pt = ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez'];
    $es = ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic'];
    $lista = $lingua === 'es' ? $es : $pt;
    return $lista[(int) $m[2] - 1] . '/' . $m[1];
}

/** "2026-11-06 22:31:05" -> "06/11/2026 22:31" */
function data_br(?string $s): string
{
    if (!$s) {
        return '';
    }
    $t = strtotime($s);
    return $t ? date('d/m/Y H:i', $t) : $s;
}
