# Firebase Chat Setup Guide

This guide explains how to properly configure Firebase for the real-time chat functionality in VeloDrive.

## Quick Diagnostic

First, run the diagnostic tool to check your current setup:
**`https://yourdomain.com/test_firebase_config.php`**

This will tell you exactly what's wrong with your configuration.

---

## Overview

The chat system uses **Firebase Realtime Database** for instant message delivery between:
- Customers (user portal)
- Drivers (driver portal)
- Administrators (admin portal)

**Fallback Mode:** If Firebase is unavailable (blocked by hosting), the chat automatically falls back to local database polling every 3 seconds.

## Your Firebase Configuration

Your provided Firebase config for project **bacolod-14904**:

```javascript
const firebaseConfig = {
  apiKey: "AIzaSyARb12c21dVwngIzzULVK9s-zoYIvytJN0",
  authDomain: "bacolod-14904.firebaseapp.com",
  databaseURL: "https://bacolod-14904-default-rtdb.asia-southeast1.firebasedatabase.app",
  projectId: "bacolod-14904",
  storageBucket: "bacolod-14904.firebasestorage.app",
  messagingSenderId: "800179035006",
  appId: "1:800179035006:web:adbf4b2748e68d174e712f",
  measurementId: "G-H9VEC8TW2P"
};
```

## Step-by-Step Setup

### Step 1: Apply Configuration to Database

1. Upload `apply_firebase_config.php` to your server root
2. Run it via browser: `https://yourdomain.com/apply_firebase_config.php`
3. **DELETE the file immediately after use** (security risk)

### Step 2: Configure Firebase Realtime Database Rules

This is the **most common cause** of the "loading forever" issue.

Go to [Firebase Console](https://console.firebase.google.com/) → Your Project → Realtime Database → Rules

#### Option A: Public Access (Easiest - for development/testing)
```json
{
  "rules": {
    "chats": {
      "$booking_id": {
        ".read": true,
        ".write": true,
        "$message_id": {
          ".validate": "newData.hasChild('sender_id') && newData.hasChild('message') && newData.hasChild('timestamp')"
        }
      }
    }
  }
}
```

#### Option B: Authenticated Access (Recommended for production)
```json
{
  "rules": {
    "chats": {
      "$booking_id": {
        ".read": "auth != null",
        ".write": "auth != null",
        "$message_id": {
          ".validate": "newData.hasChild('sender_id') && newData.hasChild('message') && newData.hasChild('timestamp')"
        }
      }
    }
  }
}
```

**Note:** The current implementation does NOT use Firebase Authentication, so use Option A unless you plan to add Firebase Auth.

### Step 3: Verify Database URL

**Important:** Your database URL uses the **asia-southeast1** region:
```
https://bacolod-14904-default-rtdb.asia-southeast1.firebasedatabase.app
```

Make sure this matches exactly in your Firebase Console. The region-specific URL is correct for your project.

### Step 4: Enable Realtime Database

1. Go to Firebase Console → Build → Realtime Database
2. Click "Create Database"
3. Choose your location (asia-southeast1 for your project)
4. Start in **test mode** (allows read/write) or set rules manually

## InfinityFree Hosting Limitations

**⚠️ Important:** If you're using InfinityFree hosting (or other free hosting), they block outbound connections to Firebase Realtime Database.

**The chat now automatically detects this and uses "Fallback Mode":**
- Messages are stored in your local MySQL database
- The chat polls for new messages every 3 seconds
- This works fine but has a slight delay compared to true real-time

**No action required** - the system handles this automatically!

---

## Troubleshooting

### Issue: Chat Keeps Loading / Spinner Never Stops

**First, check if you're on InfinityFree:**
- Run `test_firebase_config.php` 
- If it says "InfinityFree Hosting Detected", the fallback mode will activate automatically
- Wait 10-15 seconds for it to switch to fallback mode

**For other hosting:**

1. **Firebase Rules Not Set** (Most Common)
   - Check your Realtime Database Rules
   - Ensure `.read` and `.write` are set to `true`

2. **Wrong Database URL**
   - Verify the URL matches Firebase Console
   - Your URL: `https://bacolod-14904-default-rtdb.asia-southeast1.firebasedatabase.app`

3. **Configuration Not Applied**
   - Run `apply_firebase_config.php`
   - Check admin settings page

4. **Firebase SDK Not Loading**
   - Check browser console for errors
   - Ensure internet connectivity

### Issue: Chat Closes When Sending Message / Form Submits and Page Reloads

**This is now FIXED in the latest update.** 

If you're still experiencing this:

1. **Clear your browser cache** (Ctrl+Shift+R or Cmd+Shift+R)
2. **Make sure all files are uploaded**:
   - `admin/includes/chat_helper.js`
   - `user/chat.php`
   - `driver/chat.php`
   - `admin/chat.php`
3. **Check browser console for JavaScript errors**
4. **Verify the form has the correct attributes**:
   ```html
   <form id="chatForm" onsubmit="return false;" action="javascript:void(0);">
   ```

### Issue: "Permission Denied" Error

This means your Firebase Rules are too restrictive. Use the public access rules above or ensure users are authenticated.

### Issue: "Configuration Invalid" Error

One or more config values are missing or are still placeholders. Run `apply_firebase_config.php` with your correct values.

### Debug Steps

1. Open browser Developer Tools (F12)
2. Check Console for `[Firebase]` and `[ChatHelper]` log messages
3. Look for specific error codes
4. Check Network tab to see if config is loading from `get_firebase_config.php`

## Database Structure

Messages are stored at this path:
```
/chats/{booking_id}/{message_id}
```

Each message has this structure:
```json
{
  "sender_id": "123",
  "sender_name": "John Doe",
  "sender_type": "customer",
  "message": "Hello!",
  "timestamp": 1234567890
}
```

## Security Considerations

### Current Implementation (No Firebase Auth)
- Anyone with the config can read/write chat messages
- Suitable for trusted environments
- Consider adding Firebase Auth for production

### Recommended for Production
1. Implement Firebase Authentication
2. Use authenticated rules (`auth != null`)
3. Add data validation rules
4. Implement message size limits

## Files Modified

1. `apply_firebase_config.php` - Updated with your config values
2. `admin/includes/firebase_config.js` - Enhanced error handling
3. `admin/includes/chat_helper.js` - Better diagnostics and error messages
4. `admin/includes/migrations.php` - Updated default Firebase config
5. `api/get_firebase_config.php` - Added debug logging

## Support

If issues persist:
1. Check browser console for error messages
2. Verify all config values in database via admin settings
3. Test Firebase rules in Firebase Console simulator
4. Check that Realtime Database is enabled (not Firestore)
