<?php

namespace Bot;

use Exception;
use mysqli;
use Config\AppConfig;

class Database
{
    use Database\UserDbTrait;
    use Database\TourDbTrait;
    use Database\PaymentDbTrait;
    use Database\ChatDbTrait;
    use Database\GuideDbTrait;

    private $mysqli;
    private $botLink;

    public function __construct()
    {
        $config = AppConfig::getConfig();
        $this->botLink = $config['bot']['bot_link'];
        $dbConfig = $config['database'];


        $this->mysqli = new mysqli(
            $dbConfig['host'],
            $dbConfig['username'],
            $dbConfig['password'],
            $dbConfig['database']
        );

        if ($this->mysqli->connect_errno) {
            error_log("❌ Database Connection Failed: " . $this->mysqli->connect_error);
            exit();
        }

        $this->mysqli->set_charset("utf8mb4");
    }

    public function getExplorerById($Id)
    {
        $stmt = $this->mysqli->prepare("SELECT * FROM explorers WHERE id = ? ");
        $stmt->bind_param("i", $Id);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result->fetch_assoc();
    }

    private function decodeJsonField($field)
    {
        if (is_string($field)) {
            $decoded = json_decode($field, true);

            if (json_last_error() === JSON_ERROR_NONE) {
                return $decoded;
            }
        }

        return $field;
    }

    public function dbQuery(string $query)
    {
        return $this->mysqli->query($query);
    }

    public function getConnection()
    {
        return $this->mysqli;
    }
}
