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

// --- Required SDK Classes ---
use QuickBooksOnline\API\DataService\DataService;
use QuickBooksOnline\API\Core\OAuth2\OAuth2LoginHelper;
use QuickBooksOnline\API\Exception\ServiceException;
// *** We are testing THIS class's constructor ***
use QuickBooksOnline\API\ReportService\ReportService;

// --- Authentication Check and Token Refresh ---
if (!isset($_SESSION['accessTokenKey']) || !isset($_SESSION['refreshTokenKey']) || !isset($_SESSION['realmId'])) {
    $_SESSION['error'] = "Not authenticated. Please connect to QuickBooks first.";
    logError("ReportService Test: Attempt without authentication.");
    header('Location: index.php');
    exit;
}

$accessTokenKey = $_SESSION['accessTokenKey'];
$refreshTokenKey = $_SESSION['refreshTokenKey'];
$realmId = $_SESSION['realmId'];
$tokenExpiresAtStr = $_SESSION['tokenExpiresAt'] ?? null;

// --- Token Expiry Check ---
$isExpired = true;
if ($tokenExpiresAtStr) {
    try {
        $expiryTimestamp = strtotime($tokenExpiresAtStr);
        if ($expiryTimestamp !== false) {
            $isExpired = ($expiryTimestamp - (5 * 60)) < time();
        } else { logError("ReportService Test: Failed to parse token expiry time string", $tokenExpiresAtStr); }
    } catch (Exception $e) { logError("ReportService Test: Error parsing token expiry time", ['string' => $tokenExpiresAtStr, 'error' => $e->getMessage()]); }
}

$dataService = null; // Initialize

// --- Token Refresh Logic ---
if ($isExpired) {
    logError("ReportService Test: Token expired. Attempting refresh.", ['realmId' => $realmId]);
    try {
        $dataServiceForRefresh = DataService::Configure([ /* ... refresh config ... */
             'auth_mode' => 'oauth2', 'ClientID' => $clientID, 'ClientSecret' => $clientSecret,
             'RedirectURI' => $redirectURI, 'scope' => $scope, 'baseUrl' => $baseURL,
             'refreshTokenKey' => $refreshTokenKey ]);
        $oauth2LoginHelper = $dataServiceForRefresh->getOAuth2LoginHelper();
        $refreshedAccessToken = $oauth2LoginHelper->refreshToken();

        // Configure the final $dataService instance
        $dataService = DataService::Configure([ /* ... final config ... */
            'auth_mode' => 'oauth2', 'ClientID' => $clientID, 'ClientSecret' => $clientSecret,
            'scope' => $scope, 'baseUrl' => $baseURL,
            'accessTokenKey' => $refreshedAccessToken->getAccessToken(),
            'refreshTokenKey' => $refreshedAccessToken->getRefreshToken(),
            'QBORealmID' => $realmId,
            'minorVersion' => '70' // Keep minor version for consistency
        ]);
        $dataService->throwExceptionOnError(true);

        // Update session
        $_SESSION['accessTokenKey'] = $refreshedAccessToken->getAccessToken();
        $_SESSION['refreshTokenKey'] = $refreshedAccessToken->getRefreshToken();
        $_SESSION['tokenExpiresAt'] = $refreshedAccessToken->getAccessTokenExpiresAt();
        logError("ReportService Test: Token refreshed & DataService configured.", ['realmId' => $realmId]);

    } catch (Exception $e) { /* ... handle refresh failure ... */
        logError("ReportService Test: Failed to refresh token", ['error' => $e->getMessage(), 'realmId' => $realmId]);
        session_unset(); session_destroy(); session_start();
        $_SESSION['error'] = "Failed to refresh QuickBooks connection: " . $e->getMessage() . ". Please connect again.";
        header('Location: index.php');
        exit;
    }
}

// --- Configure DataService if Token Was NOT Refreshed ---
try {
    if ($dataService === null) {
        logError("ReportService Test: Token not expired. Configuring DataService.", ['realmId' => $realmId]);
        $dataService = DataService::Configure([ /* ... standard config ... */
            'auth_mode' => 'oauth2', 'ClientID' => $clientID, 'ClientSecret' => $clientSecret,
            'scope' => $scope, 'baseUrl' => $baseURL,
            'accessTokenKey' => $accessTokenKey, 'refreshTokenKey' => $refreshTokenKey,
            'QBORealmID' => $realmId,
            'minorVersion' => '70' // Keep minor version for consistency
        ]);
        if (!$dataService instanceof DataService) { throw new \Exception("DataService::Configure did not return a valid object."); }
        $dataService->throwExceptionOnError(true);
        logError("ReportService Test: DataService configured successfully.", ['realmId' => $realmId]);
    }
} catch (\Throwable $e) { /* ... handle configuration failure ... */
     logError("ReportService Test: CRITICAL - Failed during DataService::Configure", [ /*...*/ ]);
     $_SESSION['error'] = "Failed to initialize QuickBooks connection: " . $e->getMessage();
     header('Location: index.php');
     exit;
}

// --- Simple Test: Try to Instantiate ReportService ---
$reportServiceInstance = null;
$instantiationError = null;

try {
    // Ensure $dataService is valid before attempting
    if (!isset($dataService) || !$dataService instanceof DataService) {
         throw new \Exception("DataService object is invalid before attempting ReportService instantiation.");
    }

    logError("ReportService Test: Attempting 'new ReportService(\$dataService)'...", ['realmId' => $realmId]);

    // *** THE ACTUAL TEST IS JUST THIS LINE ***
    $reportServiceInstance = new ReportService($dataService);
    // *** END OF TEST LINE ***

    // If the line above didn't throw an exception, instantiation succeeded
    logError("ReportService Test: SUCCESS - 'new ReportService(\$dataService)' completed without error.", ['realmId' => $realmId]);
    $_SESSION['message'] = "ReportService Test: Object instantiation SUCCEEDED.";


} catch (\Throwable $e) { // Catch ANY error during instantiation
    // Log the specific error
    $instantiationError = $e;
    $errorDetails = [
        'error_class' => get_class($e),
        'error_message' => $e->getMessage(),
        'file' => $e->getFile(),
        'line' => $e->getLine(),
        'trace' => substr($e->getTraceAsString(), 0, 1500) . '...'
    ];
    logError("ReportService Test: FAILED - Error during 'new ReportService(\$dataService)'.", $errorDetails);
    $_SESSION['error'] = "ReportService Test: Object instantiation FAILED. Error: " . $e->getMessage();
}

// --- We are NOT executing a report in this test ---
// --- Just checking if the object could be created ---

// Redirect back to index.php with the result message
header('Location: index.php');
exit;
?>