<?php
require_once __DIR__ . '/ejecutar_migraciones_bds.php';
date_default_timezone_set('America/La_Paz');

class Database {
    private $host;
    private $port;
    private $db_name;
    private $username;
    private $password;
    private $charset;
    private $runMigrations;
    private $conn;

    public function __construct() {
        $this->host = $this->getConfigValue('149.88.104.138', 'localhost');
        $this->port = $this->getConfigValue('DB_PORT', '3306');
        $this->db_name = $this->getConfigValue('lasetsla_infoda', 'wiredcom_uni3t');
        $this->username = $this->getConfigValue('lasetsla_jims2', 'root');
        $this->password = $this->getConfigValue('J&i!Jux}Y26?4WmL', '');
        $this->charset = $this->getConfigValue('DB_CHARSET', 'utf8mb4');

        $runMigrationsRaw = $this->getConfigValue('EDUNOTE_RUN_MIGRATIONS', null);
        if ($runMigrationsRaw === null || $runMigrationsRaw === '') {
            $this->runMigrations = in_array($this->host, ['localhost', '127.0.0.1'], true);
        } else {
            $this->runMigrations = in_array(strtolower((string)$runMigrationsRaw), ['1', 'true', 'yes', 'on'], true);
        }
    }

    private function getConfigValue($envKey, $defaultValue = null) {
        $value = getenv($envKey);
        if ($value !== false && $value !== '') {
            return $value;
        }

        if (isset($_ENV[$envKey]) && $_ENV[$envKey] !== '') {
            return $_ENV[$envKey];
        }

        if (isset($_SERVER[$envKey]) && $_SERVER[$envKey] !== '') {
            return $_SERVER[$envKey];
        }

        return $defaultValue;
    }

    public function connect() {
        $this->conn = null;
        try {
            $dsn = 'mysql:host=' . $this->host . ';port=' . $this->port . ';dbname=' . $this->db_name . ';charset=' . $this->charset;
            $this->conn = new PDO($dsn, $this->username, $this->password, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ]);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            if ($this->conn && $this->runMigrations) {
                edunote_aplicar_migraciones_bds($this->conn);
            }
        } catch(PDOException $e) {
            error_log('Error de conexion DB: ' . $e->getMessage());
            throw $e;
        }
        return $this->conn;
    }
}
