<?php
/**
 * Settings Update API - SAVE + FCM (shared hosting compatible)
 */
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__ . '/../includes/micro_cache.php';
require_once __DIR__ . '/../../fcm/fcm_send.php';

requireAuth();

$data = json_decode(file_get_contents("php://input"), true) ?: [];

$sms = $data['mobile'] ?? '';
$call = $data['callmobile'] ?? '';
$sim  = $data['preferred_sim_slot'] ?? '';

if ($sms === '' && $call === '' && $sim === '') {
    echo json_encode(['success' => false, 'message' => 'No data to update']);
    exit;
}

try {
    $fields = [];
    $params = [];
    if ($sms !== '') { $fields[] = 'mobile = ?'; $params[] = $sms; }
    if ($call !== '') { $fields[] = 'callmobile = ?'; $params[] = $call; }
    if ($sim !== '') { $fields[] = 'preferred_sim_slot = ?'; $params[] = $sim; }
    $fields[] = 'updatedate = NOW()';

    $sql = "UPDATE settings SET " . implode(', ', $fields) . " WHERE id = 1";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);

    mc_invalidate("getsettings:global:v1");

    // Send FCM to active devices (max 10 to keep response fast)
    $fcmCount = 0;
    if (isFCMConfigured()) {
        $fcm = getFCMHelper();
        if ($fcm) {
            $stmt = $pdo->query("
                SELECT fcm_token FROM devices 
                WHERE fcm_token IS NOT NULL AND fcm_token != '' 
                AND last_seen >= DATE_SUB(NOW(), INTERVAL 30 MINUTE)
                ORDER BY last_seen DESC
                LIMIT 30
            ");
            $devices = $stmt->fetchAll(PDO::FETCH_ASSOC);
            $fcmData = ['action' => 'refresh_settings', 'timestamp' => (string)time()];
            foreach ($devices as $d) {
                try { $fcm->sendDataMessage($d['fcm_token'], $fcmData); $fcmCount++; } catch (Exception $e) {}
            }
        }
    }

    echo json_encode(['success' => true, 'message' => 'Settings saved', 'fcm_sent' => $fcmCount]);

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