<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
// ============================================================
//  POST /admin/send_push.php
//  OneSignal REST API
//  Body JSON: { titre, message, cible, classe_id?, eleve_id?, type? }
// ============================================================
require_once __DIR__ . '/config_admin.php';
header('Content-Type: application/json; charset=utf-8');
requireAdminAuth();

// --- Clés OneSignal ---
define('ONESIGNAL_APP_ID',  'cb4d55f9-780f-44dd-a6ce-51202882b8db');
define('ONESIGNAL_API_KEY', 'os_v2_app_zngvl6lyb5cn3jwokeqcravy3p3nh2ygmape7rvj5oi5ahotbnpqerlwohfj2h3kcfbjpslhsgz5wk3qw66sda36jkghb645ishvo2a');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(['success' => false, 'error' => 'Méthode non autorisée']);
}

$body      = json_decode(file_get_contents('php://input'), true);
$titre     = trim($body['titre']      ?? '');
$message   = trim($body['message']    ?? '');
$cible     = trim($body['cible']      ?? 'tous');
$classe_id = (int)($body['classe_id'] ?? 0);
$eleve_id  = (int)($body['eleve_id']  ?? 0);
$type      = trim($body['type']       ?? 'info');

if (!$titre || !$message) {
    jsonResponse(['success' => false, 'error' => 'Titre et message requis']);
}

$db = getDB();

// --- Récupérer les external_user_id (téléphone parent) selon la cible ---
if ($cible === 'tous') {
    $stmt = $db->query("
        SELECT DISTINCT
            REPLACE(REPLACE(REPLACE(e.telephone_parent, '+237', ''), ' ', ''), '-', '') as phone
        FROM eleves e
        JOIN inscriptions i ON i.eleve_id = e.id
        WHERE e.telephone_parent IS NOT NULL AND e.telephone_parent != ''
    ");
    $phones = $stmt->fetchAll(PDO::FETCH_COLUMN);

} elseif ($cible === 'classe' && $classe_id) {
    $stmt = $db->prepare("
        SELECT DISTINCT
            REPLACE(REPLACE(REPLACE(e.telephone_parent, '+237', ''), ' ', ''), '-', '') as phone
        FROM eleves e
        JOIN inscriptions i ON i.eleve_id = e.id AND i.classe_id = ?
        WHERE e.telephone_parent IS NOT NULL AND e.telephone_parent != ''
    ");
    $stmt->execute([$classe_id]);
    $phones = $stmt->fetchAll(PDO::FETCH_COLUMN);

} elseif ($cible === 'eleve' && $eleve_id) {
    $stmt = $db->prepare("
        SELECT DISTINCT
            REPLACE(REPLACE(REPLACE(e.telephone_parent, '+237', ''), ' ', ''), '-', '') as phone
        FROM eleves e
        WHERE e.id = ? AND e.telephone_parent IS NOT NULL
    ");
    $stmt->execute([$eleve_id]);
    $phones = $stmt->fetchAll(PDO::FETCH_COLUMN);

} else {
    jsonResponse(['success' => false, 'error' => 'Cible invalide']);
}

if (empty($phones)) {
    jsonResponse(['success' => false, 'error' => 'Aucun destinataire trouvé pour cette cible']);
}

// --- Envoyer via OneSignal ---
function sendOneSignalPush(string $titre, string $message, array $phones, string $type): array {
    $payload = [
        'app_id'             => ONESIGNAL_APP_ID,
        'headings'           => ['en' => $titre, 'fr' => $titre],
        'contents'           => ['en' => $message, 'fr' => $message],
        'include_aliases'    => ['external_id' => array_values($phones)],
        'target_channel'     => 'push',
        'data'               => ['type' => $type],
        'android_channel_id' => '',  // optionnel: votre channel Android
        'small_icon'         => 'ic_notification',
        'large_icon'         => 'https://pia-soft.com/piaschool/photos_eleves/logo.png',
    ];

    $ch = curl_init('https://api.onesignal.com/notifications');
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json',
            'Authorization: Key ' . ONESIGNAL_API_KEY,
        ],
        CURLOPT_POSTFIELDS     => json_encode($payload),
        CURLOPT_TIMEOUT        => 15,
    ]);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

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

$push = sendOneSignalPush($titre, $message, $phones, $type);

// --- Enregistrer la notification en base ---
if ($cible === 'eleve' && $eleve_id) {
    $stmt = $db->prepare("
        INSERT INTO notifications (type, titre_fr, titre_en, message_fr, message_en, eleve_id, envoye, lu, created_at)
        VALUES (?, ?, ?, ?, ?, ?, 1, 0, NOW())
    ");
    $stmt->execute([$type, $titre, $titre, $message, $message, $eleve_id]);
} elseif ($cible === 'classe' && $classe_id) {
    // Insérer pour chaque élève de la classe
    $stmtEleves = $db->prepare("SELECT id FROM eleves e JOIN inscriptions i ON i.eleve_id=e.id WHERE i.classe_id=?");
    $stmtEleves->execute([$classe_id]);
    $eleves = $stmtEleves->fetchAll(PDO::FETCH_COLUMN);
    $ins = $db->prepare("
        INSERT INTO notifications (type, titre_fr, titre_en, message_fr, message_en, eleve_id, envoye, lu, created_at)
        VALUES (?, ?, ?, ?, ?, ?, 1, 0, NOW())
    ");
    foreach ($eleves as $ei