# FCM Notification API Documentation

## Overview

This API provides endpoints for sending push notifications via Firebase Cloud Messaging (FCM) v1. The API supports sending notifications to specific topics or to all devices in specific apps filtered by platform and app ID.

## Base URL

```
https://your-domain.com/backend/
```

## Authentication

Currently, no authentication is required. The API uses Firebase service account credentials configured on the server.

## CORS

All endpoints support CORS and can be called from mobile applications. Preflight OPTIONS requests are handled automatically.

## Request Format

All endpoints accept both:
- **JSON**: `Content-Type: application/json`
- **Form Data**: `Content-Type: application/x-www-form-urlencoded`

---

## Endpoints

### 1. Send Notification to Topic

Send a push notification to all devices subscribed to a specific topic.

**Endpoint:** `POST /send_notification.php`

#### Request Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `title` | string | Yes | Notification title |
| `message` | string | Yes | Notification message body |
| `topic` | string | Yes | FCM topic name (devices must be subscribed to this topic) |

#### Request Example (JSON)

```json
{
  "title": "New Order",
  "message": "You have received a new order",
  "topic": "orders"
}
```

#### Request Example (Form Data)

```
title=New Order&message=You have received a new order&topic=orders
```

#### Success Response (200 OK)

```json
{
  "success": true,
  "message": "Notification sent successfully",
  "data": {
    "name": "projects/salla-spare/messages/0:1234567890"
  }
}
```

#### Error Responses

**400 Bad Request** - Missing or invalid parameters
```json
{
  "success": false,
  "error": "Missing required fields: title, message"
}
```

**405 Method Not Allowed** - Wrong HTTP method
```json
{
  "success": false,
  "error": "Method not allowed. Only POST requests are accepted."
}
```

**500 Internal Server Error** - FCM API error or server error
```json
{
  "success": false,
  "error": "Failed to send notification",
  "fcm_response": {
    "error": {
      "code": 400,
      "message": "Invalid topic name",
      "status": "INVALID_ARGUMENT"
    }
  }
}
```

---

### 2. Create Campaign Notification

Send a campaign notification to all devices in a specific app, filtered by platform (Android/iOS).

**Endpoint:** `POST /create_campaign.php`

#### Request Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `title` | string | Yes | Notification title |
| `message` | string | Yes | Notification message body |
| `platform` | string | Yes | Platform: `"android"`, `"ios"`, or `"both"` (case-insensitive) |
| `app_id` | string | Yes | App ID: `"com.example.vendorSallaSpare"` or `"com.example.sallaSpare"` |

#### Valid Values

**Platform:**
- `android` - Send to Android devices only
- `ios` - Send to iOS devices only
- `both` - Send to both Android and iOS devices

**App ID:**
- `com.example.vendorSallaSpare`
- `com.example.sallaSpare`

#### Topic Naming Convention

The API automatically generates topic names using the format:
```
{platform}_{appId}_all
```

Examples:
- Android devices in `com.example.vendorSallaSpare`: `android_com.example.vendorSallaSpare_all`
- iOS devices in `com.example.sallaSpare`: `ios_com.example.sallaSpare_all`

**Important:** Mobile apps must subscribe their devices to these topics for notifications to be received.

#### Request Example (JSON) - Single Platform

```json
{
  "title": "Special Offer",
  "message": "Get 50% off on all products today!",
  "platform": "android",
  "app_id": "com.example.vendorSallaSpare"
}
```

#### Request Example (JSON) - Both Platforms

```json
{
  "title": "Special Offer",
  "message": "Get 50% off on all products today!",
  "platform": "both",
  "app_id": "com.example.sallaSpare"
}
```

#### Success Response (200 OK) - Single Platform

```json
{
  "success": true,
  "message": "Campaign notification sent successfully",
  "platform": "android",
  "app_id": "com.example.vendorSallaSpare",
  "topic": "android_com.example.vendorSallaSpare_all",
  "data": {
    "name": "projects/salla-spare/messages/0:1234567890"
  }
}
```

#### Success Response (200 OK) - Both Platforms

```json
{
  "success": true,
  "message": "Campaign notifications sent successfully to both platforms",
  "app_id": "com.example.sallaSpare",
  "results": [
    {
      "platform": "android",
      "topic": "android_com.example.sallaSpare_all",
      "status": "success"
    },
    {
      "platform": "ios",
      "topic": "ios_com.example.sallaSpare_all",
      "status": "success"
    }
  ]
}
```

#### Partial Success Response (207 Multi-Status) - Both Platforms

When one platform succeeds and the other fails:

```json
{
  "success": false,
  "message": "Campaign notifications sent with partial success",
  "app_id": "com.example.sallaSpare",
  "results": [
    {
      "platform": "android",
      "topic": "android_com.example.sallaSpare_all",
      "status": "success"
    },
    {
      "platform": "ios",
      "topic": "ios_com.example.sallaSpare_all",
      "status": "failed",
      "error": "Topic not found"
    }
  ]
}
```

#### Error Responses

**400 Bad Request** - Validation errors
```json
{
  "success": false,
  "error": "Validation failed: platform must be one of: android, ios, both, app_id must be one of: com.example.vendorSallaSpare, com.example.sallaSpare"
}
```

**500 Internal Server Error** - FCM API error or server error
```json
{
  "success": false,
  "error": "Failed to send campaign notification",
  "platform": "android",
  "app_id": "com.example.vendorSallaSpare",
  "topic": "android_com.example.vendorSallaSpare_all",
  "fcm_response": {
    "error": {
      "code": 404,
      "message": "Topic not found",
      "status": "NOT_FOUND"
    }
  }
}
```

---

## Error Handling

### HTTP Status Codes

| Code | Description |
|------|-------------|
| 200 | Success |
| 207 | Multi-Status (partial success for "both" platform) |
| 400 | Bad Request (validation errors, invalid JSON) |
| 405 | Method Not Allowed (wrong HTTP method) |
| 500 | Internal Server Error (FCM API errors, server errors) |

### Error Response Format

All error responses follow this structure:

```json
{
  "success": false,
  "error": "Error message description"
}
```

Additional fields may be included depending on the error type (e.g., `fcm_response`, `results`).

---

## Mobile App Integration

### Topic Subscription

For campaign notifications to work, mobile apps must subscribe devices to the appropriate topics when the app launches or when a user logs in.

#### Example Topic Subscription (Flutter/Dart)

```dart
import 'package:firebase_messaging/firebase_messaging.dart';

Future<void> subscribeToCampaignTopics() async {
  FirebaseMessaging messaging = FirebaseMessaging.instance;
  
  // Get platform
  String platform = Platform.isAndroid ? 'android' : 'ios';
  
  // Get app ID (from your app configuration)
  String appId = 'com.example.vendorSallaSpare';
  
  // Build topic name
  String topic = '${platform}_${appId}_all';
  
  // Subscribe to topic
  await messaging.subscribeToTopic(topic);
  print('Subscribed to topic: $topic');
}
```

#### Example Topic Subscription (Android/Java)

```java
FirebaseMessaging messaging = FirebaseMessaging.getInstance();
String platform = "android";
String appId = "com.example.vendorSallaSpare";
String topic = platform + "_" + appId + "_all";

messaging.subscribeToTopic(topic)
    .addOnCompleteListener(task -> {
        if (task.isSuccessful()) {
            Log.d("FCM", "Subscribed to topic: " + topic);
        } else {
            Log.e("FCM", "Failed to subscribe to topic: " + topic);
        }
    });
```

#### Example Topic Subscription (iOS/Swift)

```swift
import FirebaseMessaging

let platform = "ios"
let appId = "com.example.sallaSpare"
let topic = "\(platform)_\(appId)_all"

Messaging.messaging().subscribe(toTopic: topic) { error in
    if let error = error {
        print("Error subscribing to topic: \(error)")
    } else {
        print("Subscribed to topic: \(topic)")
    }
}
```

---

## Testing

### Using cURL

#### Test send_notification.php

```bash
curl -X POST https://your-domain.com/backend/send_notification.php \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Test Notification",
    "message": "This is a test message",
    "topic": "test_topic"
  }'
```

#### Test create_campaign.php (Single Platform)

```bash
curl -X POST https://your-domain.com/backend/create_campaign.php \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Campaign Test",
    "message": "This is a campaign test",
    "platform": "android",
    "app_id": "com.example.vendorSallaSpare"
  }'
```

#### Test create_campaign.php (Both Platforms)

```bash
curl -X POST https://your-domain.com/backend/create_campaign.php \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Campaign Test",
    "message": "This is a campaign test",
    "platform": "both",
    "app_id": "com.example.sallaSpare"
  }'
```

### Using Postman

1. Set method to **POST**
2. Set URL to the endpoint
3. In **Headers**, add: `Content-Type: application/json`
4. In **Body**, select **raw** and **JSON**, then paste the JSON request
5. Click **Send**

---

## Requirements

### Server Requirements

- PHP 7.4 or higher
- cURL extension enabled
- Firebase service account JSON file configured
- Google API Client library (installed via Composer)

### Firebase Configuration

1. Firebase project: `salla-spare`
2. Service account file: `salla-spare-firebase-adminsdk-fbsvc-51a3557f4e.json`
3. FCM v1 API enabled

### Mobile App Requirements

- Firebase SDK integrated
- FCM token obtained
- Devices subscribed to appropriate topics
- Push notification permissions granted (iOS)

---

## Notes

1. **Topic Names**: Topic names must follow FCM naming rules:
   - Only lowercase letters, numbers, and hyphens/underscores
   - No spaces or special characters
   - Maximum 100 characters

2. **Rate Limits**: FCM has rate limits. Check [Firebase documentation](https://firebase.google.com/docs/cloud-messaging) for current limits.

3. **Topic Subscription**: Devices must be subscribed to topics before they can receive notifications sent to those topics.

4. **Platform Case**: Platform values are case-insensitive (`android`, `Android`, `ANDROID` all work).

5. **App ID Validation**: Only the two specified app IDs are accepted. Adding new app IDs requires updating the `VALID_APP_IDS` constant in `create_campaign.php`.

---

## Support

For issues or questions, please contact the development team or refer to:
- [Firebase Cloud Messaging Documentation](https://firebase.google.com/docs/cloud-messaging)
- [FCM v1 API Reference](https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages)

