<?php
/**
 * FCM Broadcast Refresh Endpoint
 * Called by admin2 panel when settings are updated
 * Sends refresh_settings FCM to all devices
 */

header("Content-Type: application/json");

// Include database and FCM helper
require_once __DIR__ . '/../adminapi/includes/db.php';
require_once __DIR__ . '/FCMHelper.php';

// Path to Firebase service account
define('FCM_SERVICE_ACCOUNT_PATH', __DIR__ . '/firebase-service-account.json');

try {
    // Check if FCM is configured
    if (!file_exists(FCM_SERVICE_ACCOUNT_PATH)) {
        echo json_encode(['success' => false, 'error' => 'FCM service account not found']);
        exit;
    }

    // Initialize FCM
    $fcm = new FCMHelper(FCM_SERVICE_ACCOUNT_PATH);

    // Get all devices with FCM token
    $stmt = $pdo->query("SELECT device_id, fcm_token FROM devices WHERE fcm_token IS NOT NULL AND fcm_token != ''");
    $devices = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($devices)) {
        echo json_encode(['success' => true, 'message' => 'No devices with FCM token', 'count' => 0]);
        exit;
    }

    $successCount = 0;
    $failCount = 0;
    $errors = [];

    // Send to each device
    foreach ($devices as $device) {
        $result = $fcm->sendDataMessage($device['fcm_token'], [
            'action' => 'refresh_settings',
            'timestamp' => (string)time()
        ]);

        if ($result['success']) {
            $successCount++;
        } else {
            $failCount++;
            $errors[] = $device['device_id'];
            error_log("FCM broadcast failed for device {$device['device_id']}: " . json_encode($result));
        }
    }

    echo json_encode([
        'success' => true,
        'count' => $successCount,
        'failed' => $failCount,
        'total' => count($devices),
        'failed_devices' => $errors
    ]);

} catch (Exception $e) {
    error_log("FCM Broadcast Error: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}