# Order Assignment Notification System

This document explains how to set up and use the notification system for order assignments to pickers.

## Overview

The notification system sends push notifications to pickers when orders are assigned to them. It uses Firebase Cloud Messaging (FCM) to deliver notifications to mobile devices.

## Setup Requirements

### 1. Firebase Configuration

1. Set up a Firebase project and get your FCM server key
2. Add the FCM key to your `.env` file:
   ```
   FCM_KEY=your_fcm_server_key_here
   ```

### 2. Database Migration

The system automatically adds the `fcmToken` field to the `users` table. Run the migration:
```bash
php artisan migrate
```

## How It Works

### 1. FCM Token Registration

Staff members (pickers) need to register their FCM tokens when they log into the mobile app:

**API Endpoint:** `POST /api/staff/update-fcm-token`

**Headers:**
```
Authorization: Bearer {jwt_token}
Content-Type: application/json
```

**Request Body:**
```json
{
    "fcm_token": "fcm_token_from_mobile_device"
}
```

**Response:**
```json
{
    "status": true,
    "message": "FCM token updated successfully"
}
```

### 2. Order Assignment Notifications

When orders are assigned to pickers through the web interface, the system automatically sends notifications to the assigned picker.

**Triggered by:**
- `applyOrderOperation` method in `OrderfulfillmentController`
- `held1` method in `OrderfulfillmentController` (when type is 'picker')

**Notification Content:**
- Title: Customizable through notification templates
- Body: Includes order count, first order number, and customer name
- Data: Order IDs, picker ID, order count for app navigation

### 3. Notification Templates

The system uses notification templates that can be customized in the admin panel:

**Default Template:**
- Subject: "New Order Assignment - {order_count} order(s)"
- SMS Body: "Hi {picker_name}, you have been assigned {order_count} new order(s) to pick. First order: {first_order_number} for {customer_name}."

**Available Placeholders:**
- `{picker_name}` - Picker's full name
- `{order_count}` - Number of orders assigned
- `{first_order_number}` - Invoice number of the first order
- `{customer_name}` - Customer name from the first order

## Mobile App Integration

### 1. FCM Token Generation

In your mobile app, generate FCM tokens when the user logs in:

```javascript
// Example for React Native
import messaging from '@react-native-firebase/messaging';

async function requestUserPermission() {
  const authStatus = await messaging().requestPermission();
  const enabled = authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
                  authStatus === messaging.AuthorizationStatus.PROVISIONAL;

  if (enabled) {
    const fcmToken = await messaging().getToken();
    // Send this token to the server
    await updateFcmToken(fcmToken);
  }
}
```

### 2. Sending FCM Token to Server

```javascript
async function updateFcmToken(token) {
  try {
    const response = await fetch('/api/staff/update-fcm-token', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${userToken}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        fcm_token: token
      })
    });
    
    const result = await response.json();
    console.log('FCM token updated:', result);
  } catch (error) {
    console.error('Failed to update FCM token:', error);
  }
}
```

### 3. Handling Incoming Notifications

```javascript
// Handle notifications when app is in foreground
messaging().onMessage(async remoteMessage => {
  console.log('Received foreground message:', remoteMessage);
  
  // Show local notification or update UI
  if (remoteMessage.data.type === 'order_assignment') {
    // Navigate to picking orders or show notification
    const orderIds = remoteMessage.data.order_ids.split(',');
    // Handle order assignment notification
  }
});

// Handle notifications when app is in background
messaging().onNotificationOpenedApp(remoteMessage => {
  console.log('App opened from background:', remoteMessage);
  
  if (remoteMessage.data.type === 'order_assignment') {
    // Navigate to picking orders
    const orderIds = remoteMessage.data.order_ids.split(',');
    // Navigate to order details
  }
});
```

## Testing

### 1. Test FCM Token Registration

1. Log in as a staff member through the mobile app
2. Check that the FCM token is sent to the server
3. Verify the token is stored in the database

### 2. Test Order Assignment Notifications

1. Assign orders to a picker through the web interface
2. Check the picker's mobile device for notifications
3. Verify notification content and data payload

### 3. Check Logs

Monitor the Laravel logs for notification-related messages:
```bash
tail -f storage/logs/laravel.log | grep "Order assignment notification"
```

## Troubleshooting

### Common Issues

1. **No notifications received:**
   - Check if FCM token is properly stored in the database
   - Verify Firebase configuration and FCM key
   - Check mobile app permissions for notifications

2. **Invalid FCM token:**
   - Ensure the token is generated correctly in the mobile app
   - Check if the token is being sent properly to the server

3. **Notification template not found:**
   - The system automatically creates a default template
   - Check the `notification_templates` table for the `order_assignment` template

### Debug Information

The system logs detailed information about notification sending:

- Success: "Order assignment notification sent to picker {id}: {result}"
- Warning: "No FCM token found for picker: {id}"
- Error: "Error sending order assignment notification: {error}"

## Security Considerations

1. **FCM Token Security:**
   - FCM tokens should be transmitted over HTTPS
   - Tokens should be validated on the server side
   - Consider token expiration and refresh mechanisms

2. **API Security:**
   - All staff API endpoints require JWT authentication
   - Validate user permissions before sending notifications
   - Rate limit FCM token update requests

## Future Enhancements

1. **Notification Preferences:**
   - Allow users to configure notification types
   - Add notification scheduling options
   - Support for different notification channels (SMS, email)

2. **Advanced Features:**
   - Notification history and read status
   - Bulk notification sending
   - Notification templates for different order types
   - Real-time notification status tracking 