<?php
require_once 'config.php';

class Database {
    private $connection;
    
    public function __construct() {
        try {
            $this->connection = new PDO(
                "mysql:host=".DB_HOST.";dbname=".DB_NAME,
                DB_USER,
                DB_PASS,
                [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"]
            );
            $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            
            // Deshabilitar ONLY_FULL_GROUP_BY para permitir consultas con GROUP BY más flexibles
            $this->disableOnlyFullGroupBy();
        } catch(PDOException $e) {
            die("Error de conexión: " . $e->getMessage());
        }
    }
    
    /**
     * Deshabilita el modo ONLY_FULL_GROUP_BY en la sesión actual de MySQL
     */
    private function disableOnlyFullGroupBy() {
        try {
            // Obtener el SQL Mode actual
            $stmt = $this->connection->query("SELECT @@sql_mode");
            $currentMode = $stmt->fetchColumn();
            
            // Eliminar ONLY_FULL_GROUP_BY del SQL Mode
            $newMode = preg_replace('/,?ONLY_FULL_GROUP_BY,?/', ',', $currentMode);
            $newMode = trim($newMode, ',');
            
            // Si el mode resulta vacío, establecer un valor mínimo
            if (empty($newMode)) {
                $newMode = "STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION";
            }
            
            // Establecer el nuevo SQL Mode
            $this->connection->exec("SET SESSION sql_mode = '$newMode'");
        } catch (PDOException $e) {
            error_log("Error al modificar SQL Mode: " . $e->getMessage());
        }
    }
    
    public function query($sql, $params = []) {
        try {
            $stmt = $this->connection->prepare($sql);
            $stmt->execute($params);
            return $stmt;
        } catch(PDOException $e) {
            die("Error en la consulta: " . $e->getMessage());
        }
    }

    public function prepare($sql) {
        return $this->connection->prepare($sql);
    }

    public function close() {
        $this->connection = null;
    }

    public function getPDO() {
        return $this->connection;
    }
}
?>
