<?php
/**
 * Firebase Configuration Test Script
 * Use this to verify your Firebase configuration is working
 */

// Try to find config.php
$config_paths = [
    'admin/includes/config.php',
    '../admin/includes/config.php',
    __DIR__ . '/admin/includes/config.php'
];

$config_found = false;
foreach ($config_paths as $path) {
    if (file_exists($path)) {
        require_once $path;
        $config_found = true;
        break;
    }
}

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Firebase Config Test</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 p-8">
    <div class="max-w-3xl mx-auto">
        <h1 class="text-2xl font-bold mb-6">Firebase Configuration Test</h1>
        
        <div id="status" class="bg-white rounded-xl shadow p-6 mb-6">
            <p class="text-gray-600">Testing configuration...</p>
        </div>
        
        <div id="config-display" class="bg-gray-900 text-green-400 p-4 rounded-xl font-mono text-sm mb-6 hidden">
        </div>
        
        <div id="actions" class="space-y-4 hidden">
            <a href="apply_firebase_config.php" class="block w-full py-3 bg-blue-600 text-white text-center rounded-xl font-bold hover:bg-blue-700">
                Run apply_firebase_config.php
            </a>
            <a href="user/my_bookings.php" class="block w-full py-3 bg-green-600 text-white text-center rounded-xl font-bold hover:bg-green-700">
                Go to My Bookings (Test Chat)
            </a>
        </div>
    </div>

    <!-- Firebase SDK -->
    <script src="https://www.gstatic.com/firebasejs/10.7.1/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.7.1/firebase-database-compat.js"></script>
    
    <script>
    async function testConfig() {
        const statusDiv = document.getElementById('status');
        const configDiv = document.getElementById('config-display');
        const actionsDiv = document.getElementById('actions');
        
        try {
            // Fetch config
            statusDiv.innerHTML = '<p class="text-blue-600">Fetching configuration from server...</p>';
            const response = await fetch('api/get_firebase_config.php');
            const data = await response.json();
            
            if (!data.success) {
                throw new Error(data.error || 'Failed to fetch config');
            }
            
            const config = data.config;
            
            // Display config (masked)
            configDiv.classList.remove('hidden');
            configDiv.innerHTML = `<strong>Configuration from server:</strong><br>
                Project ID: ${config.projectId || '<span class="text-red-400">NOT SET</span>'}<br>
                Database URL: ${config.databaseURL ? config.databaseURL.replace(/https:\/\//, '') : '<span class="text-red-400">NOT SET</span>'}<br>
                API Key: ${config.apiKey ? config.apiKey.substring(0, 10) + '...' : '<span class="text-red-400">NOT SET</span>'}<br>
                Auth Domain: ${config.authDomain || '<span class="text-red-400">NOT SET</span>'}<br>
                Messaging Sender ID: ${config.messagingSenderId || '<span class="text-red-400">NOT SET</span>'}`;
            
            // Validate
            const errors = [];
            if (!config.apiKey || config.apiKey.length < 20) errors.push('Invalid API Key');
            if (!config.projectId) errors.push('Project ID not set');
            if (!config.databaseURL) errors.push('Database URL not set');
            
            if (errors.length > 0) {
                statusDiv.innerHTML = `
                    <div class="bg-red-50 border border-red-200 rounded-lg p-4">
                        <p class="text-red-700 font-bold">Configuration Issues Found:</p>
                        <ul class="text-red-600 text-sm mt-2 list-disc list-inside">
                            ${errors.map(e => `<li>${e}</li>`).join('')}
                        </ul>
                        <p class="text-red-600 text-sm mt-3">Please run apply_firebase_config.php to fix these issues.</p>
                    </div>
                `;
                actionsDiv.classList.remove('hidden');
                return;
            }
            
            // Try to initialize Firebase
            statusDiv.innerHTML = '<p class="text-blue-600">Initializing Firebase...</p>';
            
            if (typeof firebase === 'undefined') {
                throw new Error('Firebase SDK not loaded');
            }
            
            if (firebase.apps.length > 0) {
                firebase.app().delete();
            }
            
            firebase.initializeApp(config);
            statusDiv.innerHTML += '<p class="text-green-600">✓ Firebase initialized</p>';
            
            // Test database connection
            statusDiv.innerHTML += '<p class="text-blue-600">Testing database connection...</p>';
            
            const db = firebase.database();
            const testRef = db.ref('.info/connected');
            
            const connected = await testRef.once('value');
            
            // Check if on InfinityFree hosting
            const isInfinityFree = window.location.hostname.includes('infinityfree') || 
                                   window.location.hostname.includes('free.nf');
            
            if (connected.val() === true) {
                statusDiv.innerHTML = `
                    <div class="bg-green-50 border border-green-200 rounded-lg p-4">
                        <p class="text-green-700 font-bold text-lg">✓ All Tests Passed!</p>
                        <p class="text-green-600 text-sm mt-2">Firebase is properly configured and connected.</p>
                        <p class="text-green-600 text-sm">You can now use the chat functionality.</p>
                    </div>
                `;
            } else if (isInfinityFree) {
                statusDiv.innerHTML = `
                    <div class="bg-amber-50 border border-amber-200 rounded-lg p-4">
                        <p class="text-amber-700 font-bold text-lg">⚠ InfinityFree Hosting Detected</p>
                        <p class="text-amber-600 text-sm mt-2">
                            InfinityFree blocks connections to Firebase Realtime Database.
                        </p>
                        <p class="text-amber-600 text-sm mt-1">
                            <strong>Solution:</strong> The chat will automatically use "Fallback Mode" 
                            which stores messages in your local database and polls for updates every 3 seconds.
                        </p>
                        <p class="text-amber-600 text-sm mt-1">
                            This works fine but has a slight delay compared to real-time.
                        </p>
                    </div>
                `;
            } else {
                statusDiv.innerHTML = `
                    <div class="bg-amber-50 border border-amber-200 rounded-lg p-4">
                        <p class="text-amber-700 font-bold">⚠ Partially Connected</p>
                        <p class="text-amber-600 text-sm mt-2">Firebase initialized but Realtime Database connection status is unclear.</p>
                        <p class="text-amber-600 text-sm">Try using the chat - it may still work with fallback mode.</p>
                    </div>
                `;
            }
            
            actionsDiv.classList.remove('hidden');
            
        } catch (error) {
            statusDiv.innerHTML = `
                <div class="bg-red-50 border border-red-200 rounded-lg p-4">
                    <p class="text-red-700 font-bold">Error: ${error.message}</p>
                    <p class="text-red-600 text-sm mt-2">Check the browser console for more details.</p>
                </div>
            `;
            actionsDiv.classList.remove('hidden');
            console.error('Test failed:', error);
        }
    }
    
    // Run test when page loads
    testConfig();
    </script>
</body>
</html>
