<?php
namespace App\Helpers;

/**
* Class based Helper to send Notifications
*/
class NotificationHelper
{

    /**
     * Helper to send Notifications FCM
     * 
     * @param array $data
     * @param array $target
     * @return string
     */
    public static function sendNotification($data = '', $target = []) {
        // Create a Service Account Key
        /** Go to the Firebase Console → Project Settings → Service Accounts.
         * Press "Generate new private key".
         * Save the JSON file securely on  server on storage/firebase.
        */ 

        $file= storage_path('firebase/fossha-f8d5a-firebase-adminsdk-fbsvc-f8e891f306.json');
        $serviceAccount = json_decode(file_get_contents($file), true);
        // dd($serviceAccount);
        $accessToken= self::getAccessToken($serviceAccount);
        // dd($accessToken);
        if (!$accessToken) {
            return 'fail access token';
        }

        $projectId= $serviceAccount['project_id'];
        $url = "https://fcm.googleapis.com/v1/projects/$projectId/messages:send";

        $data = isset($data['notification']) ? $data['notification'] : $data;

        $payload = [
            "message" => [
                "notification" => [
                    "title" => ($data['title'] ?? "--"),
                    "body" => ($data["body"] ?? $data["message"] ?? '--')
                ],
                "data" => $data
            ]
        ];
        $tokens= [];
        if(isset($target['registration_ids']) && $target['registration_ids'] && is_array($target['registration_ids'])){
            $tokens= $target['registration_ids'];
            $payload["message"]['topic'] = 'all_users';
        }
        if(isset($target['topic']) && $target['topic'] && is_string($target['topic'])){
            $payload["message"]['topic'] = $target['topic'];
        }
        if(isset($target['to']) && $target['to'] && is_string($target['to'])){
            $payload["message"]['token']= $target['to'];
        }
        if (request()->has('debug')) {
            // dump($accessToken, $url, $payload);
        }
        $headers = array(
            'Content-Type:application/json',
            "Authorization: Bearer $accessToken",
        );
        //CURL request to route notification to FCM connection server (provided by Google)
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Oops! FCM Send Error: ' . curl_error($ch));
        }
        curl_close($ch);
        return $result;
    }

    private static function getAccessToken($serviceAccount)
    {
        $header = [
            'alg' => 'RS256',
            'typ' => 'JWT'
        ];
    
        $now = time();
        $payload = [
            'iss' => $serviceAccount['client_email'], // Issuer
            // 'scope' => 'https://www.googleapis.com/auth/cloud-platform',
            'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
            'aud' => 'https://oauth2.googleapis.com/token',
            'iat' => $now, // Issued at
            'exp' => $now + 3600 // Expiration time (1 hour)
        ];
    
        $jwtHeader = self::base64url_encode(json_encode($header));
        $jwtPayload = self::base64url_encode(json_encode($payload));
        $unsignedToken = "$jwtHeader.$jwtPayload";
    
        // Sign the token with the private key
        openssl_sign($unsignedToken, $signature, $serviceAccount['private_key'], 'SHA256');
        $jwtSignature = self::base64url_encode($signature);
    
        $jwt = "$unsignedToken.$jwtSignature";
    
        // Make a request to get the OAuth token
        $ch = curl_init('https://oauth2.googleapis.com/token');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
            'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
            'assertion' => $jwt
        ]));
    
        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            // die('cURL Error: ' . curl_error($ch));
            return false;
        }
        curl_close($ch);
        
        $data = json_decode($response, true);
        if (isset($data['access_token'])) {
            return $data['access_token'];
        }
        
        // die('Failed to obtain access token: ' . $response);
        return false;
    }
    // Encode to Base64 URL-safe
    private static function base64url_encode($data)
    {
        return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
    }

    //
    public static function sendNotification_OLD($data = '', $target = '') {
        //FCM API end-point
        $url = 'https://fcm.googleapis.com/fcm/send';
        //api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
        $server_key = env('FIREBASE_SERVER_KEY');
        // dd($server_key);
        $data['data'] = isset($data['notification']) ? $data['notification'] : $data;
        $fields = array_merge($target, $data);
        $headers = array(
            'Content-Type:application/json',
            'Authorization:key=' . $server_key
        );
        //CURL request to route notification to FCM connection server (provided by Google)
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Oops! FCM Send Error: ' . curl_error($ch));
        }
        curl_close($ch);
        return $result;
    }
}
