<?php

namespace App\Functions;

use Illuminate\Support\Facades\Log;

class PushNotification
{
    public static function send($data)
    {
        if ($data['client_id'] ?? false) {
            foreach (\Modules\Client\Entities\DeviceToken::where('client_id', $data['client_id'])->whereNotNull('device_token')->pluck('device_token') as $token) {
                if ($token) {
                    self::send_notification([
                        'message' => $data['message'], 
                        'data' => $data['data'], 
                        'image' => $data['image'] ?? null,  
                        'token' => $token,    
                    ]);
                }
            }
        } else {
            self::send_notification([
                'message' => $data['message'], 
                'data' => $data['data'], 
                'topic' => $data['topic'] ?? 'all_users', 
                'image' => $data['image'] ?? null,  
            ]);
        }
    }

    public static function send_notification($data)
    {
        if ($data['token'] ?? false) {
            $notification = [
                'message' => [
                    'token' => $data['token'],
                    'notification' => [
                        'title' => env('APP_NAME'),
                        'body' => $data['message'],
                        'image' => $data['image'] ?? null,
                    ],
                    'data' => $data['data'],
                ],
            ];
        } else {
            $notification = [
                'message' => [
                    'topic' => $data['topic'] ?? 'all_users',
                    'notification' => [
                        'title' => env('APP_NAME'),
                        'body' => $data['message'],
                        'image' => $data['image'] ?? null,
                    ],
                    'data' => $data['data'],
                    'apns' => [
                        'payload' => [
                            'aps' => [
                                'sound' => 'default',
                                'mutable-content' => 1,
                            ],
                        ],
                    ],
                ],
            ];
        }

        $encodedData = json_encode($notification);

        $headers = [
            'Authorization: Bearer '.self::getToken(),
            'Content-Type: application/json',
        ];

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/v1/projects/nabtat-ali-app/messages:send');
        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_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $encodedData);
        $result = curl_exec($ch);
        Log::info($encodedData);
        Log::info($result);
        curl_close($ch);
    }

    public static function getToken()
    {
        $keyFilePath = public_path('firebase.json');
        $keyData = json_decode(file_get_contents($keyFilePath), true);

        $header = [
            'alg' => 'RS256',
            'typ' => 'JWT',
        ];

        $now = time();
        $claims = [
            'iss' => $keyData['client_email'],
            'scope' => 'https://www.googleapis.com/auth/cloud-platform',
            'aud' => 'https://oauth2.googleapis.com/token',
            'exp' => $now + 3600,
            'iat' => $now,
        ];

        $base64UrlHeader = self::base64UrlEncode(json_encode($header));
        $base64UrlClaims = self::base64UrlEncode(json_encode($claims));

        $signatureInput = $base64UrlHeader.'.'.$base64UrlClaims;

        openssl_sign($signatureInput, $signature, $keyData['private_key'], 'sha256WithRSAEncryption');
        $base64UrlSignature = self::base64UrlEncode($signature);

        $jwt = $signatureInput.'.'.$base64UrlSignature;

        $postFields = http_build_query([
            'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
            'assertion' => $jwt,
        ]);

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, 'https://oauth2.googleapis.com/token');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);

        $response = curl_exec($ch);
        if ($response === false) {
            exit('Curl failed: '.curl_error($ch));
        }

        $responseData = json_decode($response, true);
        curl_close($ch);

        return $responseData['access_token'];
    }

    private static function base64UrlEncode($data)
    {
        return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($data));
    }
}
