<?php
class Database {
    private $host = "198.49.68.77";
    private $port = "3306";
    private $database_name = "colchonesdisai_pos_rutas";
    private $username = "colchonesdisai_root";
    private $password = "=Prvic0501";
    private $conn = null;

    public function getConnection() {
        try {
            $this->conn = new PDO(
                "mysql:host={$this->host};port={$this->port};dbname={$this->database_name};charset=utf8mb4",
                $this->username,
                $this->password,
                [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false,
                    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4"
                ]
            );
            
            return $this->conn;
        } catch(PDOException $exception) {
            error_log("Error de conexión: " . $exception->getMessage());
            return false;
        }
    }

    public function closeConnection() {
        $this->conn = null;
    }

    // Método para verificar la conexión
    public function testConnection() {
        $connection = $this->getConnection();
        if ($connection) {
            try {
                $stmt = $connection->query("SELECT 1");
                return true;
            } catch (PDOException $e) {
                return false;
            }
        }
        return false;
    }

    // Método para obtener configuración del sistema
    public function getConfig($key = null) {
        $connection = $this->getConnection();
        if (!$connection) return false;

        try {
            if ($key) {
                $stmt = $connection->prepare("SELECT valor FROM configuracion WHERE clave = ?");
                $stmt->execute([$key]);
                $result = $stmt->fetch();
                return $result ? $result['valor'] : null;
            } else {
                $stmt = $connection->query("SELECT clave, valor FROM configuracion");
                $configs = [];
                while ($row = $stmt->fetch()) {
                    $configs[$row['clave']] = $row['valor'];
                }
                return $configs;
            }
        } catch (PDOException $e) {
            error_log("Error al obtener configuración: " . $e->getMessage());
            return false;
        }
    }

    // Método para ejecutar queries de inicialización
    public function initDatabase() {
        $connection = $this->getConnection();
        if (!$connection) return false;

        try {
            // Verificar si las tablas existen
            $stmt = $connection->query("SHOW TABLES LIKE 'productos'");
            if ($stmt->rowCount() == 0) {
                // La base de datos no está inicializada
                $sql = file_get_contents(__DIR__ . '/../database.sql');
                if ($sql) {
                    $connection->exec($sql);
                    return true;
                }
            }
            return true;
        } catch (PDOException $e) {
            error_log("Error al inicializar base de datos: " . $e->getMessage());
            return false;
        }
    }
}
?>