<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

use Firebase\JWT\JWT;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Signer\Rsa\Sha256;
use Lcobucci\JWT\Signer\Key\LocalFileReference;

//use Firebase\JWT\JWT;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    protected function FMC_V1_API()
    {
        $privateKeyPath = __DIR__ . '/te-amoapp-firebase-adminsdk-y2x6a-509d2dd092.json'; // Path to your service account private key JSON file // Path to your service account private key JSON file
        $projectId = 'te-amoapp'; // Your Firebase project ID
        $deviceToken = 'cdf9Jd_IQIuQ23j_7UtF5g:APA91bFvpIJu7bb8faMRar_nb6nnrQXMrN8gJVmkPdp8y9Qhep9hGSQhwf5zdVQvI6hAqnMNvOqacTS5573Q46Dngjpw5iLCo2NE3vrg19sWa6r9IpwnDCJ5H2jqrX7WL8EKisu5eidM'; // FCM registration token of the target device
        $clientEmail = 'firebase-adminsdk-y2x6a@te-amoapp.iam.gserviceaccount.com';

        // Generate a JWT using the Lcobucci\JWT\Signer\Rsa\Sha256 signer
        $signer = new Sha256();
        $privateKey = "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCNfJCopuL1D+Se\nT0slzpT5zWjApPoLSGuniYTKaK6i/obtDKCXLIARFwyPShWQZgys9v726GbHY/sx\n5hs65kQzvnf/KPop6hYlIBOktUSG9okHorrqMeY7tR8dE0M55bwIHClOQ8hM+I0b\nO2N+ttM/bmb63sazWGwe5UFfAIG4tlqgjPlDKEz5YsoqOK5oq0O+0X1gcalF+fIG\nwlGH8LGcoekQiMZxFOuuxRdby4FWkGZtCKP3arqLfJ1eyWYIskbowex5o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uMW/Vo0jcHYB43M2x7MEMem/Kvrr7qMgWOjnEpot+EyWD6DPed\n/i3otPBOWZuyU0P85ivFnSqqrc7pKlY9PH+GjoWNAoGBALG5NJeoRO7ce4a585qv\n4f9412gduTUfbh50P3Vw1FVVU+ovXBkMvXTzkd7ugDguRqdwmrMfLeGEqgIeB8+5\nrqSJwxLDopphAevqDHO5+5iK1kp7cLWUJubn/NDrmeaQnSvMx2Vju/Uzx7A/Aq4r\ntZahbbSy6TvOJ2bF3JM2LOIk\n-----END PRIVATE KEY-----\n";
        $time = time();

        /*$jwt = JWT::builder()
            ->issuedBy($clientEmail)
            ->permittedFor('https://www.googleapis.com/oauth2/v4/token')
            ->expiresAt($time + 3600)
            ->issuedAt($time)
            ->getToken($signer, $privateKey);

        $accessToken = '';*/
        
        $jwt = JWT::encode([
            'iss' => $clientEmail,
            'aud' => 'https://www.googleapis.com/oauth2/v4/token',
            'exp' => $time + 3600,
            'iat' => $time,
        ], $privateKey, 'RS256');

        // Exchange the JWT for an access token
        $response = Http::asForm()->post('https://www.googleapis.com/oauth2/v4/token', [
            'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
            'assertion' => $jwt,
        ]);

        if ($response->successful()) {
            $accessToken = $response->json()['access_token'];
            $return = ['accessToken' => $accessToken];
            //dd($return);
        }
        else
        {
           $return = ['message' => 'Token Failed'];
           //dd($return);
        }


        $message = [
            'message' => [
                'token' => $deviceToken,
                'notification' => [
                    'title' => 'Hello',
                    'body' => 'This is a sample notification'
                ]
            ]
        ];

        $response = Http::withHeaders([
            'Authorization' => 'Bearer '.$accessToken,
            'Content-Type' => 'application/json'
        ])->post("https://fcm.googleapis.com/v1/projects/$projectId/messages:send", $message);

        if ($response->successful()) {
            $status = $response->json();
        } else {
            return ['message' => 'Request Failed'];
        }

        // Handle the response based on the status code and content of the $status array
        var_dump($status); 
    }
}
