<?php

require_once 'includes/dbconn.php';

// Initialize arrays to hold debit and credit totals for each account
$accountDebits = [];
$accountCredits = [];

// Fetch all accounts
$sqlAccounts = "SELECT account_id, account_name FROM chart_of_accounts";
$resultAccounts = $conn->query($sqlAccounts);

while ($rowAccount = $resultAccounts->fetch_assoc()) {
    $accountId = $rowAccount['account_id'];
    $accountName = $rowAccount['account_name'];

    // Fetch debits for this account
    $sqlDebit = "SELECT COALESCE(SUM(amount), 0) AS total_debit FROM transactions WHERE account_id = $accountId AND type = 'Debit'";
    $resultDebit = $conn->query($sqlDebit);
    $rowDebit = $resultDebit->fetch_assoc();

    // Fetch credits for this account
    $sqlCredit = "SELECT COALESCE(SUM(amount), 0) AS total_credit FROM transactions WHERE account_id = $accountId AND type = 'Credit'";
    $resultCredit = $conn->query($sqlCredit);
    $rowCredit = $resultCredit->fetch_assoc();

    // Store in arrays
    $accountDebits[$accountName] = $rowDebit['total_debit'];
    $accountCredits[$accountName] = $rowCredit['total_credit'];
}

// Prepare the data
$data = array(
    'accountDebits' => $accountDebits,
    'accountCredits' => $accountCredits
);

// Output JSON response
header('Content-Type: application/json');
echo json_encode($data);

$conn->close();
?>