<?php
require_once('/home/rejoiceysn98/api.rejoicelearning.in/resources/base_path_include.php');

require $GLOBALS['base_path_to_learning'] . 'vendor/autoload.php';
require $GLOBALS['base_path_to_learning_resources'] . 'lib/cron_jobs/firebase_notification/notification_history_function.php';

use \Kreait\Firebase\Factory;
use \Kreait\Firebase\Messaging\CloudMessage;
use \Kreait\Firebase\Messaging\Notification;
use \Kreait\Firebase\Exception\MessagingException;
use \Kreait\Firebase\Exception\FirebaseException;



function getFirebaseMessagingInstance() {
    static $messagingInstance = null; // Static variable to persist instance

    if ($messagingInstance === null) {
        try {
        $serviceAccountPath = '/home/rejoiceysn98/api.rejoicelearning.in/resources/lib/cron_jobs/firebase_notification/rejoice-learning-student-4f707-firebase-adminsdk-l3cf1-c7dfe43783.json';
            
            // Ensure file exists before proceeding
            if (!file_exists($serviceAccountPath)) {
                die("<b>Error:</b> Firebase Service Account JSON file not found at: $serviceAccountPath<br>");
            }

            // Initialize Firebase only once
            $firebase_factory = (new Factory)->withServiceAccount($serviceAccountPath);
            $messagingInstance = $firebase_factory->createMessaging();
            
        } catch (Exception $e) {
            die("<b>Error:</b> Failed to initialize Firebase: " . $e->getMessage() . "<br>");
        }
    }
    
    return $messagingInstance;
}


function sendNotification($conn_rjllearning, $userIds, $notificationTitle, $notificationBody, $redirectType = null, $redirectId = null) {
    
    
    if(!is_array($userIds)) {
        // handling if single user id received by mistake
        $userIds = [$userIds];
    }
    
    if(empty($userIds)) {
        return true;
    }
    
    $tokens = getUserFCMToken($conn_rjllearning, $userIds);

    // echo "<pre>";
    // print_r($userIds);
    // echo "<br>";
    // print_r($tokens);
    // die();

    $messaging = getFirebaseMessagingInstance(); 
    if (!$messaging) {
        return 0;
    }

    $sentCount = 0;
    $nowDate = date('Y-m-d');
    $nowTime = date('H:i:s');

    foreach ($userIds as $userId) {
        // Store notification
        $storeSuccess = storeNotification($conn_rjllearning, [
            'user_id'      => $userId,
            'topic_name'   => $notificationTitle,
            'description'  => $notificationBody ?? null,
            'date_created' => $nowDate,
            'time_created' => $nowTime,
            'status_id'    => 0,
        ]);

        // Skip if storing failed
        if (!$storeSuccess) {
            continue;
        }
    }
    
   // Step 2: flatten all tokens
    $allTokens = [];
    foreach ($tokens as $userTokenList) {
        foreach ($userTokenList as $t) {
            if (is_string($t) && $t !== '') {
                $allTokens[] = $t;
            }
        }
    }
    $allTokens = array_values(($allTokens)); // dedupe
    
    // Step 3: send notifications
    $messaging    = getFirebaseMessagingInstance();
    $notification = Notification::create($notificationTitle ?? '', $notificationBody ?? '');
    $data = [];
    if ($redirectType && $redirectId) {
        $data = ['type' => (string)$redirectType, 'id' => (string)$redirectId];
    }
    
    $sentCount = 0;
    foreach ($allTokens as $fcmToken) {
        $message = CloudMessage::withTarget('token', $fcmToken)
            ->withNotification($notification)
            ->withData($data);
    
        try {
            $messaging->send($message);
            $sentCount++;
        } catch (\Kreait\Firebase\Exception\MessagingException |
                 \Kreait\Firebase\Exception\FirebaseException $e) {
            $msg = $e->getMessage();
            if (stripos($msg, 'NotRegistered') !== false
             || stripos($msg, 'invalid') !== false
             || stripos($msg, 'mismatch') !== false) {
                // Optionally: remove this token from DB (you'll need to know which user had it)
            }
            error_log("FCM error for token {$fcmToken}: ".$msg);
        }
    }

    return $sentCount;
}


function getUserFCMToken($conn_rjllearning, $userIds) {
    try {
        if (!is_array($userIds)) {
            $userIds = [$userIds];
        }


        $placeholders = implode(',', array_fill(0, count($userIds), '?'));
        $sql = "SELECT userid, fcm_token FROM user_fcm_tokens WHERE userid IN ($placeholders)";
        $stmt = $conn_rjllearning->prepare($sql);
        $stmt->execute($userIds);

        $tokens = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

            if (!empty($row['fcm_token'])) {
                $decodedTokens = json_decode($row['fcm_token'], true);

                if (is_array($decodedTokens)) {
                    $tokens[$row['userid']] = $decodedTokens;
                }
            }
        }

        return $tokens; // format: [userId => [token1, token2, ...]]
    } catch (PDOException $e) {
        errorreturn('Database error: ' . $e->getMessage());
    }
}
