# Firebase Real-Time Notifications Setup Guide

This guide will help you complete the Firebase integration for real-time notifications.

## ✅ What's Already Done

- ✅ Backend Firebase SDK installed and configured
- ✅ Frontend Firebase SDK installed
- ✅ Notification services created
- ✅ Firebase composable with sound support
- ✅ Service worker for background notifications
- ✅ Topbar integration
- ✅ API endpoints for FCM token management

## 📋 Setup Steps

### Step 1: Create Firebase Project

1. Go to [Firebase Console](https://console.firebase.google.com/)
2. Click **"Add project"** or select existing project
3. Follow the setup wizard
4. Enable **Google Analytics** (optional)

### Step 2: Enable Cloud Messaging

1. In your Firebase project, go to **Build** > **Cloud Messaging**
2. If prompted, enable Cloud Messaging API

### Step 3: Get Service Account Credentials

1. Go to **Project Settings** (⚙️ icon) > **Service Accounts**
2. Click **"Generate new private key"**
3. Download the JSON file
4. Save it as `storage/firebase-credentials.json` in your Laravel project
5. Update `.env`:
   ```env
   FIREBASE_CREDENTIALS=storage/firebase-credentials.json
   FIREBASE_PROJECT_ID=your-project-id-here
   ```

### Step 4: Add Web App to Firebase

1. Go to **Project Settings** > **General**
2. Scroll to **"Your apps"**
3. Click the **Web** icon (`</>`)
4. Register your app with a nickname (e.g., "Company History Management")
5. Copy the Firebase config object

### Step 5: Get Web Push Certificate (VAPID Key)

1. Go to **Project Settings** > **Cloud Messaging**
2. Scroll to **"Web Push certificates"**
3. Click **"Generate key pair"**
4. Copy the key pair value

### Step 6: Update Environment Variables

Update your `.env` file with all Firebase credentials:

```env
# Backend Firebase Configuration
FIREBASE_CREDENTIALS=storage/firebase-credentials.json
FIREBASE_PROJECT_ID=your-project-id
FIREBASE_DATABASE_URL=https://your-project.firebaseio.com

# Frontend Firebase Configuration (from Step 4)
FIREBASE_API_KEY=your-api-key
FIREBASE_AUTH_DOMAIN=your-project.firebaseapp.com
FIREBASE_MESSAGING_SENDER_ID=123456789
FIREBASE_APP_ID=1:123456789:web:abcdef

# Vite Environment Variables (same values as above)
VITE_FIREBASE_API_KEY=your-api-key
VITE_FIREBASE_AUTH_DOMAIN=your-project.firebaseapp.com
VITE_FIREBASE_PROJECT_ID=your-project-id
VITE_FIREBASE_MESSAGING_SENDER_ID=123456789
VITE_FIREBASE_APP_ID=1:123456789:web:abcdef
VITE_FIREBASE_VAPID_KEY=your-vapid-key-from-step-5
```

### Step 7: Update Service Worker

Edit `public/firebase-messaging-sw.js` and replace placeholder values:

```javascript
firebase.initializeApp({
    apiKey: "YOUR_API_KEY",              // Replace with your API key
    authDomain: "YOUR_AUTH_DOMAIN",      // Replace with your auth domain
    projectId: "YOUR_PROJECT_ID",         // Replace with your project ID
    messagingSenderId: "YOUR_SENDER_ID",  // Replace with your sender ID
    appId: "YOUR_APP_ID"                  // Replace with your app ID
})
```

### Step 8: Add Notification Sound

1. Download a notification sound (MP3 format)
   - Recommended sources in `public/sounds/README.md`
2. Save it as `public/sounds/notification.mp3`
3. Test the sound file works in your browser

### Step 9: Build Frontend Assets

```bash
npm run build
# or for development
npm run dev
```

### Step 10: Test the Integration

1. **Clear cache and restart:**
   ```bash
   php artisan cache:clear
   php artisan config:clear
   ```

2. **Login to the application**

3. **Allow notification permissions** when prompted

4. **Create or update a task** assigned to your user

5. **You should:**
   - See a browser notification
   - Hear the notification sound
   - See the notification count update in the topbar
   - See the notification in the dropdown

## 🔧 Troubleshooting

### Service Worker Not Registering

```bash
# Clear browser cache
# Check browser console for errors
# Verify firebase-messaging-sw.js has correct config
```

### Notifications Not Received

1. Check Firebase Console > Cloud Messaging for errors
2. Verify service account JSON file exists and is valid
3. Check browser console for token errors
4. Ensure user is subscribed to topic (check Network tab for `/api/fcm/subscribe` call)

### Sound Not Playing

1. Verify `public/sounds/notification.mp3` exists
2. Test the file directly in browser: `http://localhost:8000/sounds/notification.mp3`
3. Check browser console for audio errors
4. Some browsers block autoplay - user interaction may be required first

### Firebase Not Initializing

1. Check all VITE_ environment variables are set correctly
2. Run `npm run dev` or `npm run build` after changing `.env`
3. Restart Vite dev server if running

## 📱 Testing Checklist

- [ ] Firebase credentials configured
- [ ] Service worker updated with real config
- [ ] Environment variables set
- [ ] Frontend assets built
- [ ] Browser notification permission granted
- [ ] Can create task and receive notification
- [ ] Notification sound plays
- [ ] Notification appears in topbar dropdown
- [ ] Clicking notification navigates to task
- [ ] Background notifications work (when tab is not focused)

## 🎯 How It Works

### Flow Diagram

```
User Creates Task
       ↓
TaskService creates task
       ↓
NotificationService creates DB notification
       ↓
FirebaseService sends FCM message to topic "user_{id}"
       ↓
       ├─→ [App in Foreground]
       │   └─→ onMessage listener in useFirebaseMessaging
       │       ├─→ Play notification sound
       │       ├─→ Show browser notification
       │       ├─→ Reload notifications via Inertia
       │       └─→ Show toast
       │
       └─→ [App in Background/Closed]
           └─→ firebase-messaging-sw.js receives message
               ├─→ Show browser notification
               └─→ Handle click to navigate to task
```

### Topic Subscription

- Each user subscribes to a topic: `user_{user_id}`
- When a notification is created, it's sent to the user's topic
- All devices/tabs logged in as that user receive the notification

## 📚 Additional Resources

- [Firebase Cloud Messaging Docs](https://firebase.google.com/docs/cloud-messaging)
- [Kreait Firebase PHP SDK](https://firebase-php.readthedocs.io/)
- [Firebase JavaScript SDK](https://firebase.google.com/docs/web/setup)

## 🆘 Need Help?

If you encounter issues:
1. Check browser console for errors
2. Check Laravel logs: `storage/logs/laravel.log`
3. Check Firebase Console > Cloud Messaging for delivery reports
4. Verify all environment variables are correct
