<?php

// delete in Wordpress Plugin to avoid plugin guideline violation

namespace SiteZen\Telemetry\Connectors\DatabaseAdapters;


class MysqliResult implements DbResult
{
    private \mysqli_result $result;

    public function __construct(\mysqli_result $result)
    {
        $this->result = $result;
    }

    public function fetch_assoc(): ?array
    {
        $row = $this->result->fetch_assoc();
        return $row === null ? null : $row; // mysqli returns null at end in newer versions
    }

    public function free(): void
    {
        $this->result->free();
    }
}

class MysqliAdapter implements DbAdapter
{
    private ?\mysqli $mysqli = null;
    private string $host;
    private string $username;
    private string $password;
    private string $database;
    private int $port;
    private ?string $socket;
    private string $lastError = '';

    public function __construct(array $config)
    {
        $this->host = $config['host'] ?? '';
        $this->username = $config['username'] ?? '';
        $this->password = $config['password'] ?? '';
        $this->database = $config['database'] ?? '';
        $this->port = (int)($config['port'] ?? 0);
        $this->socket = $config['socket'] ?? null;
    }

    public function connect(): void
    {
        if ($this->mysqli instanceof \mysqli) {
            return;
        }
        $this->mysqli = @new \mysqli($this->host, $this->username, $this->password, $this->database, $this->port, $this->socket ?? '');
        if ($this->mysqli->connect_errno) {
            $this->lastError = (string)$this->mysqli->connect_error;
            throw new \Exception('Failed to connect to MySQL: ' . $this->lastError);
        }
    }

    public function query(string $sql): DbResult
    {
        $this->connect();
        $res = $this->mysqli->query($sql);
        if ($res === false) {
            $this->lastError = (string)$this->mysqli->error;
            throw new \Exception('MySQL error: ' . $this->lastError);
        }
        return new MysqliResult($res);
    }

    public function error(): string
    {
        return $this->lastError;
    }

    public function close(): void
    {
        if ($this->mysqli instanceof \mysqli) {
            $this->mysqli->close();
            $this->mysqli = null;
        }
    }
}
