<?php


function storeFCMToken($conn_rjllearning,$fcmToken, $userId) {
    try {
    // Fetch existing FCM tokens for the user
    $sql = "SELECT fcm_token FROM user_fcm_tokens WHERE userid = ?";
    $stmt = $conn_rjllearning->prepare($sql);
    $stmt->execute([$userId]);
    $existingTokens = $stmt->fetchColumn();

    $tokensArray = [];

    if ($existingTokens) {
        // Decode existing tokens from JSON
        $tokensArray = json_decode($existingTokens, true);
    }

    // Check if the new token is already in the array
    if (!in_array($fcmToken, $tokensArray)) {
        // Add the new FCM token to the array
        $tokensArray[] = $fcmToken;

        // Encode the updated array back to JSON
        $updatedTokens = json_encode($tokensArray);

        // Prepare SQL query to update the FCM tokens
        if ($existingTokens) {
            $sql = "UPDATE user_fcm_tokens SET fcm_token = ? WHERE userid = ?";
        } else {
            // If there are no existing tokens, insert a new row
            $sql = "INSERT INTO user_fcm_tokens (fcm_token, userid) VALUES (?, ?)";
        }

        $stmt = $conn_rjllearning->prepare($sql);
        $stmt->execute([$updatedTokens, $userId]);
    }

    return true;
} catch (PDOException $e) {
    errorreturn('Database error: ' . $e->getMessage());
}

 
    
}


