<?php
// QuickBooks PHP Integration with Error Handling
// This script connects to QuickBooks Online API, authenticates, and pulls account data

// 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';

$errorMessage = null;
$accountsData = [];

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

    // Handle logout request
    if (isset($_GET['logout'])) {
        // Clear session data
        session_unset();
        session_destroy();
        
        // Redirect to the main page
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }

    // Initialize token data
    $accessTokenKey = isset($_SESSION['accessTokenKey']) ? $_SESSION['accessTokenKey'] : null;
    $refreshTokenKey = isset($_SESSION['refreshTokenKey']) ? $_SESSION['refreshTokenKey'] : null;
    $tokenExpiresAt = isset($_SESSION['tokenExpiresAt']) ? $_SESSION['tokenExpiresAt'] : null;
    $realmId = isset($_SESSION['realmId']) ? $_SESSION['realmId'] : null;
    
    // Check if we have valid token data
    $hasTokenData = ($accessTokenKey && $refreshTokenKey && $realmId);

    // Authorization flow
    if (!$hasTokenData) {
        // If we don't have token data, check for an authorization code
        if (!isset($_GET['code'])) {
            // No authorization code, start the authorization flow
            try {
                $dataService = QuickBooksOnline\API\DataService\DataService::Configure(array(
                    'auth_mode' => 'oauth2',
                    'ClientID' => $clientID,
                    'ClientSecret' => $clientSecret,
                    'RedirectURI' => $redirectURI,
                    'scope' => $scope,
                    'baseUrl' => $baseURL
                ));
                
                $OAuth2LoginHelper = $dataService->getOAuth2LoginHelper();
                $authorizationURL = $OAuth2LoginHelper->getAuthorizationCodeURL();
                
                // Redirect to QuickBooks authorization page
                header("Location: " . $authorizationURL);
                exit;
            } catch (Exception $e) {
                logError("Failed to start authorization flow", $e->getMessage());
                $errorMessage = "Error starting authorization: " . $e->getMessage();
            }
        } else {
            // We have an authorization code, exchange it for access token
            try {
                $dataService = QuickBooksOnline\API\DataService\DataService::Configure(array(
                    'auth_mode' => 'oauth2',
                    'ClientID' => $clientID,
                    'ClientSecret' => $clientSecret,
                    'RedirectURI' => $redirectURI,
                    'scope' => $scope,
                    'baseUrl' => $baseURL
                ));
                
                $OAuth2LoginHelper = $dataService->getOAuth2LoginHelper();
                $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'];
                
                // Redirect to remove the query parameters
                header("Location: " . $_SERVER['PHP_SELF']);
                exit;
            } catch (Exception $e) {
                logError("Failed to exchange authorization code for token", array(
                    'error' => $e->getMessage(),
                    'code' => $_GET['code']
                ));
                $errorMessage = "Authentication error: " . $e->getMessage();
            }
        }
    } else {
        // We have the token data, check if token is expired
        $tokenExpired = ($tokenExpiresAt && (time() > strtotime($tokenExpiresAt)));
        
        if ($tokenExpired) {
            try {
                // Token expired, try to refresh it
                $dataService = QuickBooksOnline\API\DataService\DataService::Configure(array(
                    'auth_mode' => 'oauth2',
                    'ClientID' => $clientID,
                    'ClientSecret' => $clientSecret,
                    'RedirectURI' => $redirectURI,
                    'scope' => $scope,
                    'baseUrl' => $baseURL,
                    'refreshTokenKey' => $refreshTokenKey
                ));
                
                $OAuth2LoginHelper = $dataService->getOAuth2LoginHelper();
                $refreshedAccessToken = $OAuth2LoginHelper->refreshToken();
                
                // Update the session with new token data
                $_SESSION['accessTokenKey'] = $refreshedAccessToken->getAccessToken();
                $_SESSION['refreshTokenKey'] = $refreshedAccessToken->getRefreshToken();
                $_SESSION['tokenExpiresAt'] = $refreshedAccessToken->getAccessTokenExpiresAt();
                
                // Update our local variables
                $accessTokenKey = $_SESSION['accessTokenKey'];
                $refreshTokenKey = $_SESSION['refreshTokenKey'];
                $tokenExpiresAt = $_SESSION['tokenExpiresAt'];
                
            } catch (Exception $e) {
                logError("Failed to refresh token", $e->getMessage());
                // Clear session and restart auth flow
                session_unset();
                session_destroy();
                header("Location: " . $_SERVER['PHP_SELF']);
                exit;
            }
        }

        try {
            // Configure DataService with the token data
            $dataService = QuickBooksOnline\API\DataService\DataService::Configure(array(
                'auth_mode' => 'oauth2',
                'ClientID' => $clientID,
                'ClientSecret' => $clientSecret,
                'RedirectURI' => $redirectURI,
                'scope' => $scope,
                'baseUrl' => $baseURL,
                'QBORealmID' => $realmId,
                'accessTokenKey' => $accessTokenKey,
                'refreshTokenKey' => $refreshTokenKey
            ));
            
            $dataService->throwExceptionOnError(true);
            
            // First, try a simple query to verify connectivity
            try {
                $companyInfo = $dataService->getCompanyInfo();
                logError("Successfully retrieved company info", array(
                    'company_name' => isset($companyInfo->CompanyName) ? $companyInfo->CompanyName : 'Unknown'
                ));
            } catch (Exception $e) {
                logError("Failed to retrieve company info", $e->getMessage());
                // Don't throw yet, try the account query
            }

            // Get and log detail about the company we're connected to
            try {
                $companyInfo = $dataService->getCompanyInfo();
                logError("Company info", array(
                    'company_name' => isset($companyInfo->CompanyName) ? $companyInfo->CompanyName : 'Unknown',
                    'legal_name' => isset($companyInfo->LegalName) ? $companyInfo->LegalName : 'Unknown',
                    'company_id' => isset($companyInfo->Id) ? $companyInfo->Id : 'Unknown',
                    'realm_id' => $realmId
                ));
                
                // Log details about our connection
                logError("Connection details", array(
                    'baseUrl' => $baseURL,
                    'scope' => $scope,
                    'accessTokenKey' => substr($accessTokenKey, 0, 10) . '...',
                    'refreshTokenKey' => substr($refreshTokenKey, 0, 10) . '...',
                    'tokenExpiresAt' => $tokenExpiresAt
                ));
            } catch (Exception $e) {
                logError("Failed to get company info", $e->getMessage());
            }
            
            // Try a different, very basic query first
            try {
                logError("Attempting a simple query", "Querying for a single account");
                $basicQueryResponse = $dataService->Query("SELECT Id FROM Account MAXRESULTS 1");
                
                if ($basicQueryResponse && !empty($basicQueryResponse)) {
                    logError("Basic query successful", "Found at least one account");
                } else {
                    logError("Basic query returned no results", "Query executed but no accounts found");
                }
            } catch (Exception $e) {
                logError("Basic query failed", $e->getMessage());
            }
            
            // Now try the full account query
            try {
                logError("Attempting full account query", "SELECT * FROM Account");
                $accountQueryResponse = $dataService->Query("SELECT * FROM Account");
                
                // Check for errors after query
                $error = $dataService->getLastError();
                if ($error) {
                    logError("Error querying accounts", $error->getResponseBody());
                    throw new Exception("Error querying accounts: " . $error->getResponseBody());
                }
            } catch (Exception $e) {
                logError("Full account query failed", $e->getMessage());
                throw $e;
            }
            
            // Convert accounts to array for display
            if ($accountQueryResponse && !empty($accountQueryResponse)) {
                foreach ($accountQueryResponse as $account) {
                    $accountsData[] = array(
                        'id' => $account->Id,
                        'name' => $account->Name,
                        'type' => $account->AccountType,
                        'subtype' => isset($account->AccountSubType) ? $account->AccountSubType : '',
                        'current_balance' => isset($account->CurrentBalance) ? $account->CurrentBalance : 0,
                        'active' => $account->Active ? 'Yes' : 'No'
                    );
                }
            }
            // End Account Data
            // Start P&L Data
            
            
            
            // End P&L
        } catch (Exception $e) {
            logError("Error fetching account data", $e->getMessage());
            $errorMessage = "Error fetching account data: " . $e->getMessage();
            
            // If we've had an authentication error, clear the session and restart
            if (strpos($e->getMessage(), 'auth') !== false || 
                strpos($e->getMessage(), 'token') !== false ||
                strpos($e->getMessage(), 'OAuth') !== false) {
                session_unset();
                session_destroy();
                // Add a message to let the user know
                $errorMessage .= " - Restarting authentication...";
                // Redirect after a short delay
                echo "<script>setTimeout(function() { window.location = '" . $_SERVER['PHP_SELF'] . "'; }, 3000);</script>";
            }
        }
    }
} catch (Exception $e) {
    $errorMessage = "Fatal Error: " . $e->getMessage();
    logError("Uncaught exception", $errorMessage);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>QuickBooks Account Information</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            margin: 20px;
        }
        h1 {
            color: #2c3e50;
        }
        .error-container {
            background-color: #f8d7da;
            color: #721c24;
            padding: 15px;
            margin-bottom: 20px;
            border: 1px solid #f5c6cb;
            border-radius: 4px;
        }
        .info-container {
            background-color: #d1ecf1;
            color: #0c5460;
            padding: 15px;
            margin-bottom: 20px;
            border: 1px solid #bee5eb;
            border-radius: 4px;
        }
        table {
            border-collapse: collapse;
            width: 100%;
            margin-top: 20px;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        tr:hover {
            background-color: #f1f1f1;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        .debug-info {
            margin-top: 40px;
            padding: 10px;
            background-color: #f8f9fa;
            border: 1px solid #ddd;
            font-size: 14px;
        }
        .button {
            display: inline-block;
            padding: 8px 16px;
            background-color: #3498db;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>QuickBooks Account Information</h1>
        
        <?php if ($errorMessage): ?>
            <div class="error-container">
                <h3>An error occurred:</h3>
                <p><?php echo htmlspecialchars($errorMessage); ?></p>
            </div>
            <a href="<?php echo $_SERVER['PHP_SELF']; ?>" class="button">Try Again</a>
        <?php endif; ?>
        
        <?php if (empty($accountsData) && !$errorMessage): ?>
            <div class="info-container">
                <h3>Authentication Required</h3>
                <p>You need to authenticate with QuickBooks to view your account data.</p>
                <p>If you're seeing this message and weren't redirected automatically, click the button below:</p>
                <a href="<?php echo $_SERVER['PHP_SELF']; ?>" class="button">Connect to QuickBooks</a>
            </div>
        <?php elseif (!empty($accountsData)): ?>
            <div class="info-container">
                <h3>Successfully connected to QuickBooks!</h3>
                <p>Displaying account information below.</p>
            </div>
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Type</th>
                        <th>Subtype</th>
                        <th>Current Balance</th>
                        <th>Active</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($accountsData as $account): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($account['id']); ?></td>
                            <td><?php echo htmlspecialchars($account['name']); ?></td>
                            <td><?php echo htmlspecialchars($account['type']); ?></td>
                            <td><?php echo htmlspecialchars($account['subtype']); ?></td>
                            <td><?php echo htmlspecialchars(number_format($account['current_balance'], 2)); ?></td>
                            <td><?php echo htmlspecialchars($account['active']); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <p><a href="<?php echo $_SERVER['PHP_SELF']; ?>?logout=1" class="button">Disconnect from QuickBooks</a></p>
        <?php endif; ?>
        
        <!-- Debug Information -->
        <div class="debug-info">
            <h3>Debug Information</h3>
            <p>PHP Version: <?php echo phpversion(); ?></p>
            <p>Server: <?php echo isset($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SOFTWARE'] : 'Unknown'; ?></p>
            <p>Session Status: <?php echo session_status() == PHP_SESSION_ACTIVE ? 'Active' : 'Inactive'; ?></p>
            <?php if (isset($_SESSION['realmId'])): ?>
                <p>Realm ID: <?php echo htmlspecialchars($_SESSION['realmId']); ?></p>
            <?php endif; ?>
            <?php if (isset($_SESSION['accessTokenKey'])): ?>
                <p>Has Access Token: Yes</p>
                <p>Token Expires: <?php echo isset($_SESSION['tokenExpiresAt']) ? htmlspecialchars($_SESSION['tokenExpiresAt']) : 'Unknown'; ?></p>
            <?php else: ?>
                <p>Has Access Token: No</p>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>