<?php
// --- Your existing authentication and DataService initialization code goes here ---
// (This includes your session handling, token exchange, and instantiation of $dataService)

// Once you have a valid session with $realmId, $accessTokenKey, etc., continue:

// Include required SDK classes for reporting
require_once('path_to_sdk/Core/ServiceContext.php');
require_once('path_to_sdk/PlatformService/PlatformService.php');
require_once('path_to_sdk/Utility/Configuration/ConfigurationManager.php');

// Set up OAuthRequestValidator (for OAuth2, the access token secret is not used)
$accessToken = $_SESSION['accessTokenKey'];
$accessTokenSecret = ''; // OAuth2 doesn't require an access token secret
$consumerKey = $clientID;       // from your config
$consumerSecret = $clientSecret; // from your config

$requestValidator = new OAuthRequestValidator(
    $accessToken,
    $accessTokenSecret,
    $consumerKey,
    $consumerSecret
);

// Create the ServiceContext object; note we use IntuitServicesType::QBO for QuickBooks Online
$serviceType = IntuitServicesType::QBO;
$serviceContext = new ServiceContext($realmId, $serviceType, $requestValidator);

// Create the ReportService object
$reportService = new ReportService($serviceContext);

// Now, iterate through the months starting January 2023 to the current date,
// execute the Profit & Loss report for each month, and store the data in a JSON file.
$monthlyReports = [];

$startDate = new DateTime('2023-01-01');
$endDate   = new DateTime(); // current date; adjust if you need a different end date

while ($startDate < $endDate) {
    // Define the month start and end dates
    $monthStart = $startDate->format('Y-m-01');
    $monthEnd   = $startDate->format('Y-m-t'); // Last day of the month

    try {
        // Set the report query parameters
        $reportService->setStartDate($monthStart);
        $reportService->setEndDate($monthEnd);
        // Optionally, set the accounting method (e.g., "Accrual")
        // $reportService->setAccountingMethod("Accrual");

        // Execute the Profit and Loss report using the report name constant.
        // (Ensure that ReportName::PROFITANDLOSS is defined in your SDK.)
        $profitAndLossReport = $reportService->executeReport(ReportName::PROFITANDLOSS);
        
        // Convert the report object to an array for easier JSON encoding.
        $reportData = json_decode(json_encode($profitAndLossReport), true);
        
        // Store the report data keyed by the month (e.g., "2023-01")
        $monthlyReports[$startDate->format('Y-m')] = $reportData;
        
        echo "Fetched P&L report for " . $startDate->format('Y-m') . "\n";
    } catch (Exception $e) {
        // Capture any errors for this month
        echo "Error fetching report for " . $startDate->format('Y-m') . ": " . $e->getMessage() . "\n";
        $monthlyReports[$startDate->format('Y-m')] = [
            'error' => $e->getMessage()
        ];
    }
    
    // Move to the first day of the next month
    $startDate->modify('first day of next month');
}

// Save all monthly report data into a JSON file
$fileSaved = file_put_contents('pnl_reports.json', json_encode($monthlyReports, JSON_PRETTY_PRINT));

if ($fileSaved !== false) {
    echo "Reports successfully saved to pnl_reports.json\n";
} else {
    echo "Error saving reports to file.\n";
}
?>
