<?php
namespace app\models;

if (!class_exists('app\\models\\conexion')) {
class conexion
{
    private static $instance = null;

    public function DB()
    {
        if (self::$instance === null) {
            $loaderPaths = [
                __DIR__ . '/../../env_loader.php',
                __DIR__ . '/../env_loader.php',
                __DIR__ . '/env_loader.php',
            ];
            foreach ($loaderPaths as $p) {
                if (file_exists($p)) { require_once $p; break; }
            }

            $host    = env('DB_HOST', 'localhost');
            $dbname  = env('DB_NAME');
            $user    = env('DB_USER');
            $pass    = env('DB_PASS');
            $charset = env('DB_CHARSET', 'utf8');

            if (!$dbname || !$user) {
                throw new \Exception('[conexion.php] Faltan credenciales en .env');
            }

            self::$instance = new \PDO(
                "mysql:host={$host};dbname={$dbname};charset={$charset}",
                $user, $pass,
                [
                    \PDO::ATTR_PERSISTENT       => true,
                    \PDO::ATTR_ERRMODE           => \PDO::ERRMODE_EXCEPTION,
                    \PDO::ATTR_EMULATE_PREPARES  => false,
                    \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES {$charset}",
                ]
            );
        }
        return self::$instance;
    }

    public static function resetConnection() { self::$instance = null; }

} // end class
} // end class_exists
