<?php

namespace App\Helpers;

use App\Models\Notification;
use App\Models\User;
use Exception;
use Google_Client;
use Illuminate\Support\Facades\Log;

class NotificationHelper
{
    public static function getAccessToken()
    {
        // Specify the path to your service account key file
        $serviceAccountPath = public_path("firebase-messaging-sw.json");
        // Initialize Google Client
        $client = new Google_Client();
        $client->setAuthConfig($serviceAccountPath);

        // Add the required scope for Firebase Cloud Messaging
        $client->addScope('https://www.googleapis.com/auth/firebase.messaging');

        // Fetch the access token
        $token = $client->fetchAccessTokenWithAssertion();

        // Return the access token
        return $token['access_token'];
    }

    public static function sendNotification($fcmToken, $title = "Message", $message = "", $type = "", $modelId = null)
    {
        try {

            $accessToken = self::getAccessToken();
            $endpoint    = 'https://fcm.googleapis.com/v1/projects/trading-fmcg-292b2/messages:send';
            $bearer      = $accessToken;
            //dd($bearer);
            $data = [
                'message' => [
                    'token' => $fcmToken,
                    'notification' => [
                        'title' => $title,
                        'body' => $message,
                        // 'sound' => 'default',
                    ],
                    'data' => [
                        'notif_type' => (string)$type,
                        'model_id' => (string)$modelId
                    ],
                    'android' => [
                        'priority' => 'high',
                    ],
                    'apns' => [
                        'headers' => [
                            'apns-priority' => '10',
                        ],
                        'payload' => [
                            'aps' => [
                                'sound' => 'default',
                                "content-available" => 1
                            ],
                        ],

                    ],
                ],
            ];

            $jsonData = json_encode($data);

            // Set up cURL options
            $curlOptions = [
                CURLOPT_URL => $endpoint,
                CURLOPT_POST => true,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POSTFIELDS => $jsonData,
                CURLOPT_HTTPHEADER => [
                    'Content-Type: application/json',
                    'Authorization: Bearer ' . $bearer,
                ],
            ];

            // Initialize cURL session
            $ch = curl_init();
            curl_setopt_array($ch, $curlOptions);

            // Execute cURL session and get the response
            $response = curl_exec($ch);

            // Check for cURL errors
            if (curl_errno($ch)) {
                return 'cURL error: ' . curl_error($ch);
            }

            // Close cURL session
            curl_close($ch);
            Log::info("Firebase Notificaion Send", array('data' => $response));

            return $response;
        } catch (\Exception $ex) {
            Log::error("Firebase Notificaion Failed", array('data' => $ex->getMessage()));
            return null;
        }
    }

    public static function sendNotificationNew($fcmTokens, $title = "Message", $message = "", $type = "", $modelId = null)
    {
        try {

            $accessToken = self::getAccessToken();
            $endpoint    = 'https://fcm.googleapis.com/v1/projects/trading-fmcg-292b2/messages:send';
            $bearer      = $accessToken;

            $fcmTokens = $fcmTokens->pluck('fcm_token')->toArray();
            // Ensure tokens is always an array
            if (!is_array($fcmTokens)) {
                $fcmTokens = [$fcmTokens];
            }

             foreach ($fcmTokens as $token) {
                $data = [
                    'message' => [
                        'token' => $token,
                        'notification' => [
                            'title' => $title,
                            'body' => $message,
                            // 'sound' => 'default',
                        ],
                        'data' => [
                            'notif_type' => (string)$type,
                            'model_id' => (string)$modelId
                        ],
                        'android' => [
                            'priority' => 'high',
                        ],
                        'apns' => [
                            'headers' => [
                                'apns-priority' => '10',
                            ],
                            'payload' => [
                                'aps' => [
                                    'sound' => 'default',
                                    "content-available" => 1
                                ],
                            ],

                        ],
                    ],
                ];

                $jsonData = json_encode($data);

                // Set up cURL options
                $curlOptions = [
                    CURLOPT_URL => $endpoint,
                    CURLOPT_POST => true,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_POSTFIELDS => $jsonData,
                    CURLOPT_HTTPHEADER => [
                        'Content-Type: application/json',
                        'Authorization: Bearer ' . $bearer,
                    ],
                ];

                // Initialize cURL session
                $ch = curl_init();
                curl_setopt_array($ch, $curlOptions);

                // Execute cURL session and get the response
                $response = curl_exec($ch);

                // Check for cURL errors
                if (curl_errno($ch)) {
                    return 'cURL error: ' . curl_error($ch);
                }

                // Close cURL session
                curl_close($ch);

            }
            Log::info("Firebase Notificaion Send", array('data' => $response));

            return $response;
        } catch (\Exception $ex) {
            Log::error("Firebase Notificaion Failed", array('data' => $ex->getMessage()));
            return null;
        }
    }

    public static function sendAndStoreNotification($fcmToken, $receiverId, $title = "Message", $message = "", $senderId = null, $type = null, $isNotify = 1, $modelId = null)
    {
        try {
            Log::info("preparing to send Notificaion", array('data' => $fcmToken));
            Notification::createRecord(
                $receiverId,
                $title,
                $message,
                $senderId,
                $type,
                $modelId,
            );

            if ($isNotify) {
                self::sendNotification($fcmToken, $title, $message, $type, $modelId);
            }
        } catch (Exception $ex) {
            Log::error("Send Notification Error", array('error' => $ex->getMessage()));
        }
    }

    public static function sendAndStoreNotificationNew($userFcmTokens, $receiverId, $title = "Message", $message = "", $senderId = null, $type = null, $isNotify = 1, $modelId = null)
    {
        try {

            $fcmTokens = $userFcmTokens->pluck('fcm_token')->toArray();

            if (!is_array($fcmTokens)) {
                $fcmTokens = [$fcmTokens];
            }

            Log::info("Preparing to send Notification", ['data' => $fcmTokens]);

            // Store in DB (once per user, not per token)
            Notification::createRecord(
                $receiverId,
                $title,
                $message,
                $senderId,
                $type,
                $modelId,
            );

            if ($isNotify) {
                foreach ($fcmTokens as $token) {
                    self::sendNotification($token, $title, $message, $type, $modelId);
                }
            }
        } catch (Exception $ex) {
            Log::error("Send Notification Error", ['error' => $ex->getMessage()]);
        }
    }
}
