<?php

if (!function_exists('send_fcm_notification')) {
    /**
     * Sends an FCM Notification via the HTTP v1 API
     *
     * @param array $device_tokens An array of device tokens
     * @param string $title The notification title
     * @param string $body The notification body
     * @param array $data Additional data payload (optional)
     * @return array Response from FCM
     */
    function send_fcm_notification($device_tokens, $title, $body, $data = []) {
        $key_file_path = APPPATH . 'config/firebase_notification_key.json'; // Path to your service account JSON file
        $project_id = 'mrit-24277'; // Replace with your Firebase Project ID
    

        // Generate the OAuth 2.0 Access Token
        $access_token = generate_access_token($key_file_path);

        if (!$access_token) {
            return ['status' => 'error', 'message' => 'Unable to generate access token'];
        }

        $url = "https://fcm.googleapis.com/v1/projects/$project_id/messages:send";

        $responses = [];

        foreach ($device_tokens as $token) {
            $message = [
                'message' => [
                    'token' => $token,
                    'notification' => [
                        'title' => $title,
                        'body' => $body,
                    ],
                ],
            ];

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

            $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_POSTFIELDS, json_encode($message));

            $response = curl_exec($ch);

            if (curl_errno($ch)) {
                $responses[] = ['status' => 'error', 'message' => curl_error($ch)];
            } else {
                $responses[] = ['status' => 'success', 'response' => json_decode($response, true)];
            }

            curl_close($ch);
        }

        return $responses;
    }
    

    /**
     * Generates an OAuth 2.0 Access Token from the service account JSON file
     *
     * @param string $key_file_path Path to the service account JSON file
     * @return string|null The access token, or null on failure
     */
    function generate_access_token($key_file_path) {
        // Load the service account key JSON file
        $key = json_decode(file_get_contents($key_file_path), true);

        // Create a JWT (Header + Payload)
        $header = base64url_encode(json_encode(['alg' => 'RS256', 'typ' => 'JWT']));
        $now = time();
        $payload = base64url_encode(json_encode([
            'iss' => $key['client_email'],
            'sub' => $key['client_email'],
            'aud' => 'https://oauth2.googleapis.com/token',
            'iat' => $now,
            'exp' => $now + 3600, // Token expires in 1 hour
            'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
        ]));

        // Sign the JWT using the private key
        $signature = '';
        openssl_sign($header . '.' . $payload, $signature, $key['private_key'], 'SHA256');

        // Final JWT
        $jwt = $header . '.' . $payload . '.' . base64url_encode($signature);

        // Exchange the JWT for an access token
        $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_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
            'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
            'assertion' => $jwt,
        ]));

        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            return null;
        }

        $response_data = json_decode($response, true);

        curl_close($ch);

        return $response_data['access_token'] ?? null;
    }

    /**
     * Encodes data in URL-safe Base64
     *
     * @param string $data Data to encode
     * @return string URL-safe Base64 encoded string
     */
    function base64url_encode($data) {
        return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
    }
}
