<?php
// pnl_report.php
require_once 'config.php'; // Assumes DATA_DIR is defined

header('Content-Type: application/json');

$month = isset($_GET['month']) ? $_GET['month'] : date('Y-m', strtotime('first day of last month'));
$transactionFile = DATA_DIR . '/transactions_curl_' . $month . '.json';

if (!file_exists($transactionFile)) {
    echo json_encode(['error' => "Transaction file for month {$month} not found."]);
    exit;
}

$transactionsData = json_decode(file_get_contents($transactionFile), true);
if (!$transactionsData) {
    echo json_encode(['error' => "Error decoding transaction data for {$month}."]);
    exit;
}

$report = [
    'summary'   => [],
    'netProfit' => 0
];

// We will build a hierarchy (associative array) keyed by account names.
$hierarchy = [];

/**
 * Recursively adds an amount and transaction detail into a node.
 *
 * @param array &$node The current node in the hierarchy.
 * @param array $levels Remaining levels of account names.
 * @param float $amount The line amount.
 * @param array $txnDetail Transaction detail (e.g. date and amount).
 */
function addToHierarchy(&$node, $levels, $amount, $txnDetail) {
    if (empty($levels)) {
        if (!isset($node['total'])) {
            $node['total'] = 0;
        }
        $node['total'] += $amount;
        if (!isset($node['transactions'])) {
            $node['transactions'] = [];
        }
        $node['transactions'][] = $txnDetail;
    } else {
        $currentLevel = array_shift($levels);
        if (!isset($node['subaccounts'])) {
            $node['subaccounts'] = [];
        }
        if (!isset($node['subaccounts'][$currentLevel])) {
            $node['subaccounts'][$currentLevel] = [
                'account'     => $currentLevel,
                'total'       => 0,
                'subaccounts' => []
            ];
        }
        $node['total'] = (isset($node['total']) ? $node['total'] : 0) + $amount;
        addToHierarchy($node['subaccounts'][$currentLevel], $levels, $amount, $txnDetail);
    }
}

$totalRevenue = 0;
$totalExpenses = 0;

// Loop through each transaction.
foreach ($transactionsData as $txn) {
    if (!isset($txn['Line']) || !is_array($txn['Line'])) continue;
    $txnDate = $txn['TxnDate'] ?? '';
    foreach ($txn['Line'] as $line) {
        if (!isset($line['DetailType'])) continue;

        $amount = floatval($line['Amount'] ?? 0);
        $txnDetail = [
            'date'   => $txnDate,
            'amount' => $amount
        ];
        $accountFullName = '';

        // Check for Sales (Income) lines.
        if ($line['DetailType'] === 'SalesItemLineDetail') {
            if (!isset($line['SalesItemLineDetail']['ItemAccountRef']['name'])) {
                continue;
            }
            $accountFullName = $line['SalesItemLineDetail']['ItemAccountRef']['name'];
            $totalRevenue += $amount;
        }
        // Check for Expense/Purchase lines.
        elseif ($line['DetailType'] === 'AccountBasedExpenseLineDetail' || $line['DetailType'] === 'PurchaseLineDetail') {
            // Adjust the path based on your data structure.
            if (!isset($line['AccountBasedExpenseLineDetail']['AccountRef']['name']) &&
                !isset($line['PurchaseLineDetail']['AccountRef']['name'])) {
                continue;
            }
            $accountFullName = isset($line['AccountBasedExpenseLineDetail']['AccountRef']['name']) ?
                $line['AccountBasedExpenseLineDetail']['AccountRef']['name'] :
                $line['PurchaseLineDetail']['AccountRef']['name'];
            $totalExpenses += $amount;
        } else {
            // If you have other detail types you want to capture, handle them here.
            continue;
        }

        // Split the account name by colon to create a hierarchy.
        $levels = array_map('trim', explode(':', $accountFullName));
        if (empty($levels)) continue;
        $topLevel = $levels[0];
        if (!isset($hierarchy[$topLevel])) {
            $hierarchy[$topLevel] = [
                'account'     => $topLevel,
                'total'       => 0,
                'subaccounts' => []
            ];
        }
        addToHierarchy($hierarchy[$topLevel], array_slice($levels, 1), $amount, $txnDetail);

        // For net profit, assume sales are positive and expenses are negative.
        // (If your expense amounts are positive in your dataset, you might need to subtract them.)
    }
}

$report['netProfit'] = $totalRevenue - $totalExpenses;

function hierarchyToArray($node) {
    $result = $node;
    if (isset($node['subaccounts'])) {
        $result['subaccounts'] = [];
        foreach ($node['subaccounts'] as $sub) {
            $result['subaccounts'][] = hierarchyToArray($sub);
        }
    }
    return $result;
}

$report['summary'] = [];
foreach ($hierarchy as $topAccount) {
    $report['summary'][] = hierarchyToArray($topAccount);
}

usort($report['summary'], function($a, $b) {
    return $b['total'] <=> $a['total'];
});

echo json_encode($report, JSON_PRETTY_PRINT);
exit;
?>
