# 📖 Guide d'Intégration pour Applications Tierces
## Comment envoyer des notifications Push FCM à vos utilisateurs

Ce guide explique pas-à-pas comment une application tierce (mobile Android/iOS, site Web, ou serveur backend) s'intègre avec le service de notification centralisé.

---

## 🧭 Vue d'ensemble du fonctionnement

Le système repose sur **3 étapes simples** :

```mermaid
sequenceDiagram
    autonumber
    actor User as Utilisateur Mobile (Android/iOS)
    participant ClientApp as Application Mobile Tierce
    participant BackendTiers as Backend de l'App Tierce
    participant FCMService as Service Notification (Ce Projet)
    participant GoogleFCM as Firebase Cloud Messaging (Google)

    Note over ClientApp,GoogleFCM: Étape 1 : Enregistrement du Token
    ClientApp->>GoogleFCM: 1. Demande du token FCM
    GoogleFCM-->>ClientApp: Retourne le token FCM de l'appareil
    ClientApp->>FCMService: 2. POST /api/register_device.php (Token + User ID)
    FCMService-->>ClientApp: Confirmation enregistrement

    Note over BackendTiers,GoogleFCM: Étape 2 : Envoi / Programmation d'une Notification
    BackendTiers->>FCMService: 3. POST /api/create_notification.php (Titre, Message, Cible)
    FCMService-->>BackendTiers: Statut 'a_envoyer' ou 'envoye' (avec ID notif)

    Note over FCMService,User: Étape 3 : Distribution
    FCMService->>GoogleFCM: 4. Envoi FCM HTTP v1 (JWT OAuth2)
    GoogleFCM->>User: 5. Réception de la notification Push sur le téléphone
```

---

## 🔑 Prérequis : Obtenir votre Clé API (`X-API-KEY`)

Chaque application tierce dispose de sa propre clé d'accès sécurisée.  
Elle doit être fournie dans les en-têtes HTTP de chaque requête :

```http
X-API-KEY: VOTRE_CLE_API_APPLICATION
```

*(Exemple : `app_ecommerce_key_9f8a7b6c5d4e3f2a`)*

---

## 📱 Étape 1 : Enregistrer le token FCM de l'appareil mobile

Dès que l'application mobile démarre (ou que l'utilisateur se connecte), elle récupère le token FCM auprès du SDK Firebase et l'enregistre sur le service.

### Point d'accès
- **URL** : `POST /api/register_device.php`
- **Header obligatoire** : `X-API-KEY: VOTRE_CLE_API`
- **Content-Type** : `application/json`

### Corps de la requête (JSON)
```json
{
  "fcm_token": "fXy89z...token_fourni_par_firebase_sdk...",
  "platform": "android",
  "external_user_id": "USER_4589",
  "device_model": "Samsung Galaxy S23",
  "app_version": "2.1.0"
}
```

### Paramètres détaillés :
| Paramètre | Type | Requis | Description |
|---|---|---|---|
| `fcm_token` | String | **Oui** | Le token unique de l'appareil généré par Firebase. |
| `platform` | String | **Oui** | Plateforme : `"android"`, `"ios"` ou `"web"`. |
| `external_user_id` | String | *Conseillé* | L'identifiant de votre utilisateur dans votre base (ex: ID client, ID chauffeur). Permet de lui envoyer des notifications directement par son ID. |
| `device_model` | String | Non | Modèle de téléphone (ex: `"iPhone 14"`, `"Pixel 7"`). |
| `app_version` | String | Non | Version de votre application (ex: `"1.0.4"`). |

### Exemple de code (cURL)
```bash
curl -X POST "https://votre-serveur.com/api/register_device.php" \
  -H "X-API-KEY: VOTRE_CLE_API" \
  -H "Content-Type: application/json" \
  -d '{
    "fcm_token": "c8J-98x_kLm...",
    "platform": "android",
    "external_user_id": "USER_4589",
    "device_model": "Samsung Galaxy A53"
  }'
```

### Exemple de code dans une app mobile (Flutter / Dart)
```dart
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:firebase_messaging/firebase_messaging.dart';

Future<void> registerDeviceToNotificationService(String userId) async {
  String? token = await FirebaseMessaging.instance.getToken();
  if (token == null) return;

  final response = await http.post(
    Uri.parse('https://votre-serveur.com/api/register_device.php'),
    headers: {
      'Content-Type': 'application/json',
      'X-API-KEY': 'VOTRE_CLE_API',
    },
    body: jsonEncode({
      'fcm_token': token,
      'platform': 'android', // ou Platform.isIOS ? 'ios' : 'android'
      'external_user_id': userId,
    }),
  );

  print('Réponse enregistrement: ${response.body}');
}
```

---

## ✉️ Étape 2 : Envoyer ou Programmer une Notification

Depuis votre **backend tiers** (PHP, Node.js, Python, Java, etc.) ou votre CRM, vous pouvez créer une notification.

### Point d'accès
- **URL** : `POST /api/create_notification.php`
- **Header obligatoire** : `X-API-KEY: VOTRE_CLE_API`
- **Content-Type** : `application/json`

---

### Cas 1 : Envoyer à UN utilisateur spécifique (par son ID)
Idéal pour les alertes de commande, livraison, facture, message privé :

```json
{
  "title": "📦 Commande expédiée !",
  "body": "Votre colis #12345 est en cours de livraison.",
  "target_type": "user",
  "target_value": "USER_4589",
  "immediate_send": true,
  "data": {
    "screen": "order_tracking",
    "order_id": "12345"
  }
}
```

---

### Cas 2 : Envoyer à TOUS vos utilisateurs (Notification générale)
Idéal pour une annonce, promo ou maintenance :

```json
{
  "title": "🎉 Soldes d'été !",
  "body": "Jusqu'à -50% dès maintenant sur toute la boutique.",
  "target_type": "all_users",
  "priority": "high",
  "immediate_send": false
}
```
*(Avec `immediate_send: false`, la notification sera enregistrée avec le statut **`a_envoyer`** et traitée par la file d'attente/worker).*

---

### Cas 3 : Envoyer uniquement aux utilisateurs Android ou iOS
```json
{
  "title": "Mise à jour disponible",
  "body": "Une nouvelle version est disponible sur le Play Store.",
  "target_type": "platform",
  "target_value": "android",
  "immediate_send": true
}
```

---

### Cas 4 : Envoyer directement à un Token FCM unique
```json
{
  "title": "Test de notification",
  "body": "Message direct au terminal de test.",
  "target_type": "single_device",
  "target_value": "c8J-98x_kLm...token...",
  "immediate_send": true
}
```

---

### Résumé des paramètres de création :
| Paramètre | Type | Requis | Valeurs possibles / Description |
|---|---|---|---|
| `title` | String | **Oui** | Titre de la notification affiché sur le téléphone. |
| `body` | String | **Oui** | Texte du message. |
| `target_type` | String | Non | `"all_users"` *(défaut)*, `"user"`, `"platform"`, `"single_device"`. |
| `target_value` | String | Selon type | ID de l'utilisateur (`"USER_4589"`), plateforme (`"android"`/`"ios"`), ou token direct. |
| `image_url` | String | Non | URL d'une image (bannière grand format). |
| `data` | Object | Non | Objet JSON de données personnalisées transmises à l'application (ex: `{"page": "promo", "id": 12}`). |
| `priority` | String | Non | `"high"` *(défaut)* ou `"normal"`. |
| `scheduled_at` | String | Non | Date/Heure d'envoi différé au format `"YYYY-MM-DD HH:MM:SS"`. |
| `immediate_send` | Boolean | Non | `true` pour envoyer sur-le-champ, `false` pour laisser en file `a_envoyer`. |

---

### Exemples d'implémentation Backend & Frontend

#### 🐘 En PHP : Classe Client Réutilisable (POO)
Voici une classe PHP légère et autonome que vous pouvez inclure dans n'importe quel projet tiers (Laravel, Symfony, WordPress ou PHP natif) :

```php
<?php
/**
 * Client PHP pour le Service de Notification FCM
 */
class FcmNotificationClient
{
    private string $baseUrl;
    private string $apiKey;

    public function __construct(string $baseUrl, string $apiKey)
    {
        $this->baseUrl = rtrim($baseUrl, '/');
        $this->apiKey  = $apiKey;
    }

    /**
     * Enregistre le token d'un appareil (Android/iOS)
     */
    public function registerDevice(string $token, string $platform = 'android', ?string $userId = null): array
    {
        return $this->request('POST', '/api/register_device.php', [
            'fcm_token'        => $token,
            'platform'         => $platform,
            'external_user_id' => $userId
        ]);
    }

    /**
     * Envoie une notification à un utilisateur spécifique (par son ID client)
     */
    public function sendToUser(string $userId, string $title, string $body, array $data = [], bool $immediate = true): array
    {
        return $this->request('POST', '/api/create_notification.php', [
            'title'          => $title,
            'body'           => $body,
            'target_type'    => 'user',
            'target_value'   => $userId,
            'data'           => $data,
            'immediate_send' => $immediate
        ]);
    }

    /**
     * Diffuse une notification à TOUS les utilisateurs
     */
    public function broadcast(string $title, string $body, array $data = [], bool $immediate = false): array
    {
        return $this->request('POST', '/api/create_notification.php', [
            'title'          => $title,
            'body'           => $body,
            'target_type'    => 'all_users',
            'data'           => $data,
            'immediate_send' => $immediate
        ]);
    }

    /**
     * Récupère le statut d'une notification
     */
    public function getStatus(int $notificationId): array
    {
        return $this->request('GET', '/api/notification_status.php?id=' . $notificationId);
    }

    /**
     * Envoi de requête HTTP cURL
     */
    private function request(string $method, string $endpoint, array $body = []): array
    {
        $url = $this->baseUrl . $endpoint;
        $ch = curl_init($url);

        $headers = [
            'X-API-KEY: ' . $this->apiKey,
            'Accept: application/json'
        ];

        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
            $headers[] = 'Content-Type: application/json';
        }

        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER     => $headers,
            CURLOPT_TIMEOUT        => 15,
            CURLOPT_SSL_VERIFYPEER => true
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        $data = json_decode($response, true);
        return $data ?: ['success' => false, 'error' => "HTTP {$httpCode}: {$response}"];
    }
}

// ==========================================
// Exemple d'utilisation dans votre code PHP :
// ==========================================
$client = new FcmNotificationClient('https://votre-serveur.com', 'app_ecommerce_key_9f8a7b6c5d4e3f2a');

// 1. Envoi à un utilisateur lors d'une commande
$res = $client->sendToUser('USER_4589', 'Commande confirmée !', 'Votre commande #8892 est validée.', [
    'screen'   => 'orders',
    'order_id' => '8892'
]);

if ($res['success']) {
    echo "Notification envoyée ! ID : " . $res['data']['notification_id'] . " | Statut : " . $res['data']['status'];
}
```

---

#### 🟢 En Vue.js 3 : Composant d'administration (`NotificationSender.vue`)
> [!TIP]
> Un composable TypeScript complet et typé est directement fourni à la racine du projet : **[`useNotification.ts`](file:///c:/workspace/notificationFCM/useNotification.ts)**. Vous pouvez l'importer directement dans vos projets Vue 3 / Nuxt 3 !

Voici un composant Vue 3 (Composition API avec `<script setup>` et Axios / Fetch) pour intégrer l'envoi de notifications dans votre back-office ou CRM :

```vue
<template>
  <div class="notification-card">
    <h3>Envoyer une Notification Push</h3>

    <form @submit.prevent="handleSend">
      <!-- Sélection de la cible -->
      <div class="field">
        <label>Destinataire :</label>
        <select v-model="form.target_type">
          <option value="all_users">Tous les utilisateurs</option>
          <option value="user">Utilisateur spécifique</option>
          <option value="platform">Plateforme (Android / iOS)</option>
        </select>
      </div>

      <!-- Cible spécifique si nécessaire -->
      <div class="field" v-if="form.target_type === 'user'">
        <label>ID Utilisateur :</label>
        <input v-model="form.target_value" placeholder="Ex: USER_4589" required />
      </div>

      <div class="field" v-if="form.target_type === 'platform'">
        <label>Plateforme :</label>
        <select v-model="form.target_value">
          <option value="android">Android</option>
          <option value="ios">iOS (Apple)</option>
        </select>
      </div>

      <!-- Titre & Message -->
      <div class="field">
        <label>Titre :</label>
        <input v-model="form.title" placeholder="Ex: Flash Promo !" required />
      </div>

      <div class="field">
        <label>Message :</label>
        <textarea v-model="form.body" placeholder="Votre message push..." required></textarea>
      </div>

      <!-- Options -->
      <div class="field-checkbox">
        <label>
          <input type="checkbox" v-model="form.immediate_send" />
          Envoi immédiat (sinon mis en file d'attente 'a_envoyer')
        </label>
      </div>

      <button type="submit" :disabled="loading">
        {{ loading ? 'Envoi en cours...' : '🚀 Envoyer la Notification' }}
      </button>
    </form>

    <!-- Résultat -->
    <div v-if="result" :class="['alert', result.success ? 'success' : 'error']">
      <p><strong>{{ result.message }}</strong></p>
      <p v-if="result.data">ID: #{{ result.data.notification_id }} | Statut: {{ result.data.status }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';

const API_BASE_URL = 'https://votre-serveur.com';
const API_KEY = 'VOTRE_CLE_API_APPLICATION';

const loading = ref(false);
const result = ref(null);

const form = reactive({
  title: '',
  body: '',
  target_type: 'all_users',
  target_value: '',
  immediate_send: true,
  data: { source: 'backoffice_crm' }
});

const handleSend = async () => {
  loading.value = true;
  result.value = null;

  try {
    const response = await fetch(`${API_BASE_URL}/api/create_notification.php`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-KEY': API_KEY
      },
      body: JSON.stringify(form)
    });

    const data = await response.json();
    result.value = data;

    if (data.success) {
      // Réinitialiser le formulaire
      form.title = '';
      form.body = '';
    }
  } catch (err) {
    result.value = { success: false, message: 'Erreur réseau : ' + err.message };
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.notification-card {
  max-width: 500px;
  padding: 20px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  font-family: sans-serif;
}
.field { margin-bottom: 15px; display: flex; flex-direction: column; }
.field label { font-weight: bold; margin-bottom: 5px; font-size: 0.9em; }
.field input, .field select, .field textarea { padding: 8px 10px; border: 1px solid #ccc; border-radius: 4px; }
.field textarea { resize: vertical; min-height: 70px; }
.field-checkbox { margin-bottom: 15px; }
button { width: 100%; padding: 10px; background: #4f46e5; color: white; border: none; border-radius: 6px; font-weight: bold; cursor: pointer; }
button:hover { background: #4338ca; }
button:disabled { opacity: 0.6; cursor: not-allowed; }
.alert { margin-top: 15px; padding: 10px; border-radius: 6px; font-size: 0.9em; }
.alert.success { background: #dcfce7; color: #166534; }
.alert.error { background: #fee2e2; color: #991b1b; }
</style>
```

---

#### 🟢 En Vue.js : Enregistrer un Token FCM Web (Service Push Web)
Si votre application Vue.js utilise le SDK Firebase côté navigateur :

```javascript
// composables/useFCM.js
import { getMessaging, getToken } from "firebase/messaging";

export async function registerBrowserDevice(externalUserId) {
  const messaging = getMessaging();
  
  // 1. Demande de permission et récupération du token FCM Web
  const currentToken = await getToken(messaging, { 
    vapidKey: 'VOTRE_CLE_VAPID_FIREBASE' 
  });

  if (!currentToken) {
    console.warn("Aucun token FCM obtenu. Permission refusée ?");
    return;
  }

  // 2. Enregistrement auprès de votre API de notification
  await fetch('https://votre-serveur.com/api/register_device.php', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-KEY': 'VOTRE_CLE_API_APPLICATION'
    },
    body: JSON.stringify({
      fcm_token: currentToken,
      platform: 'web',
      external_user_id: externalUserId
    })
  });

  console.log("Appareil Web enregistré avec succès pour l'utilisateur :", externalUserId);
}
```

---

## 🔍 Étape 3 : Suivre le statut d'envoi

Vous pouvez à tout moment vérifier si une notification a été envoyée, si elle est en attente, ou s'il y a eu des erreurs.

### Point d'accès
- **URL** : `GET /api/notification_status.php?id={notification_id}`
- **Header obligatoire** : `X-API-KEY: VOTRE_CLE_API`

### Exemple de Réponse :
```json
{
  "success": true,
  "data": {
    "id": 42,
    "title": "📦 Commande expédiée !",
    "status": "envoye",
    "scheduled_at": null,
    "sent_at": "2026-09-14 22:15:30",
    "stats": {
      "recipients": 1,
      "success": 1,
      "failure": 0,
      "retries": 0
    }
  }
}
```

### Signification des statuts :
- `a_envoyer` : La notification est mise en file d'attente et attend d'être traitée par le worker.
- `en_cours` : Le worker est en train d'expédier les messages vers Google FCM.
- `envoye` : Tous les destinataires ont reçu la notification avec succès.
- `partiel` : Certains appareils ont réussi, d'autres ont échoué (ex: token désinstallé).
- `echec` : Aucun envoi n'a abouti.
