<?php
// File: app/Helpers/oauth_helper.php

use Google\Client as GoogleClient;
use Google\Service\Oauth2;

// Check if the function exists, to prevent redeclaration
if (!function_exists('googleOauthLogin')) {

    function googleOAuthLogin($oauthToken)
    {   
        
        // Retrieve configuration values from environment variables
        // $appName = "710416535204-q948ovmbgs74lpf7so5866qtk8bpjthm.apps.googleusercontent.com";
        // $clientID = "710416535204-q948ovmbgs74lpf7so5866qtk8bpjthm.apps.googleusercontent.com";
        // $clientSecret = "18GKZJcIChn1Nore25fLPoT52137";
        // $redirectUri = "http://localhost/ts_tat/googleoauth";
        // $scopes = ["https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"];

        $clientID     = '696241936560-m2mr272ge7vr2n4q36c22l3d2gdgi90l.apps.googleusercontent.com';
        $clientSecret = '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';
        $redirectUri = "http://localhost/ts_tat/googleoauth";       
        $scopes = ["https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"];


        // Initialize a new Google client
        $client = new GoogleClient();
        $client->setClientId($clientID);
        $client->setClientSecret($clientSecret);
        $client->setRedirectUri($redirectUri); 
        $client->addScope($scopes);
        // $client->setApprovalPrompt('force'); 
        $client->setPrompt('consent'); 
        $client->setAccessType('offline');

        // Check if an OAuth token is provided
        if ($oauthToken) {
            try {
                // Attempt to fetch the access token with the provided OAuth token
                $token = $client->fetchAccessTokenWithAuthCode($oauthToken);
                $client->setAccessToken($token);

                $oauth = new Oauth2($client);
                
                // Get user information using the OAuth2 service
                $user_info = $oauth->userinfo->get();
                return $user_info;

            } catch (\Exception $e) {
                // Handle exceptions and return an error message
                return 'Error fetching access token: ' . $e->getMessage();
            }
        } else {
            // If no OAuth token is provided, generate the authentication URL
            $url = $client->createAuthUrl();
            // Redirect the user to the authentication URL
            // return  $url;
            return redirect()->to(filter_var($url, FILTER_SANITIZE_URL));
        }
    }
}

?>
