<?php

function getFirebaseAccessToken()
{
    $json = json_decode(
        file_get_contents(__DIR__ . '/../firebase/firebase_service_account.json'),
        true
    );

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

    $now = time();

    $payload = [
        'iss' => $json['client_email'],
        'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
        'aud' => 'https://oauth2.googleapis.com/token',
        'iat' => $now,
        'exp' => $now + 3600
    ];

    $jwt = base64url_encode(json_encode($header)) . "." .
           base64url_encode(json_encode($payload));

    openssl_sign(
        $jwt,
        $signature,
        $json['private_key'],
        'sha256'
    );

    $jwt .= "." . base64url_encode($signature);

    $ch = curl_init();

    curl_setopt_array($ch,[
        CURLOPT_URL => "https://oauth2.googleapis.com/token",
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS => http_build_query([
            'grant_type'=>'urn:ietf:params:oauth:grant-type:jwt-bearer',
            'assertion'=>$jwt
        ])
    ]);

    $response = json_decode(curl_exec($ch),true);

    curl_close($ch);

    return $response['access_token'];
}

function base64url_encode($data)
{
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}