<?php
session_start();
require_once 'config.php';           // Your configuration file with credentials
require_once 'vendor/autoload.php';  // Composer autoload for QuickBooks SDK

// Configure the DataService instance for OAuth2
$dataService = QuickBooksOnline\API\DataService\DataService::Configure([
    'auth_mode'       => 'oauth2',
    'ClientID'        => $clientID,
    'ClientSecret'    => $clientSecret,
    'RedirectURI'     => $redirectURI,
    'scope'           => $scope,
    'baseUrl'         => $baseURL
]);

$OAuth2LoginHelper = $dataService->getOAuth2LoginHelper();

if (!isset($_GET['code'])) {
    // No code, so redirect to QuickBooks authorization URL
    $authorizationURL = $OAuth2LoginHelper->getAuthorizationCodeURL();
    header("Location: " . $authorizationURL);
    exit;
} else {
    // We have received the authorization code; exchange it for tokens.
    try {
        $accessToken = $OAuth2LoginHelper->exchangeAuthorizationCodeForToken($_GET['code'], $_GET['realmId']);

        // Store the token data in session
        $_SESSION['accessTokenKey']  = $accessToken->getAccessToken();
        $_SESSION['refreshTokenKey'] = $accessToken->getRefreshToken();
        $_SESSION['tokenExpiresAt']  = $accessToken->getAccessTokenExpiresAt();
        $_SESSION['realmId']         = $_GET['realmId'];

        // Redirect back to index.php after successful authentication
        header("Location: index.php");
        exit;
    } catch (Exception $e) {
        echo "Error exchanging authorization code for tokens: " . $e->getMessage();
        exit;
    }
}
?>
