<?php
// QuickBooks Callback Handler with Error Handling
// This script handles the OAuth callback from QuickBooks

// Include the shared config file
require_once 'config.php';

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Load QuickBooks SDK classes directly
require_once 'vendor/autoload.php';

try {
    // Check if composer dependencies exist
    if (!file_exists('vendor/autoload.php')) {
        throw new Exception("Composer dependencies not found. Please run 'composer install'");
    }

    // Check if we have the authorization code and realmId
    if (!isset($_GET['code']) || !isset($_GET['realmId'])) {
        throw new Exception("Missing authorization code or realm ID in the callback request");
    }

    // Configure DataService
    $dataService = QuickBooksOnline\API\DataService\DataService::Configure(array(
        'auth_mode' => 'oauth2',
        'ClientID' => $clientID,
        'ClientSecret' => $clientSecret,
        'RedirectURI' => $redirectURI,
        'realmId' => '9130357879244816',
        'scope' => $scope,
        'baseUrl' => $baseURL
    ));
    
    // Get OAuth2LoginHelper
    $OAuth2LoginHelper = $dataService->getOAuth2LoginHelper();
    
    // Exchange authorization code for access token
    try {
        $accessToken = $OAuth2LoginHelper->exchangeAuthorizationCodeForToken($_GET['code'], $_GET['realmId']);
        
        // Store individual token components instead of the whole object
        $_SESSION['accessTokenKey'] = $accessToken->getAccessToken();
        $_SESSION['refreshTokenKey'] = $accessToken->getRefreshToken();
        $_SESSION['tokenExpiresAt'] = $accessToken->getAccessTokenExpiresAt();
        $_SESSION['realmId'] = $_GET['realmId'];
        
        // Verify that the token was obtained successfully
        if (!$accessToken) {
            throw new Exception("Failed to obtain access token");
        }
        
        // Log successful authentication
        logError("Successfully authenticated with QuickBooks", array(
            'realmId' => $_GET['realmId'],
            'token_expires' => $accessToken->getAccessTokenExpiresAt()
        ));
        
        // Successful authentication, redirect back to main page
        header('Location: index.php');
        exit;
    } catch (Exception $e) {
        logError("Error exchanging authorization code for token", array(
            'error' => $e->getMessage(),
            'code' => $_GET['code'],
            'realmId' => $_GET['realmId']
        ));
        throw new Exception("Error exchanging authorization code for token: " . $e->getMessage());
    }
} catch (Exception $e) {
    $errorMessage = $e->getMessage();
    logError("Uncaught exception in callback handler", $errorMessage);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>QuickBooks Authentication Error</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            margin: 20px;
            color: #333;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        h1 {
            color: #c0392b;
        }
        .error-message {
            background-color: #f8d7da;
            color: #721c24;
            padding: 15px;
            margin-bottom: 20px;
            border: 1px solid #f5c6cb;
            border-radius: 4px;
        }
        .action-buttons {
            margin-top: 20px;
        }
        .btn {
            display: inline-block;
            padding: 10px 15px;
            background-color: #3498db;
            color: white;
            text-decoration: none;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>QuickBooks Authentication Error</h1>
        <div class="error-message">
            <p><strong>An error occurred during authentication:</strong></p>
            <p><?php echo htmlspecialchars($errorMessage); ?></p>
        </div>
        <div class="action-buttons">
            <a href="index.php" class="btn">Try Again</a>
        </div>
        <div>
            <h3>Troubleshooting Tips:</h3>
            <ul>
                <li>Check that your Client ID and Client Secret are correct in config.php</li>
                <li>Verify that your Redirect URI matches exactly what's configured in the QuickBooks Developer portal</li>
                <li>Make sure the required PHP extensions are installed (curl, openssl, json)</li>
                <li>Check the error log for more detailed information</li>
            </ul>
        </div>
    </div>
</body>
</html>
<?php
    exit;
}
?>