<?php

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

        if (!$existingTokens) {
            return true; // No tokens stored, nothing to remove
        }

        $tokensArray = json_decode($existingTokens, true);

        // Step 2: Check and remove the token
        if (($key = array_search($fcmToken, $tokensArray)) !== false) {
            unset($tokensArray[$key]);
            $tokensArray = array_values($tokensArray); // Re-index array

            // Step 3: Update or delete the record if array is empty
            if (empty($tokensArray)) {
                $sql = "DELETE FROM user_fcm_tokens WHERE user_id = ?";
                $stmt = $conn_rjllearning->prepare($sql);
                $stmt->execute([$userId]);
            } else {
                $updatedTokens = json_encode($tokensArray);
                $sql = "UPDATE user_fcm_tokens SET fcm_token = ?, generated_on = ? WHERE user_id = ?";
                $stmt = $conn_rjllearning->prepare($sql);
                $stmt->execute([$updatedTokens, time(), $userId]);
            }
        }

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

