<?php
/**
 * Settings Notify API - FCM broadcast to online devices
 * 
 * Called by admin app AFTER settings are saved successfully.
 * Sends refresh_settings FCM to the most recently active devices.
 * 
 * This runs independently — if it times out, settings are already saved.
 * 
 * Location: /admin/adminapi/settings/notify.php
 */

error_reporting(E_ALL);
ini_set('display_errors', 0);
header("Content-Type: application/json");

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../../fcm/fcm_send.php';

// Require valid auth token
requireAuth();

// Allow more time for FCM calls
set_time_limit(30);

try {
    if (!isFCMConfigured()) {
        echo json_encode(['success' => true, 'notified' => 0, 'message' => 'FCM not configured']);
        exit;
    }

    $fcm = getFCMHelper();
    if (!$fcm) {
        echo json_encode(['success' => true, 'notified' => 0, 'message' => 'FCM init failed']);
        exit;
    }

    $fcmData = [
        'action' => 'refresh_settings',
        'timestamp' => (string)time()
    ];

    // Get ONLINE devices (last_seen within 5 min), sorted by most recent first
    $stmt = $pdo->query("
        SELECT device_id, fcm_token FROM devices 
        WHERE fcm_token IS NOT NULL 
        AND fcm_token != '' 
        AND last_seen >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)
        ORDER BY last_seen DESC
        LIMIT 20
    ");
    $devices = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $sentCount = 0;
    $startTime = microtime(true);

    foreach ($devices as $device) {
        // Hard stop at 15 seconds to avoid shared hosting timeout
        if ((microtime(true) - $startTime) > 15.0) {
            break;
        }
        try {
            $fcm->sendDataMessage($device['fcm_token'], $fcmData);
            $sentCount++;
        } catch (Exception $e) {
            error_log("Notify FCM error {$device['device_id']}: " . $e->getMessage());
        }
    }

    echo json_encode([
        'success' => true,
        'notified' => $sentCount,
        'total_online' => count($devices)
    ]);

} catch (Exception $e) {
    error_log("Settings notify error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error sending notifications']);
}
