<?php
class OdbcSimulator {
    private static $instance = null;
    private $connection;

    // Singleton initialization
    public static function getInstance($host, $user, $pass, $db) {
        if (self::$instance === null) {
            self::$instance = new self($host, $user, $pass, $db);
        }
        return self::$instance;
    }

    private function __construct($host, $user, $pass, $db) {
        $this->connection = new mysqli($host, $user, $pass, $db);
        if ($this->connection->connect_error) {
            die("MySQL Connection failed: " . $this->connection->connect_error);
        }
    }

    // Get mysqli connection
    public static function getConnection() {
        return self::$instance->connection;
    }

    // Simulate odbc_connect (returns mysqli connection)
    public static function odbc_connect($host, $user, $pass) {
        return self::getConnection();
    }

    // Simulate odbc_exec
    public static function odbc_exec($conn, $sql) {
        // Convert EXEC SP call to CALL for MySQL
        $sql = preg_replace('/EXEC\s+(\w+)\((.*)\)/i', 'CALL $1($2)', $sql);

        $result = $conn->query($sql);
        if ($result === false) {
            die("Query Error: " . $conn->error . "\nSQL: $sql");
        }

        $rows = [];
        if ($result instanceof mysqli_result) {
            $rows = $result->fetch_all(MYSQLI_ASSOC);
            $result->free();
        }

        // Wrap in array to keep track of index
        return ['rows' => $rows, 'index' => 0];
    }

    // Simulate odbc_fetch_row
    public static function odbc_fetch_row(&$result) {
        if ($result['index'] < count($result['rows'])) {
            $result['index']++;
            return true;
        }
        return false;
    }

    // Simulate odbc_fetch_array
    public static function odbc_fetch_array(&$result) {
        if ($result['index'] < count($result['rows'])) {
            return $result['rows'][$result['index']++];
        }
        return false;
    }

    // Simulate odbc_result
    public static function odbc_result($result, $field) {
        $i = $result['index'] - 1;
        return $result['rows'][$i][$field] ?? null;
    }
}
