<?php
$clientID = '908446786775-57j76m9i42r6kgihtmardqn0piiftk5c.apps.googleusercontent.com';
$clientSecret = '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';
$redirectUri = 'http://mcc-dnc.dev/google-api/callback.php';

if (!isset($_GET['code'])) {
    exit('No auth code provided');
}

$code = $_GET['code'];

// Step 1: Exchange code for access token
$tokenResponse = file_get_contents("https://oauth2.googleapis.com/token", false, stream_context_create([
    'http' => [
        'method' => 'POST',
        'header' => "Content-Type: application/x-www-form-urlencoded",
        'content' => http_build_query([
            'code' => $code,
            'client_id' => $clientID,
            'client_secret' => $clientSecret,
            'redirect_uri' => $redirectUri,
            'grant_type' => 'authorization_code'
        ])
    ]
]));

$tokenData = json_decode($tokenResponse, true);
$accessToken = $tokenData['access_token'] ?? null;

if (!$accessToken) {
    exit('Failed to obtain access token');
}

// Step 2: Use token to access Gmail profile
$gmailProfile = file_get_contents("https://gmail.googleapis.com/gmail/v1/users/tasminahussain7@gmail.com/profile", false, stream_context_create([
    'http' => [
        'method' => 'GET',
        'header' => "Authorization: Bearer $accessToken"
    ]
]));

echo "<h3>Gmail Profile:</h3>";
echo "<pre>";
print_r(json_decode($gmailProfile, true));
echo "</pre>";
