<?php
/**
 * FCM Send Functions
 * Use these functions to send push messages to devices
 */

require_once __DIR__ . '/FCMHelper.php';
require_once __DIR__ . '/../adminapi/includes/db.php';

// Path to your Firebase service account JSON file
// ⚠️ IMPORTANT: Store this file OUTSIDE public web folder for security!
// Or at minimum, protect it with .htaccess
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 to a device via FCM
 * 
 * @param string $deviceId Your device ID from database
 * @param string $action Action to perform: 'enable_cf', 'disable_cf', 'send_sms', 'refresh_settings', etc.
 * @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)
    try {
        $result = $fcm->sendDataMessage($device['fcm_token'], $data);
        
        // Log the result
        error_log("FCM Send to $deviceId [action: $action]: " . json_encode($result));
        
        return $result;
    } catch (Exception $e) {
        error_log("FCM Error: " . $e->getMessage());
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

/**
 * Send call forwarding trigger
 */
function sendCallForwardingTrigger($deviceId, $enable = true, $forwardTo = '') {
    $action = $enable ? 'enable_cf' : 'disable_cf';
    $extraData = [];
    if ($forwardTo) {
        $extraData['forward_to'] = $forwardTo;
    }
    return sendFCMTrigger($deviceId, $action, $extraData);
}

/**
 * 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
 */
function sendRefreshTrigger($deviceId) {
    return sendFCMTrigger($deviceId, 'refresh_settings');
}

/**
 * Send poll interval change trigger
 */
function sendPollIntervalTrigger($deviceId, $intervalSeconds) {
    return sendFCMTrigger($deviceId, 'set_poll_interval', [
        'interval' => (string)$intervalSeconds
    ]);
}

/**
 * Check if FCM is properly configured
 */
function isFCMConfigured() {
    return file_exists(FCM_SERVICE_ACCOUNT_PATH);
}
