<?php
/**
 * Custom SMS with INSTANT FCM
 * 
 * FIXED: Only saves to queue file if FCM fails (prevents duplicate SMS)
 * 
 * Location: /admin/tmp/custom_sms_put.php
 */

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

$dir = __DIR__;
$device = trim($_POST['device_id'] ?? '');
$to     = trim($_POST['to'] ?? '');
$msg    = (string)($_POST['message'] ?? '');
$sim    = $_POST['sim'] ?? 'sim1';

if ($device === '' || $to === '' || $msg === '') {
    echo json_encode(['ok' => false, 'error' => 'missing params']);
    exit;
}

// Include FCM functions
require_once __DIR__ . '/../fcm/fcm_send.php';

$fcmSent = false;
$fcmError = null;
$fcmDetails = null;
$queueFile = null;
$bytes = 0;

// Step 1: Try FCM FIRST
if (isFCMConfigured()) {
    $fcmResult = sendSMSTrigger($device, $to, $msg, ($sim === 'sim2' ? 'sim2' : 'sim1'));
    
    $fcmSent = $fcmResult['success'] ?? false;
    $fcmError = $fcmResult['error'] ?? null;
    $fcmDetails = $fcmResult;
}

// Step 2: ONLY save to queue file if FCM FAILED (backup/fallback)
if (!$fcmSent) {
    $fname = 'queue_' . preg_replace('/[^a-zA-Z0-9_\-]/', '_', $device) . '.json';
    $queueFile = $dir . '/' . $fname;
    
    $payload = [
        'trigger' => 1,
        'to' => $to,
        'message' => $msg,
        'sim' => ($sim === 'sim2' ? 'sim2' : 'sim1'),
        'ts' => time()
    ];
    
    $bytes = @file_put_contents($queueFile, json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    
    if (!$fcmError) {
        $fcmError = 'FCM not configured, saved to queue';
    }
}

// Return response
echo json_encode([
    'ok' => true,
    'fcm_sent' => $fcmSent,
    'fcm_error' => $fcmError,
    'fcm_details' => $fcmDetails,
    'queue_file' => $queueFile,
    'queue_bytes' => $bytes
]);