<?php
namespace Modules\Notification\Services;

/**
 * Class based Helper to send Notifications using FCM v1 API
 */
class SendNotificationService
{
    /**
     * Helper to send Notifications via FCM v1 API
     *
     * @param array $data
     * @param array $target
     * @return string
     */
    public static function sendNotification($data = '', $target = [])
    {
        $file = storage_path('firebase/fossha-f8d5a-firebase-adminsdk-fbsvc-f8e891f306.json');
        $serviceAccount = json_decode(file_get_contents($file), true);
        $accessToken = self::getAccessToken($serviceAccount);

        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;

        $headers = [
            'Content-Type: application/json',
            "Authorization: Bearer $accessToken",
        ];

        // Sending to multiple tokens
        if (isset($target['registration_ids']) && is_array($target['registration_ids'])) {
            $responses = [];
            foreach ($target['registration_ids'] as $token) {
                $payload = [
                    "message" => [
                        "token" => $token,
                        "notification" => [
                            "title" => ($data['title'] ?? "--"),
                            "body" => ($data["body"] ?? $data["message"] ?? '--')
                        ],
                        "data" => $data
                    ]
                ];

                $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) {
                    $responses[] = 'FCM Send Error: ' . curl_error($ch);
                } else {
                    $responses[] = json_decode($result, true);
                }
                curl_close($ch);
            }
            return json_encode($responses);
        }

        // Sending to a single token
        if (isset($target['to']) && is_string($target['to'])) {
            $payload = [
                "message" => [
                    "token" => $target['to'],
                    "notification" => [
                        "title" => ($data['title'] ?? "--"),
                        "body" => ($data["body"] ?? $data["message"] ?? '--')
                    ],
                    "data" => $data
                ]
            ];

            $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) {
                return 'FCM Send Error: ' . curl_error($ch);
            }
            curl_close($ch);
            return $result;
        }

        return 'No valid target specified.';
    }

    private static function getAccessToken($serviceAccount)
    {
        $now = time();
        $jwtHeader = json_encode(['alg' => 'RS256', 'typ' => 'JWT']);
        $jwtClaim = json_encode([
            'iss' => $serviceAccount['client_email'],
            'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
            'aud' => 'https://oauth2.googleapis.com/token',
            'iat' => $now,
            'exp' => $now + 3600
        ]);

        $jwt = rtrim(strtr(base64_encode($jwtHeader), '+/', '-_'), '=') . '.' . rtrim(strtr(base64_encode($jwtClaim), '+/', '-_'), '=');
        $signature = '';
        openssl_sign($jwt, $signature, $serviceAccount['private_key'], 'sha256');
        $jwt .= '.' . rtrim(strtr(base64_encode($signature), '+/', '-_'), '=');

        $postData = 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_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        $result = curl_exec($ch);

        if ($result === FALSE) {
            return false;
        }

        $response = json_decode($result, true);
        return $response['access_token'] ?? false;
    }
}
