/**
 * Firebase Configuration
 * Updated to fetch configuration dynamically from the database.
 */

(function() {
    // Determine the correct API path based on script location
    let apiPath = '../api/get_firebase_config.php';
    if (document.currentScript && document.currentScript.src) {
        const scriptSrc = document.currentScript.src;
        if (scriptSrc.includes('admin/includes/')) {
            apiPath = scriptSrc.substring(0, scriptSrc.indexOf('admin/includes/')) + 'api/get_firebase_config.php';
        }
    }

    console.log("Fetching Firebase config from:", apiPath);

    fetch(apiPath)
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                const config = data.config;

                // Initialize Firebase if not already initialized
                if (typeof firebase !== 'undefined') {
                    if (!firebase.apps.length) {
                        firebase.initializeApp(config);
                        console.log("Firebase initialized dynamically with Project ID:", config.projectId);
                    } else {
                        console.log("Firebase already initialized");
                    }

                    // Dispatch a custom event so other scripts know Firebase is ready
                    document.dispatchEvent(new CustomEvent('firebase-ready', { detail: config }));
                } else {
                    console.error("Firebase SDK not loaded");
                }
            } else {
                console.error("Failed to load Firebase config:", data.error);
            }
        })
        .catch(err => {
            console.error("Error fetching Firebase config:", err);
        });
})();
