<?php

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

    // Database configuration
    private $servername = "localhost";
    private $username = "autk7644_customer_app_user";
    private $password = "AppUserPassOke2025";
    private $dbname = "autk7644_customer_app_db";

    private function __construct()
    {
        $this->connect();
    }

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

    private function connect()
    {
        try {
            $this->connection = new mysqli($this->servername, $this->username, $this->password, $this->dbname);

            if ($this->connection->connect_error) {
                throw new Exception("Connection failed: " . $this->connection->connect_error);
            }

            $this->connection->set_charset("utf8mb4");
        } catch (Exception $e) {
            error_log("Database connection error: " . $e->getMessage());
            throw $e;
        }
    }

    public function getConnection()
    {
        // Check if connection is still alive
        if (!$this->connection || !$this->connection->ping()) {
            $this->connect();
        }
        return $this->connection;
    }

    public function close()
    {
        if ($this->connection) {
            $this->connection->close();
        }
    }

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

    // Prevent unserialization of the instance
    public function __wakeup()
    {
        throw new Exception("Cannot unserialize singleton");
    }
}

// Helper function for quick access
function getDB()
{
    return Database::getInstance()->getConnection();
}
