<?php
namespace App\Services;

use App\User;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification;
use Illuminate\Support\Facades\DB;

class NotificationService
{
    public function sendPushNotification($title, $body, $additionalParams)
    {
        try {
            // Get the users
             $users = User::where('status', 1)->where('type','!=','admin');
            
            if(isset($additionalParams['user_id'])){
                if($additionalParams['user_id'] != 'all'){
                    $users = $users->where('id',$additionalParams['user_id']);
                }
            }
            
            $users = $users->get();
            
            if ($users->isEmpty()) {
                \Log::error("No active users found.");
                return false;
            }
            
            foreach ($users as $user) {
                if ($user->device_key) {
                    // Get the Firebase device token
                    $deviceToken = $user->device_key;
                    
                    if (!$deviceToken) {
                        \Log::error("No device token found for user with ID {$user->id}.");
                        continue; // Skip this user and move to the next one
                    }

                    // Get the additional parameters
                    $postId = $additionalParams['postId'] ?? null;
        
                    // Prepare notification and data arrays
                    $notification = Notification::create($title, $body);
                    $data = [
                        "postId" => $postId,
                    ];
        
                    // Create CloudMessage object
                    $cloudMessage = CloudMessage::withTarget('token', $deviceToken)
                        ->withNotification($notification)
                        ->withData($data);
        
                    try {
                        // Send the notification using Firebase
                        $messaging = app('firebase.messaging');
                        $messaging->send($cloudMessage);
                        
                        \Log::info("Push notification sent successfully to user with ID {$user->id}.");
                    } catch (\Kreait\Firebase\Exception\MessagingException $e) {
                        \Log::error("The message could not be delivered to the device identified by '{$deviceToken}' for user with ID {$user->id}. Error: " . $e->getMessage());
                        // Continue to the next user
                        continue;
                    }
                } else {
                    \Log::error("User with ID {$user->id} does not have a device key.");
                }
            }
        } catch (\Exception $e) {
            \Log::error("Error sending push notification: " . $e->getMessage(), ['exception' => $e]);
            return false;
        }

        return true;
    }
}