<?php

/*
 * @name        JMY CMS
 * @link        https://jmy.su/
 * @copyright   Copyright (C) 2012-2025 JMY LTD
 * @license     LICENSE.txt (see attached file)
 * @version     VERSION.txt (see attached file)
 * @author      Komarov Ivan
 * @edited      Orlov Alexsey
 */

class controlDB
{
    public $resource = false;
    public $timeQuery = 0;
    public $timeQueries = 0;
    public $numQueries = 0;
    public $listQueries = array();

    public function connect($dbhost, $dbuser, $dbpass, $dbname, $dbpersist = false): void
    {
        mysqli_report(MYSQLI_REPORT_OFF);
        $dbpersist = $dbpersist ? 'p:' . $dbhost : $dbhost;
        $this->resource = mysqli_connect($dbpersist, $dbuser, $dbpass, $dbname);
        if (!mysqli_connect_errno()) {
            mysqli_set_charset($this->resource, 'utf8');
            if (!mysqli_select_db($this->resource, $dbname)) {
                if (file_exists('install.php')) if (!file_exists('install/lock.install')) Header('Location: /install.php');
                mysqlFatalError('Ошибка в базе данных MySQL', 'База данных ' . $dbname . ' не найдена', '');
            }
        } else {
            if (file_exists('install.php')) if (!file_exists('install/lock.install')) Header('Location: /install.php');
            mysqlFatalError('Ошибка в базе данных MySQL', 'Нет подключения к ' . $dbhost, '');
            exit();
        }
    }

    function safesql($str): string
    {
        return mysqli_real_escape_string($this->resource, $str);
    }

    public function doQuery($str, $ignoreError, $prefix): mysqli_result|bool
    {
        $timer = microtime(1);
        if ($ignoreError) {
            $result = mysqli_query($this->resource, $str) or writeInLog('[Ошибка в базе данных] - запрос: ' . str_replace($prefix, '', $str), 'db_query');
        } else {
            $result = mysqli_query($this->resource, $str) or mysqlFatalError('Ошибка выполнения запроса в DB', "Не удалось выполнить запрос '" . str_replace($prefix, '', $str) . "'<br />Ответ с сервера: " . str_replace($prefix, '', mysqli_error($this->resource)), str_replace($prefix, '', $str));
        }
        $this->timeQuery += microtime(1) - $timer;
        $this->timeQueries += $this->timeQuery;
        $this->numQueries++;
        if (DEBUG) $this->listQueries[$this->numQueries] = array($str, $this->timeQuery);
        return $result;
    }

    public function freeResult($resource): string|bool
    {
        if ($resource instanceof mysqli_result) {
            return mysqli_free_result($resource);
        } else {
            return false;
        }
    }

    public function getRow($resource): false|array|null
    {
        if ($resource instanceof mysqli_result) {
            return @mysqli_fetch_assoc($resource);
        } else {
            return false;
        }
    }

    public function fetchRow($resource): false|array|null
    {
        if ($resource instanceof mysqli_result) {
            return @mysqli_fetch_array($resource);
        } else {
            return false;
        }
    }

    public function numRows($resource): false|int|string
    {
        if ($resource instanceof mysqli_result) {
            return mysqli_num_rows($resource);
        } else {
            return false;
        }
    }

    public function insidRows($resource): false|int|string
    {
        if ($resource instanceof mysqli_result) {
            return mysqli_insert_id($resource);
        } else {
            return false;
        }
    }

    public function affectedRows($resource): false|int|string
    {
        if ($resource instanceof mysqli_result) {
            return mysqli_affected_rows($resource);
        } else {
            return false;
        }
    }

    function getFields($resource): false|array
    {
        if ($resource instanceof mysqli_result) {
            while ($field = mysqli_fetch_field($resource)) {
                $fields[] = $field;
            }
            return $fields;
        } else {
            return false;
        }
    }

    public function info(): ?string
    {
        return mysqli_info($this->resource);
    }
}