# Firebase Notification Setup Guide

This guide explains how to set up Firebase Cloud Messaging (FCM) notifications for the Day Loan API.

## Prerequisites

1. Firebase project created at [Firebase Console](https://console.firebase.google.com/)
2. Firebase Admin SDK service account key

## Setup Steps

### 1. Get Firebase Service Account Key

1. Go to [Firebase Console](https://console.firebase.google.com/)
2. Select your project: `finlms-f8227`
3. Go to **Project Settings** (gear icon) > **Service Accounts**
4. Click **Generate New Private Key**
5. Save the JSON file securely (e.g., `config/firebase-service-account.json`)

### 2. Configure Firebase Admin SDK

You have two options:

#### Option A: Using Service Account File (Recommended)

1. Place the service account JSON file in your project:
   ```
   config/firebase-service-account.json
   ```

2. Update `utils/firebase.js` to use the service account file:
   ```javascript
   const serviceAccount = require('../config/firebase-service-account.json');
   admin.initializeApp({
     credential: admin.credential.cert(serviceAccount)
   });
   ```

#### Option B: Using Environment Variables

1. Set the service account JSON as an environment variable:
   ```bash
   export FIREBASE_SERVICE_ACCOUNT='{"type":"service_account","project_id":"..."}'
   ```

2. Or add to your `.env` file:
   ```
   FIREBASE_SERVICE_ACCOUNT={"type":"service_account","project_id":"..."}
   ```

### 3. Add FCM Token Column to Database

Run the SQL script to add the `fcm_token` column to the `staff` table:

```bash
mysql -u root -p xesstech_dayloan < add_fcm_token_to_staff.sql
```

Or manually run:
```sql
ALTER TABLE `staff` 
ADD COLUMN `fcm_token` VARCHAR(500) NULL AFTER `token_expires`;

CREATE INDEX `idx_staff_fcm_token` ON `staff` (`fcm_token`);
```

### 4. Client-Side Setup (Mobile App)

For the mobile app to receive notifications, you'll need to:

1. Install Firebase SDK in your mobile app
2. Get the FCM token from the device:
   ```javascript
   // Example for React Native
   import messaging from '@react-native-firebase/messaging';
   
   const fcmToken = await messaging().getToken();
   ```

3. Register the FCM token with the API when admin logs in

## API Endpoints

### 1. Register FCM Token (Admin)

**Endpoint:** `POST /admin/register_fcm_token`

**Authentication:** Required (Admin token)

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

**Response:**
```json
{
  "status": "success",
  "message": "FCM token registered successfully",
  "data": {
    "admin_id": 1,
    "admin_name": "Admin Name",
    "fcm_token_registered": true
  }
}
```

### 2. Remove FCM Token (Admin)

**Endpoint:** `POST /admin/remove_fcm_token`

**Authentication:** Required (Admin token)

**Response:**
```json
{
  "status": "success",
  "message": "FCM token removed successfully",
  "data": {
    "admin_id": 1,
    "admin_name": "Admin Name"
  }
}
```

### 3. Send Notification to Admins (Agent)

**Endpoint:** `POST /send_notification_to_admins`

**Authentication:** Required (Agent token)

**Request Body:**
```json
{
  "title": "Collection Alert",
  "body": "Agent John Doe collected ₹5000",
  "data": {
    "receipt_id": "123",
    "loan_id": "456",
    "amount": "5000"
  }
}
```

**Response:**
```json
{
  "status": "success",
  "message": "Notification sent to admins successfully",
  "data": {
    "agent_id": 5,
    "agent_name": "John Doe",
    "company_id": 1,
    "notification": {
      "title": "Collection Alert",
      "body": "Agent John Doe collected ₹5000"
    },
    "result": {
      "successCount": 2,
      "failureCount": 0
    }
  }
}
```

## Usage Examples

### Agent Sending Notification After Collection

```javascript
// After successful receipt insertion
const response = await fetch('http://your-api.com/send_notification_to_admins', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${agentAuthToken}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'New Collection',
    body: `Received ₹${amount} from ${customerName}`,
    data: {
      receipt_id: receiptId,
      loan_id: loanId,
      amount: amount.toString()
    }
  })
});
```

### Admin Registering FCM Token

```javascript
// After admin login, get FCM token and register it
const fcmToken = await messaging().getToken();

await fetch('http://your-api.com/admin/register_fcm_token', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${adminAuthToken}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    fcm_token: fcmToken
  })
});
```

## Notes

- The notification is sent to all admins in the same company as the agent
- If an admin doesn't have an FCM token registered, they won't receive notifications
- Invalid or expired FCM tokens are automatically handled by the Firebase service
- Make sure to handle FCM token refresh in your mobile app and update it via the API

## Troubleshooting

1. **Notifications not received:**
   - Verify FCM token is registered correctly
   - Check Firebase service account credentials are correct
   - Ensure the device has internet connection
   - Check Firebase Console for delivery logs

2. **Firebase initialization errors:**
   - Verify service account JSON file is valid
   - Check file path is correct
   - Ensure Firebase Admin SDK is installed: `npm install firebase-admin`

3. **Database errors:**
   - Ensure `fcm_token` column exists in `staff` table
   - Check database connection is working

