<br />
<b>Warning</b>:  Undefined variable $auth in <b>/home/pevo0181/public_html/pia-soft.com/cleania/routes/index.php</b> on line <b>542</b><br />
<br />
<b>Warning</b>:  Trying to access array offset on value of type null in <b>/home/pevo0181/public_html/pia-soft.com/cleania/routes/index.php</b> on line <b>542</b><br />
<?php
// ============================================================
//  PIASCHOOL — send_notification.php
//  Script pour envoyer des push notifications FCM V1
//  Déposer dans : piaschool/piaschool1/
// ============================================================

error_reporting(0);
ini_set('display_errors', 0);

define('DB_HOST', 'localhost');
define('DB_NAME', 'pevo0181_piaschool1');
define('DB_USER', 'pevo0181_piaschool1');
define('DB_PASS', 'Piasoft2021');
define('FIREBASE_CREDENTIALS', __DIR__ . '/firebase-credentials.json');
define('FIREBASE_PROJECT_ID', 'piaschool-b9da8');

try {
    $pdo = new PDO(
        "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=utf8mb4",
        DB_USER, DB_PASS,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
         PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
    );
} catch (Exception $e) {
    die(json_encode(['success' => false, 'message' => 'Erreur DB']));
}

// ── Obtenir token OAuth2 pour FCM V1
function getAccessToken() {
    $credentials = json_decode(file_get_contents(FIREBASE_CREDENTIALS), true);
    $now = time();
    $header  = base64url_encode(json_encode(['alg' => 'RS256', 'typ' => 'JWT']));
    $payload = base64url_encode(json_encode([
        'iss'   => $credentials['client_email'],
        'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
        'aud'   => 'https://oauth2.googleapis.com/token',
        'iat'   => $now,
        'exp'   => $now + 3600,
    ]));
    $signingInput = "$header.$payload";
    openssl_sign($signingInput, $signature, $credentials['private_key'], 'SHA256');
    $jwt = "$header.$payload." . base64url_encode($signature);

    $ch = curl_init('https://oauth2.googleapis.com/token');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion'  => $jwt,
    ]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($response, true);
    return $data['access_token'] ?? null;
}

function base64url_encode($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

// ── Envoyer via FCM V1
function envoyerFCM($fcmToken, $titre, $message, $data = []) {
    $accessToken = getAccessToken();
    if (!$accessToken) return ['success' => false, 'message' => 'Token invalide'];

    $dataStr = [];
    foreach ($data as $k => $v) $dataStr[(string)$k] = (string)$v;

    $payload = json_encode([
        'message' => [
            'token' => $fcmToken,
            'notification' => ['title' => $titre, 'body' => $message],
            'data' => $dataStr,
            'android' => [
                'priority' => 'high',
                'notification' => ['channel_id' => 'piaschool_channel', 'sound' => 'default'],
            ],
        ]
    ]);

    $url = "https://fcm.googleapis.com/v1/projects/" . FIREBASE_PROJECT_ID . "/messages:send";
    $ch  = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $accessToken,
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result   = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return ['success' => $httpCode === 200, 'http_code' => $httpCode, 'response' => json_decode($result, true)];
}

// ── Enregistrer + envoyer notification
function envoyerNotification($pdo, $parentId, $eleveId, $type, $titre, $message, $data = []) {
    $stmt = $pdo->prepare("INSERT INTO mobile_notifications (parent_id, eleve_id, type, titre, message, data) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->execute([$parentId, $eleveId, $type, $titre, $message, json_encode($data)]);

    $tokenStmt = $pdo->prepare("SELECT fcm_token FROM fcm_tokens WHERE parent_id = ?");
    $tokenStmt->execute([$parentId]);
    $fcmToken = $tokenStmt->fetchColumn();
    if (!$fcmToken) return ['success' => false, 'message' => 'Token FCM non trouvé'];

    return envoyerFCM($fcmToken, $titre, $message, array_merge($data, [
        'type' => $type, 'parent_id' => $parentId, 'eleve_id' => (string)$eleveId,
    ]));
}

// ── Fonctions métier
function notifierAbsence($pdo, $eleveId, $dateAppel, $periode = '') {
    $stmt = $pdo->prepare("SELECT nom, prenom FROM eleves WHERE id = ?");
    $stmt->execute([$eleveId]);
    $eleve = $stmt->fetch();
    if (!$eleve) return ['success' => false];
    return envoyerNotification($pdo, 'P_'.$eleveId, $eleveId, 'absence',
        "⚠️ Absence signalée",
        "{$eleve['prenom']} {$eleve['nom']} a été absent(e) le $dateAppel" . ($periode ? " ($periode)" : ""),
        ['date' => $dateAppel, 'periode' => $periode]
    );
}

function notifierNote($pdo, $eleveId, $matiere, $note, $noteMax) {
    $stmt = $pdo->prepare("SELECT nom, prenom FROM eleves WHERE id = ?");
    $stmt->execute([$eleveId]);
    $eleve = $stmt->fetch();
    if (!$eleve) return ['success' => false];
    $sur20 = round(($note / $noteMax) * 20, 2);
    return envoyerNotification($pdo, 'P_'.$eleveId, $eleveId, 'note',
        "📊 Nouvelle note — $matiere",
        "{$eleve['prenom']} a obtenu $note/$noteMax ($sur20/20) en $matiere",
        ['matiere' => $matiere, 'note' => (string)$note, 'note_max' => (string)$noteMax]
    );
}

function notifierPaiement($pdo, $eleveId, $montant, $tranche) {
    $stmt = $pdo->prepare("SELECT nom, prenom FROM eleves WHERE id = ?");
    $stmt->execute([$eleveId]);
    $eleve = $stmt->fetch();
    if (!$eleve) return ['success' => false];
    return envoyerNotification($pdo, 'P_'.$eleveId, $eleveId, 'paiement',
        "✅ Paiement confirmé",
        "Paiement de " . number_format($montant, 0, ',', ' ') . " FCFA reçu (Tranche $tranche) pour {$eleve['prenom']}",
        ['montant' => (string)$montant, 'tranche' => (string)$tranche]
    );
}

function notifierTousParents($pdo, $titre, $message) {
    $tokens = $pdo->query("SELECT parent_id, fcm_token FROM fcm_tokens")->fetchAll();
    $resultats = [];
    foreach ($tokens as $t) {
        $resultats[] = ['parent_id' => $t['parent_id'], 'result' => envoyerFCM($t['fcm_token'], $titre, $message, ['type' => 'info'])];
    }
    return $resultats;
}

// ── Point d'entrée
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $body = json_decode(file_get_contents('php://input'), true) ?? [];
    switch ($body['type'] ?? '') {
        case 'absence':
            echo json_encode(notifierAbsence($pdo, intval($body['eleve_id']), $body['date'] ?? date('Y-m-d'), $body['periode'] ?? ''));
            break;
        case 'note':
            echo json_encode(notifierNote($pdo, intval($body['eleve_id']), $body['matiere'], floatval($body['note']), floatval($body['note_max'] ?? 20)));
            break;
        case 'paiement':
            echo json_encode(notifierPaiement($pdo, intval($body['eleve_id']), floatval($body['montant']), intval($body['tranche'])));
            break;
        case 'broadcast':
            echo json_encode(['success' => true, 'resultats' => notifierTousParents($pdo, $body['titre'] ?? '', $body['message'] ?? '')]);
            break;
        case 'test':
            echo json_encode(envoyerFCM($body