<?php
require_once 'config.php'; // Includes session_start()

use QuickBooksOnline\API\DataService\DataService;
use QuickBooksOnline\API\Core\OAuth2\OAuth2LoginHelper;

// Check for required parameters from QuickBooks redirect
if (!isset($_GET['code']) || !isset($_GET['realmId']) || !isset($_GET['state'])) {
    $_SESSION['error'] = "Invalid callback request: Missing required parameters.";
    logError("Invalid callback request", $_GET);
    header('Location: index.php');
    exit;
}

// Optional: Verify state parameter here if you implemented CSRF protection
// if ($_GET['state'] !== $_SESSION['oauth_state']) { ... handle error ... }

$code = $_GET['code'];
$realmId = $_GET['realmId'];

try {
    $dataService = DataService::Configure([
        'auth_mode' => 'oauth2',
        'ClientID' => $clientID,
        'ClientSecret' => $clientSecret,
        'RedirectURI' => $redirectURI, // Must match the one used to get the code
        'scope' => $scope,
        'baseUrl' => $baseURL
    ]);

    $oauth2LoginHelper = $dataService->getOAuth2LoginHelper();
    $accessToken = $oauth2LoginHelper->exchangeAuthorizationCodeForToken($code, $realmId);

    // Store token information securely in the session
    $_SESSION['accessTokenKey'] = $accessToken->getAccessToken();
    $_SESSION['refreshTokenKey'] = $accessToken->getRefreshToken();
    $_SESSION['tokenExpiresAt'] = $accessToken->getAccessTokenExpiresAt(); // Store as string/timestamp
    $_SESSION['realmId'] = $realmId;

    logError("Successfully obtained tokens", ['realmId' => $realmId]);
    $_SESSION['message'] = "Successfully connected to QuickBooks!";

    // Redirect back to the main page
    header('Location: index.php');
    exit;

} catch (Exception $e) {
    logError("Failed to exchange authorization code for token", [
        'error' => $e->getMessage(),
        'code' => $code,
        'realmId' => $realmId
    ]);
    $_SESSION['error'] = "Authentication error: Failed to obtain access token. " . $e->getMessage();
    // Clear any potentially partially stored session data on error
    unset($_SESSION['accessTokenKey'], $_SESSION['refreshTokenKey'], $_SESSION['tokenExpiresAt'], $_SESSION['realmId']);
    header('Location: index.php');
    exit;
}
?>