<?php
// admin/contador/_common.php
// Módulo Contador SIN LOGIN (solo DB + helpers)

// Cargar config.php del proyecto
$rootConfig = realpath(__DIR__ . '/../../config.php');
if (!$rootConfig || !file_exists($rootConfig)) {
    http_response_code(500);
    exit("No se encontró config.php en ../../config.php");
}
require_once $rootConfig;

function db(): PDO {
    global $sql_details;
    $dsn = sprintf(
        "mysql:host=%s;dbname=%s;port=%s;charset=utf8mb4",
        $sql_details['host'],
        $sql_details['db'],
        $sql_details['port'] ?? '3306'
    );
    return new PDO($dsn, $sql_details['user'], $sql_details['pass'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
}

function h($s): string {
    return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
}

function date_or_null($s): ?string {
    if (!$s) return null;
    $s = trim($s);
    if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $s)) return $s;
    return null;
}

function money($n): string {
    if ($n === null || $n === '') return '';
    return number_format((float)$n, 2, ',', '.');
}

function build_query_range(array $wh, array $params): array {
    $where = $wh ? ('WHERE ' . implode(' AND ', $wh)) : '';
    return [$where, $params];
}
