<?php

function getAccessToken($credentialsFilePath)
{
    // if (!cache()->has('access_token')):
    $credentials = json_decode(file_get_contents($credentialsFilePath), true);
    $jwtHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode(json_encode(['alg' => 'RS256', 'typ' => 'JWT'])));
    $jwtClaimSet = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode(json_encode([
        'iss' => $credentials['client_email'],
        'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
        'aud' => 'https://oauth2.googleapis.com/token',
        'exp' => time() + 3600,
        'iat' => time()
    ])));
    $signatureInput = "$jwtHeader.$jwtClaimSet";
    openssl_sign($signatureInput, $signature, $credentials['private_key'], 'SHA256');
    $jwt = "$signatureInput." . str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
    $ch = curl_init('https://oauth2.googleapis.com/token');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS => http_build_query([
            'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
            'assertion' => $jwt
        ])
    ]);
    $response = curl_exec($ch);
    curl_close($ch);
    $access_token = json_decode($response, true)['access_token'];
    cache()->put('access_token', $access_token, 3600);
    // endif;
    // return cache()->get('access_token');
}

function SendGoogleApis($headers, $project_id, $payload)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://fcm.googleapis.com/v1/projects/$project_id/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_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_VERBOSE, true); // Enable verbose output for debugging
    $response = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);

    if ($err) :
        return response()->json([
            'message' => 'Curl Error: ' . $err,
            'status' => 500
        ]);
    endif;
    return response()->json([
        'message' => 'Notification has been sent',
        'response' => json_decode($response, true),
        'status' => 200
    ]);
}
