<?php

require 'config.php';          // <-- this gives $pdorequire 'google_config.php';   // <-- this gives getGoogleClient()

$client = getGoogleClient();

if (isset($_GET['code'])) {

    $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);

    if (isset($token['access_token'])) {

        $accessToken  = $token['access_token'];
        $refreshToken = $token['refresh_token'] ?? null;

        $expiresAt = null;
        if (!empty($token['expires_in'])) {
            $expiresAt = date("Y-m-d H:i:s", time() + (int)$token['expires_in']);
        }

        // Keep only one token row
        $pdo->query("DELETE FROM google_tokens");

        $stmt = $pdo->prepare("
            INSERT INTO google_tokens 
            (access_token, refresh_token, expires_at)
            VALUES (?, ?, ?)
        ");

        $stmt->execute([
            $accessToken,
            $refreshToken,
            $expiresAt
        ]);

        echo "Google Calendar Connected Successfully & Token Saved!";
    } else {
        echo "Token error: " . json_encode($token);
    }

} else {
    echo "No authorization code received.";
}
