<?php
/**
 * Database Configuration Class (mysqli)
 * Reads credentials from shared config: /admin/db_config.php
 */

require_once __DIR__ . '/../../admin/db_config.php';

class Database {
    private $conn = null;
    private static $instance = null;

    private function __construct() {
        ini_set('display_errors', 0);
        ini_set('display_startup_errors', 0);
        error_reporting(E_ALL);
    }

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new Database();
        }
        return self::$instance;
    }

    public function getConnection() {
        if ($this->conn === null) {
            try {
                $this->conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
                if ($this->conn->connect_error) {
                    throw new Exception("Connection failed: " . $this->conn->connect_error);
                }
                $this->conn->set_charset(DB_CHARSET);
                $this->conn->query("SET SESSION sql_mode = ''");
                 $this->conn->query("SET time_zone = '+05:30'");
            } catch (Exception $e) {
                error_log($e->getMessage());
                return null;
            }
        }
        return $this->conn;
    }

    public function closeConnection() {
        if ($this->conn !== null) {
            $this->conn->close();
            $this->conn = null;
        }
    }

    private function __clone() { }

    public function __destruct() {
        $this->closeConnection();
    }

    public function escapeString($string) {
        $conn = $this->getConnection();
        if ($conn) {
            return $conn->real_escape_string($string);
        }
        return $string;
    }
}
