<?php
if (!defined('EvolutionScript')) {
    exit('Hacking attempt...');
}
require_once __DIR__ . '/config.php';

class CronDbCore
{
    public $link;

    public function __construct(array $config)
    {
        $host = $config['Database']['servername'] ?? 'localhost';
        $user = $config['Database']['username'] ?? '';
        $pass = $config['Database']['password'] ?? '';
        $name = $config['Database']['dbname'] ?? '';
        $this->link = mysqli_connect($host, $user, $pass, $name);
        if (!$this->link) {
            die(json_encode(array(
                'ok' => false,
                'message' => 'Database connection failed.',
                'error' => mysqli_connect_error(),
            )));
        }
        mysqli_set_charset($this->link, 'utf8mb4');
    }

    public function query($sql)
    {
        return mysqli_query($this->link, $sql);
    }

    public function fetch_array($result)
    {
        return mysqli_fetch_assoc($result);
    }

    public function fetchRow($sql)
    {
        $res = $this->query($sql);
        if (!$res) {
            return null;
        }
        return $this->fetch_array($res);
    }
}

$db = new CronDbCore($config);

if (!function_exists('mysql_set_charset')) {
    function mysql_set_charset($charset) {
        global $db;
        if (isset($db) && isset($db->link)) {
            return mysqli_set_charset($db->link, $charset);
        }
        return false;
    }
}

if (!function_exists('mysql_real_escape_string')) {
    function mysql_real_escape_string($value) {
        global $db;
        if (isset($db) && isset($db->link)) {
            return mysqli_real_escape_string($db->link, (string)$value);
        }
        return addslashes((string)$value);
    }
}
?>
