<?php
// dbConnection.php

//require_once 'config.php';
require_once(__DIR__ . '/config.php');


class DatabaseConnection {
    private $host = DB_HOST;
    private $user = DB_USER;
    private $pass = DB_PASS;
    private $dbname = DB_NAME;
    private $conn;
    private static $instance;

    // Make constructor private to enforce Singleton pattern
    private function __construct() {
        $this->connect();
    }

    // Singleton pattern to get a single connection instance
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    // Establish the database connection
    private function connect() {
        try {
            // Create a new connection using MySQLi
            $this->conn = new mysqli($this->host, $this->user, $this->pass, $this->dbname);

            // Check for connection error and throw an exception if needed
            if ($this->conn->connect_error) {
                throw new Exception("Connection failed: " . $this->conn->connect_error);
            }

        } catch (Exception $e) {
            // Log the error for debugging purposes and stop script execution
            error_log($e->getMessage(), 3, 'errors.log'); // Log to a file
            die("Database connection error. Please try again later.");
        }
    }

    // Return the database connection
    public function getConnection() {
        return $this->conn;
    }

    // Return a prepared statement
    public function prepare($query) {
        if ($this->conn) {
            return $this->conn->prepare($query);
        } else {
            throw new Exception("Database connection is not established.");
        }
    }

    // Close the connection
    public function close() {
        if ($this->conn) {
            $this->conn->close();
        }
    }

    // Prevent cloning the instance
    private function __clone() {}
}

