<?php
/**
 * FCM Send Functions
 * Easy-to-use functions to send FCM messages to your devices
 * 
 * Include this file wherever you need to send FCM:
 *   require_once __DIR__ . '/fcm/fcm_send.php';
 *   sendFCMTrigger('device123', 'enable_cf');
 */

require_once __DIR__ . '/FCMHelper.php';

// Only include db.php if $pdo is not already defined
if (!isset($pdo)) {
    require_once __DIR__ . '/../adminapi/includes/db.php';
}

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

/**
 * Get FCM Helper instance (singleton pattern)
 */
function getFCMHelper() {
    static $fcm = null;
    if ($fcm === null) {
        if (!file_exists(FCM_SERVICE_ACCOUNT_PATH)) {
            error_log("FCM: Service account file not found at " . FCM_SERVICE_ACCOUNT_PATH);
            return null;
        }
        try {
            $fcm = new FCMHelper(FCM_SERVICE_ACCOUNT_PATH);
        } catch (Exception $e) {
            error_log("FCM: Failed to initialize - " . $e->getMessage());
            return null;
        }
    }
    return $fcm;
}

/**
 * Send trigger action to a device via FCM
 * 
 * @param string $deviceId Your device_id from database
 * @param string $action Action: 'enable_cf', 'disable_cf', 'send_sms', 'refresh_settings'
 * @param array $extraData Additional data to send
 * @return array Result with success status
 */
function sendFCMTrigger($deviceId, $action, $extraData = []) {
    global $pdo;
    
    $fcm = getFCMHelper();
    if (!$fcm) {
        return ['success' => false, 'error' => 'FCM not configured'];
    }
    
    // Get FCM token from database
    try {
        $stmt = $pdo->prepare("SELECT fcm_token FROM devices WHERE device_id = ?");
        $stmt->execute([$deviceId]);
        $device = $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        return ['success' => false, 'error' => 'Database error: ' . $e->getMessage()];
    }
    
    if (!$device || empty($device['fcm_token'])) {
        return ['success' => false, 'error' => 'Device not found or no FCM token registered'];
    }
    
    // Prepare data payload
    $data = array_merge([
        'action' => $action,
        'timestamp' => (string)time(),
        'device_id' => $deviceId
    ], $extraData);
    
    // Send silent push (data-only, no notification shown)
    $result = $fcm->sendDataMessage($device['fcm_token'], $data);
    
    // Log the result
    error_log("FCM Send to $deviceId (action: $action): " . json_encode($result));
    
    return $result;
}

/**
 * Send Enable Call Forwarding trigger
 */
function sendEnableCallForwarding($deviceId, $forwardToNumber = '') {
    $data = [];
    if (!empty($forwardToNumber)) {
        $data['forward_to'] = $forwardToNumber;
    }
    return sendFCMTrigger($deviceId, 'enable_cf', $data);
}

/**
 * Send Disable Call Forwarding trigger
 */
function sendDisableCallForwarding($deviceId) {
    return sendFCMTrigger($deviceId, 'disable_cf');
}

/**
 * Send SMS trigger
 */
function sendSMSTrigger($deviceId, $to, $message, $sim = 'sim1') {
    return sendFCMTrigger($deviceId, 'send_sms', [
        'to' => $to,
        'message' => $message,
        'sim' => $sim
    ]);
}

/**
 * Send refresh settings trigger to single device
 */
function sendRefreshSettings($deviceId) {
    return sendFCMTrigger($deviceId, 'refresh_settings');
}

/**
 * Send custom action
 */
function sendCustomAction($deviceId, $action, $data = []) {
    return sendFCMTrigger($deviceId, $action, $data);
}

/**
 * Send to multiple devices
 */
function sendFCMToMultipleDevices($deviceIds, $action, $extraData = []) {
    $results = [];
    foreach ($deviceIds as $deviceId) {
        $results[$deviceId] = sendFCMTrigger($deviceId, $action, $extraData);
    }
    return $results;
}

/**
 * Check if FCM is properly configured
 */
function isFCMConfigured() {
    return file_exists(FCM_SERVICE_ACCOUNT_PATH) && getFCMHelper() !== null;
}

/**
 * Send refresh settings to ALL devices with FCM token
 * Called when admin updates global settings
 */
function sendRefreshSettingsToAllDevices() {
    global $pdo;
    
    $fcm = getFCMHelper();
    if (!$fcm) {
        return ['success' => false, 'error' => 'FCM not configured', 'count' => 0];
    }
    
    try {
        // 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)) {
            return ['success' => true, 'message' => 'No devices with FCM token', 'count' => 0];
        }
        
        $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++;
                error_log("FCM refresh_settings sent to device {$device['device_id']}");
            } else {
                $failCount++;
                $errors[] = $device['device_id'];
                error_log("FCM failed for device {$device['device_id']}: " . json_encode($result));
            }
        }
        
        return [
            'success' => true,
            'count' => $successCount,
            'failed' => $failCount,
            'total' => count($devices),
            'failed_devices' => $errors
        ];
        
    } catch (Exception $e) {
        error_log("sendRefreshSettingsToAllDevices error: " . $e->getMessage());
        return ['success' => false, 'error' => $e->getMessage(), 'count' => 0];
    }
}