<?php
$redirectUri = 'https://api.tripz-egypt.com/tripz/auth/google_auth/callback.php';

// google_auth.php

require_once __DIR__ . '/../vendor/autoload.php';

use Google\Client;

header('Content-Type: application/json');

$response = [
    'success' => false,
    'error' => null,
    'data' => null,
];

try {
    if (!isset($_POST['code'])) {
        throw new Exception("Missing authorization code.");
    }

    $code = $_POST['code'];

    $client = new Client();
    $client->setClientId('1086900987150-j8brn0i5s97315kh1ej9jr72grkfqgh5.apps.googleusercontent.com');
    $client->setClientSecret('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');
    $client->setRedirectUri('postmessage');
    $client->addScope('email');
    $client->addScope('profile');

    $token = $client->fetchAccessTokenWithAuthCode($code);

    if (isset($token['error'])) {
        throw new Exception("Access token error: " . $token['error']);
    }

    $client->setAccessToken($token['access_token']);

    $oauth2 = new Google_Service_Oauth2($client);
    $userinfo = $oauth2->userinfo->get();

    $response['success'] = true;
    $response['data'] = [
        'id' => $userinfo->id,
        'email' => $userinfo->email,
        'name' => $userinfo->name,
        'picture' => $userinfo->picture,
    ];

} catch (Exception $e) {
    $response['error'] = $e->getMessage();
}

echo json_encode($response);