<?php
/**
 * Firebase Configuration Setup Script
 * Updates the database with your Firebase credentials
 *
 * Usage:
 * 1. Upload this file to your server root.
 * 2. Run it via Browser: yourdomain.com/apply_firebase_config.php
 * 3. DELETE THIS FILE IMMEDIATELY AFTER USE.
 */

// Enable error display for debugging (remove in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Try to find config.php in common locations
$config_paths = [
    'admin/includes/config.php',
    '../admin/includes/config.php',
    'includes/config.php',
    __DIR__ . '/admin/includes/config.php',
    dirname(__FILE__) . '/admin/includes/config.php'
];

$config_found = false;
$config_error = '';

foreach ($config_paths as $path) {
    if (file_exists($path)) {
        try {
            require_once $path;
            $config_found = true;
            break;
        } catch (Exception $e) {
            $config_error = "Error loading config from {$path}: " . $e->getMessage();
        }
    }
}

// Check if we have the required function
if ($config_found && !function_exists('getDBConnection')) {
    $config_found = false;
    $config_error = "Config file loaded but getDBConnection() function not found.";
}

if (!$config_found) {
    // Try to create a basic connection manually
    $db_host = 'localhost';
    $db_name = 'car_rental_db';
    $db_user = 'root';
    $db_pass = '';
    
    // Check if we can read from environment or common config locations
    try {
        $pdo = new PDO("mysql:host={$db_host};dbname={$db_name};charset=utf8mb4", $db_user, $db_pass, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]);
        $manual_connection = true;
    } catch (PDOException $e) {
        die("<h1 style='color:red'>Configuration Error</h1>
        <p>Could not find config.php and could not connect to database manually.</p>
        <p><strong>Config Error:</strong> " . htmlspecialchars($config_error) . "</p>
        <p><strong>Database Error:</strong> " . htmlspecialchars($e->getMessage()) . "</p>
        <p>Please ensure:</p>
        <ol>
            <li>The system is properly installed</li>
            <li>admin/includes/config.php exists</li>
            <li>Database credentials are correct</li>
        </ol>");
    }
}

// ============================================
// YOUR FIREBASE CONFIGURATION
// ============================================
$firebase_config = [
    'firebase_api_key' => 'AIzaSyARb12c21dVwngIzzULVK9s-zoYIvytJN0',
    'firebase_auth_domain' => 'bacolod-14904.firebaseapp.com',
    'firebase_database_url' => 'https://bacolod-14904-default-rtdb.asia-southeast1.firebasedatabase.app',
    'firebase_project_id' => 'bacolod-14904',
    'firebase_storage_bucket' => 'bacolod-14904.firebasestorage.app',
    'firebase_messaging_sender_id' => '800179035006',
    'firebase_app_id' => '1:800179035006:web:adbf4b2748e68d174e712f',
    'firebase_measurement_id' => 'G-H9VEC8TW2P',
    'firebase_vapid_key' => ''
];

// ============================================
// DO NOT MODIFY BELOW THIS LINE
// ============================================

try {
    // Get database connection
    if (!isset($pdo)) {
        $pdo = getDBConnection();
    }
    
    if (!$pdo) {
        throw new Exception("Database connection failed");
    }
    
    // Check if settings table exists, create if not
    $stmt = $pdo->query("SHOW TABLES LIKE 'settings'");
    if ($stmt->rowCount() == 0) {
        // Create settings table
        $pdo->exec("CREATE TABLE settings (
            id INT AUTO_INCREMENT PRIMARY KEY,
            key_name VARCHAR(255) UNIQUE NOT NULL,
            key_value TEXT,
            description TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    }
    
    // Ensure table has the right structure (compatible with older MySQL)
    try {
        $pdo->exec("ALTER TABLE settings MODIFY COLUMN key_name VARCHAR(255) NOT NULL");
    } catch (Exception $e) {
        // Column might already be the right type, ignore error
    }
    
    // Try to add unique key if it doesn't exist
    try {
        $pdo->exec("ALTER TABLE settings ADD UNIQUE KEY unique_key_name (key_name)");
    } catch (Exception $e) {
        // Key might already exist, ignore error
    }
    
} catch (Exception $e) {
    die("<h1 style='color:red'>Database Error</h1>
    <p>" . htmlspecialchars($e->getMessage()) . "</p>
    <p>Please check your database configuration and ensure the settings table exists.</p>");
}

// Process the form submission
try {
    $updated = [];
    $errors = [];
    
    foreach ($firebase_config as $key => $value) {
        try {
            // Use INSERT ... ON DUPLICATE KEY UPDATE for MySQL
            $stmt = $pdo->prepare("
                INSERT INTO settings (key_name, key_value, description) 
                VALUES (?, ?, ?) 
                ON DUPLICATE KEY UPDATE 
                key_value = VALUES(key_value),
                updated_at = CURRENT_TIMESTAMP
            ");
            
            // Description for each setting
            $descriptions = [
                'firebase_api_key' => 'Firebase API Key',
                'firebase_auth_domain' => 'Firebase Auth Domain',
                'firebase_database_url' => 'Firebase Realtime Database URL',
                'firebase_project_id' => 'Firebase Project ID',
                'firebase_storage_bucket' => 'Firebase Storage Bucket',
                'firebase_messaging_sender_id' => 'Firebase Messaging Sender ID',
                'firebase_app_id' => 'Firebase App ID',
                'firebase_measurement_id' => 'Firebase Measurement ID',
                'firebase_vapid_key' => 'Firebase VAPID Key for Push Notifications'
            ];
            $description = isset($descriptions[$key]) ? $descriptions[$key] : 'Firebase Setting';
            
            $stmt->execute([$key, $value, $description]);
            $updated[] = $key;
        } catch (Exception $e) {
            $errors[] = "Failed to update {$key}: " . $e->getMessage();
        }
    }
    
} catch (Exception $e) {
    die("<h1 style='color:red'>Update Error</h1>
    <p>" . htmlspecialchars($e->getMessage()) . "</p>");
}

// Output success page
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Firebase Configuration Applied</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 p-4 md:p-8">
    <div class="max-w-2xl mx-auto bg-white rounded-xl shadow-lg p-6 md:p-8">
        <div class="flex items-center gap-3 mb-6">
            <svg class="w-10 h-10 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
            </svg>
            <h1 class="text-xl md:text-2xl font-bold text-gray-800">Firebase Configuration Applied!</h1>
        </div>

        <?php if (count($updated) > 0): ?>
        <div class="bg-green-50 border border-green-200 rounded-lg p-4 mb-6">
            <p class="text-green-800 font-medium">Successfully updated <?php echo count($updated); ?> settings:</p>
            <ul class="mt-2 space-y-1 text-sm text-green-700">
                <?php foreach ($updated as $key): 
                    $value = $firebase_config[$key];
                    // Mask sensitive values
                    if (strpos($key, 'api_key') !== false || strpos($key, 'vapid') !== false) {
                        $display = substr($value, 0, 10) . '...' . substr($value, -5);
                    } else {
                        $display = htmlspecialchars($value);
                    }
                ?>
                <li><code class="bg-green-100 px-2 py-0.5 rounded text-xs"><?php echo htmlspecialchars($key); ?></code>: <?php echo $display; ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
        <?php endif; ?>

        <?php if (count($errors) > 0): ?>
        <div class="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
            <p class="text-red-800 font-medium">Some settings could not be updated:</p>
            <ul class="mt-2 space-y-1 text-sm text-red-700">
                <?php foreach ($errors as $error): ?>
                <li><?php echo htmlspecialchars($error); ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
        <?php endif; ?>

        <div class="bg-amber-50 border border-amber-200 rounded-lg p-4 mb-6">
            <h2 class="font-bold text-amber-800 mb-2 flex items-center gap-2">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
                </svg>
                IMPORTANT NEXT STEPS:
            </h2>
            <ol class="list-decimal list-inside space-y-2 text-amber-800 text-sm">
                <li><strong class="text-red-600">DELETE this file</strong> (apply_firebase_config.php) from your server immediately for security.</li>
                <li><strong>Update Firebase Realtime Database Rules</strong> (copy rules below).</li>
                <li><strong>Get your VAPID key</strong> from Firebase Console &gt; Project Settings &gt; Cloud Messaging and add it to Admin Settings.</li>
                <li>Test the chat functionality in user/driver/admin portals.</li>
            </ol>
        </div>

        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
            <h2 class="font-bold text-blue-800 mb-2">Required Firebase Realtime Database Rules:</h2>
            <p class="text-sm text-blue-700 mb-2">Go to <a href="https://console.firebase.google.com/project/bacolod-14904/database/bacolod-14904-default-rtdb/rules" target="_blank" class="underline font-medium">Firebase Console &gt; Realtime Database &gt; Rules</a> and paste:</p>
            <pre class="bg-gray-900 text-green-400 p-4 rounded-lg text-xs overflow-x-auto">{
  "rules": {
    "chats": {
      "$booking_id": {
        ".read": true,
        ".write": true
      }
    }
  }
}</pre>
            <button onclick="copyRules()" class="mt-2 px-3 py-1 bg-blue-600 text-white text-xs rounded hover:bg-blue-700 transition-colors">Copy Rules</button>
        </div>

        <div class="bg-gray-100 rounded-lg p-4">
            <h2 class="font-bold text-gray-800 mb-2">Testing Checklist:</h2>
            <ul class="space-y-2 text-sm text-gray-600">
                <li class="flex items-center gap-2">
                    <input type="checkbox" class="rounded">
                    <span>Run this script and see success message</span>
                </li>
                <li class="flex items-center gap-2">
                    <input type="checkbox" class="rounded">
                    <span>Update Firebase Realtime Database Rules</span>
                </li>
                <li class="flex items-center gap-2">
                    <input type="checkbox" class="rounded">
                    <span>Open user portal and start a chat on a booking</span>
                </li>
                <li class="flex items-center gap-2">
                    <input type="checkbox" class="rounded">
                    <span>Verify messages appear in real-time</span>
                </li>
            </ul>
        </div>
    </div>

    <script>
    function copyRules() {
        const rules = `{
  "rules": {
    "chats": {
      "$booking_id": {
        ".read": true,
        ".write": true
      }
    }
  }
}`;
        navigator.clipboard.writeText(rules).then(() => {
            alert('Rules copied to clipboard!');
        });
    }
    </script>
</body>
</html>
