<?php
/**
 * MongoDB Database Configuration for Recora Admin Panel
 */
$autoload = dirname(__DIR__, 1) . '/vendor/autoload.php';

if (!file_exists($autoload)) {
    // TEMP: help you see what path it's trying
    throw new \RuntimeException("Composer autoload not found at: $autoload");
}
require_once $autoload;

use MongoDB\Client;

class MongoDBConnection {
    private static $instance = null;
    private $client;
    private $database;
    
    // MongoDB Atlas Configuration
    private $connection_string = 'mongodb+srv://mongodb:mtvMongo123@mongodbcluster.wsgjnyw.mongodb.net/?retryWrites=true&w=majority&tls=true&maxPoolSize=10';
    private $database_name = 'recora';
    
    private function __construct() {
        try {
            // Use the provided Atlas connection string directly
            $connectionString = $this->connection_string;
            
            // Connect to MongoDB Atlas
            $this->client = new MongoDB\Client($connectionString);
            $this->database = $this->client->selectDatabase($this->database_name);
            
            // Test connection to Atlas
            $this->database->command(['ping' => 1]);
            
        } catch (Exception $e) {
            error_log("MongoDB connection failed: " . $e->getMessage());
            throw new Exception("Database connection failed: " . $e->getMessage());
        }
    }
    
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    public function getDatabase() {
        return $this->database;
    }
    
    public function getCollection($collectionName) {
        return $this->database->selectCollection($collectionName);
    }
    
    // Prevent cloning
    private function __clone() {}
    
    // Prevent unserialization
    public function __wakeup() {}
}

/**
 * Database Helper Functions
 */
class DatabaseHelper {
    
    /**
     * Get database statistics
     */
    public static function getDatabaseStats() {
        try {
            $db = MongoDBConnection::getInstance()->getDatabase();
            $stats = $db->command(['dbStats' => 1])->toArray();
            return $stats[0] ?? [];
        } catch (Exception $e) {
            error_log("Error getting database stats: " . $e->getMessage());
            return [];
        }
    }
    
    /**
     * Get collection statistics
     */
    public static function getCollectionStats($collectionName) {
        try {
            $db = MongoDBConnection::getInstance()->getDatabase();
            $stats = $db->command(['collStats' => $collectionName])->toArray();
            return $stats[0] ?? [];
        } catch (Exception $e) {
            error_log("Error getting collection stats for $collectionName: " . $e->getMessage());
            return [];
        }
    }
    
    /**
     * Format MongoDB ObjectId for display
     */
    public static function formatObjectId($objectId) {
        if ($objectId instanceof MongoDB\BSON\ObjectId) {
            return (string) $objectId;
        }
        return $objectId;
    }
    
    /**
     * Format MongoDB DateTime for display
     */
    public static function formatDateTime($dateTime) {
        if ($dateTime instanceof MongoDB\BSON\UTCDateTime) {
            return $dateTime->toDateTime()->format('Y-m-d H:i:s');
        }
        return $dateTime;
    }
    
    /**
     * Safe array access with default value
     */
    public static function safeGet($array, $key, $default = null) {
        return isset($array[$key]) ? $array[$key] : $default;
    }
    
    /**
     * Convert MongoDB document to array
     */
    public static function documentToArray($document) {
        if ($document instanceof MongoDB\Model\BSONDocument) {
            return $document->toArray();
        }
        return $document;
    }
}

/**
 * Error handling
 */
function handleDatabaseError($e) {
    error_log("Database error: " . $e->getMessage());
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST' || 
        (isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'error' => 'Database operation failed',
            'message' => $e->getMessage()
        ]);
        exit;
    } else {
        $error_message = "Database operation failed. Please try again.";
        // You can include this in your template
        return $error_message;
    }
}

// Auto-initialize connection on include
try {
    $mongoConnection = MongoDBConnection::getInstance();
} catch (Exception $e) {
    $db_error = handleDatabaseError($e);
}

?>
