<?php
declare(strict_types=1);

/**
 * includes/db_ventashielo.php
 * ------------------------------------------------------------
 * Conexión secundaria a la base de VentasHielo desde BReport.
 *
 * Requiere que en la configuración principal exista:
 *
 * return [
 *   'db' => [...], // BReport
 *   'ventashielo_db' => [
 *      'host' => 'localhost',
 *      'port' => '3306',
 *      'socket' => '',
 *      'name' => 'deltadmin_testSistemas',
 *      'user' => '...',
 *      'pass' => '...',
 *      'charset' => 'utf8mb4',
 *   ],
 * ];
 * ------------------------------------------------------------
 */

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

if (!function_exists('ventashielo_db_config')) {
    function ventashielo_db_config(): array {
        static $cfg = null;
        if ($cfg !== null) return $cfg;

        if (function_exists('app_config')) {
            $app = app_config();
            $db = $app['ventashielo_db'] ?? [];
            if (is_array($db) && !empty($db)) {
                $cfg = $db;
                return $cfg;
            }
        }

        $cfg = [
            'host' => 'localhost',
            'port' => '3306',
            'socket' => '',
            'name' => 'deltadmin_ventasAppHielo',
            'user'    => 'deltadmin_dbmanager',
            'pass'    => 'Deltasol2013*',   // Recomendado: rotar credencial
            'charset' => 'utf8mb4',
        ];
        return $cfg;
    }
}

    
if (!function_exists('pdo_ventashielo')) {
    function pdo_ventashielo(): PDO {
        static $pdo = null;
        if ($pdo instanceof PDO) return $pdo;

        $db = ventashielo_db_config();

        if (!extension_loaded('pdo_mysql')) {
            throw new RuntimeException('Extensión pdo_mysql no está habilitada en este servidor.');
        }

        $host    = (string)($db['host'] ?? 'localhost');
        $port    = (string)($db['port'] ?? '');
        $socket  = (string)($db['socket'] ?? '');
        $name    = (string)($db['name'] ?? '');
        $user    = (string)($db['user'] ?? '');
        $pass    = (string)($db['pass'] ?? '');
        $charset = (string)($db['charset'] ?? 'utf8mb4');

        if ($name === '' || $user === '') {
            throw new RuntimeException('Config VentasHielo incompleta. Define ventashielo_db en tu config.');
        }

        $mkDsn = static function(string $h) use ($socket, $port, $name, $charset): string {
            if ($socket !== '') {
                return "mysql:unix_socket={$socket};dbname={$name};charset={$charset}";
            }
            $dsn = "mysql:host={$h};dbname={$name};charset={$charset}";
            if ($port !== '' && ctype_digit($port)) {
                $dsn = "mysql:host={$h};port={$port};dbname={$name};charset={$charset}";
            }
            return $dsn;
        };

        $opt = [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ];

        $hosts = [$host];
        if (strtolower($host) === 'localhost') $hosts[] = '127.0.0.1';
        if ($host === '127.0.0.1') $hosts[] = 'localhost';

        $last = null;
        foreach (array_unique($hosts) as $h) {
            try {
                $pdo = new PDO($mkDsn($h), $user, $pass, $opt);
                return $pdo;
            } catch (Throwable $e) {
                $last = $e;
            }
        }

        throw $last ?: new RuntimeException('No se pudo conectar a la base de VentasHielo.');
    }
}
