<?php
class SQLTools {
    private $host = "localhost";
    private $user = "root";
    private $pass = "33comRxXMysql";
    private $db_name = "MS_Usuario"; // BD por defecto
    private $charset = "utf8mb4";
    public $conn;

    // Constructor: Permite cambiar de BD al vuelo
    public function __construct($db_dinamica = null) {
        if ($db_dinamica) {
            $this->db_name = $db_dinamica;
        }

        try {
            $dsn = "mysql:host=" . $this->host . ";dbname=" . $this->db_name . ";charset=" . $this->charset;
            $this->conn = new PDO($dsn, $this->user, $this->pass, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
            ]);
        } catch (PDOException $e) {
            die("Error Conexión: " . $e->getMessage());
        }
    }

    // MÉTODO PARA LEER (Devuelve Array PHP limpio)
    public function select($sql) {
        try {
            $stmt = $this->conn->prepare($sql);
            $stmt->execute();
            // Retornamos un array con data y columnas (útil para SmartTable)
            $data = $stmt->fetchAll();
            
            // Obtener nombres de columnas
            $columns = [];
            if ($stmt->columnCount() > 0) {
                for ($i = 0; $i < $stmt->columnCount(); $i++) {
                    $meta = $stmt->getColumnMeta($i);
                    $columns[] = $meta['name'];
                }
            }
            
            return ["status" => "success", "data" => $data, "columns" => $columns];

        } catch (Exception $e) {
            return ["status" => "error", "message" => $e->getMessage()];
        }
    }

    // MÉTODO PARA ESCRIBIR (Insert/Update/Delete)
    public function query($sql) {
        try {
            $stmt = $this->conn->prepare($sql);
            $stmt->execute();
            
            $lastId = 0;
            // Si es un INSERT, capturamos el ID
            if (stripos(trim($sql), 'INSERT') === 0) {
                $lastId = $this->conn->lastInsertId();
            }

            return [
                "status" => "success", 
                "rows_affected" => $stmt->rowCount(),
                "last_id" => $lastId
            ];

        } catch (Exception $e) {
            return ["status" => "error", "message" => $e->getMessage()];
        }
    }
}
?>