# FCM Token-Based Notifications Implementation

## Overview
This implementation switches from Firebase topic-based notifications to token-based notifications with proper database storage and management.

## Changes Made

### 1. Database Changes
- **New Table**: `user_fcm_tokens`
  - Stores FCM tokens per user with device information
  - Tracks: token, user_id, device_name, device_type, browser, platform, last_used_at
  - Automatically deletes tokens when user is deleted (cascade)

### 2. Backend Changes

#### New Model: `UserFcmToken`
- Manages FCM tokens for users
- Relationship with User model
- Tracks device information and last usage

#### Updated `FirebaseService`
- **Token-Based Sending**: Sends notifications directly to user tokens instead of topics
- **Multi-Device Support**: Sends to all registered devices for a user
- **Invalid Token Cleanup**: Automatically removes invalid/expired tokens
- **Sound Support**: Configured for Android and Web with proper sound settings
- **High Priority**: Ensures notifications are delivered even when app is in background

**New Methods**:
- `sendToTokens()`: Send to specific FCM tokens
- `storeToken()`: Store FCM token with device info
- `removeToken()`: Remove specific token
- `removeUserTokens()`: Remove all tokens for a user

#### Updated `FcmController`
- **subscribe**: Now stores token in database with device information
- **unsubscribe**: Removes token from database
- No longer requires user_id in request (uses authenticated user)

#### Updated `AuthController`
- **logout**: Automatically removes all FCM tokens for the user on logout

### 3. Frontend Changes

#### Updated `useFirebaseMessaging.js`
- Detects and sends device information (browser, platform, device type)
- Stores token in database instead of subscribing to topics
- Better error handling

#### Updated `firebase-messaging-sw.js` (Service Worker)
- **Background Notification Support**: Properly handles notifications when app is closed
- **Sound Support**: Configured to play notification sound (`silent: false`)
- **Better Click Handling**: 
  - Focuses existing tab if URL matches
  - Navigates existing tab if app is open
  - Opens new tab if app is closed
- **Push Event Logging**: Added for debugging

## Features

### ✅ Token-Based Notifications
- Direct device targeting (no topics needed)
- More reliable delivery
- Better tracking of active devices

### ✅ Multi-Device Support
- Users can receive notifications on multiple devices
- All active devices get notified

### ✅ Automatic Token Cleanup
- Invalid tokens removed automatically
- Tokens deleted on logout
- Cascade delete when user is deleted

### ✅ Device Information Tracking
- Browser type
- Platform (OS)
- Device type (web/android/ios)
- Last used timestamp

### ✅ Sound & Background Notifications
- Notification sound plays on all platforms
- Background notifications work when app is closed
- High priority delivery for Android

## Testing

### 1. Test Token Registration
1. Login to the application
2. Grant notification permission when prompted
3. Check browser console for "FCM token stored successfully"
4. Verify in database: `SELECT * FROM user_fcm_tokens`

### 2. Test Foreground Notifications
1. Keep the app open in browser
2. Trigger a notification (e.g., create a task)
3. Should see notification popup with sound
4. Should hear notification sound

### 3. Test Background Notifications
1. Close the browser tab or minimize it
2. Trigger a notification
3. Should see system notification with sound
4. Click notification - should open/focus the app

### 4. Test Multi-Device
1. Login on multiple browsers/devices
2. Check database - should see multiple tokens for same user
3. Trigger notification - all devices should receive it

### 5. Test Logout Cleanup
1. Login and register FCM token
2. Verify token in database
3. Logout
4. Check database - token should be deleted

### 6. Test Invalid Token Cleanup
1. Manually invalidate a token in Firebase
2. Try to send notification
3. Invalid token should be removed from database

## Database Queries for Testing

```sql
-- View all FCM tokens
SELECT * FROM user_fcm_tokens;

-- View tokens for specific user
SELECT * FROM user_fcm_tokens WHERE user_id = 1;

-- Count devices per user
SELECT user_id, COUNT(*) as device_count 
FROM user_fcm_tokens 
GROUP BY user_id;

-- View token details with user info
SELECT u.name, u.email, f.device_type, f.browser, f.platform, f.last_used_at
FROM user_fcm_tokens f
JOIN users u ON f.user_id = u.id;
```

## Troubleshooting

### Notifications Not Received
1. Check notification permission in browser settings
2. Verify FCM token is stored in database
3. Check browser console for errors
4. Verify Firebase credentials are correct

### No Sound
1. Check browser notification settings (sound enabled)
2. Check system notification settings
3. Verify `silent: false` in service worker
4. Test with different browsers

### Background Notifications Not Working
1. Verify service worker is registered: `navigator.serviceWorker.getRegistrations()`
2. Check service worker console for errors
3. Ensure HTTPS is used (required for service workers)
4. Clear browser cache and re-register service worker

### Token Not Stored
1. Check API endpoint is accessible: `/api/fcm/subscribe`
2. Verify user is authenticated
3. Check Laravel logs for errors
4. Verify database migration ran successfully

## API Endpoints

### POST /api/fcm/subscribe
Store FCM token for authenticated user

**Request**:
```json
{
  "token": "fcm_token_here",
  "device_type": "web",
  "browser": "Chrome",
  "platform": "Win32",
  "device_name": "Win32 - Chrome"
}
```

**Response**:
```json
{
  "message": "Successfully subscribed to notifications",
  "success": true
}
```

### POST /api/fcm/unsubscribe
Remove FCM token

**Request**:
```json
{
  "token": "fcm_token_here"
}
```

**Response**:
```json
{
  "message": "Successfully unsubscribed from notifications",
  "success": true
}
```

## Migration Path

If you have existing topic-based subscriptions:
1. Users will automatically get new token-based subscriptions on next login
2. Old topic subscriptions will remain but won't be used
3. You can manually clean up old topic subscriptions if needed

## Notes

- Tokens are unique per device/browser
- Same user can have multiple tokens (multiple devices)
- Tokens expire and are automatically cleaned up
- Service worker must be HTTPS (except localhost)
- Notification permission must be granted by user
