<?php

require_once __DIR__ . '/config.php';

/**
 * Database connection class to manage connections to both databases
 */
class Database {
    private static $primaryConnection = null;
    private static $apiConnection = null;

    /**
     * Get connection to the primary Deywuro database
     * @return mysqli Database connection
     */
    public static function getPrimaryConnection() {
        if (self::$primaryConnection === null) {
            self::$primaryConnection = new mysqli(
                PRIMARY_DB_HOST,
                PRIMARY_DB_USER,
                PRIMARY_DB_PASS,
                PRIMARY_DB_NAME,
                PRIMARY_DB_PORT
            );

            if (self::$primaryConnection->connect_error) {
                error_log('Primary database connection failed: ' . self::$primaryConnection->connect_error);
                throw new Exception('Database connection error');
            }

            self::$primaryConnection->set_charset('utf8mb4');
        }

        return self::$primaryConnection;
    }

    /**
     * Get connection to the API-specific database
     * @return mysqli Database connection
     */
    public static function getApiConnection() {
        if (self::$apiConnection === null) {
            self::$apiConnection = new mysqli(
                API_DB_HOST,
                API_DB_USER,
                API_DB_PASS,
                API_DB_NAME,
                API_DB_PORT
            );

            if (self::$apiConnection->connect_error) {
                error_log('API database connection failed: ' . self::$apiConnection->connect_error);
                throw new Exception('Database connection error');
            }

            self::$apiConnection->set_charset('utf8mb4');
        }

        return self::$apiConnection;
    }

    /**
     * Close all database connections
     */
    public static function closeConnections() {
        if (self::$primaryConnection !== null) {
            self::$primaryConnection->close();
            self::$primaryConnection = null;
        }

        if (self::$apiConnection !== null) {
            self::$apiConnection->close();
            self::$apiConnection = null;
        }
    }
} 