<?php
// Required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

include_once '../config/database.php';  
include_once '../objects/other_service_charges.php';

session_start();

// Initialize database connection
$database = new Database();
$db = $database->getConnection();

// Initialize object
$other_service_charges = new OtherServiceCharges($db);

// Get input data
$data = json_decode(file_get_contents("php://input"));

$other_service_charges->df = $data->df ?? null;
$other_service_charges->dt = $data->dt ?? null;
$other_service_charges->type = $data->type ?? null;

// Fetch data
$stmt = $other_service_charges->SearchCashBookOffice();
$num = $stmt->rowCount();

// Initialize response arrays
$arr = [
    "records" => [],
    "records1" => [],
    "records2" => [],
];

// Get opening balance based on type
if ($other_service_charges->type == 'all') {
    $arr["balance"] = bcdiv($other_service_charges->SearchOpeningBalance(), 1, 2);
} elseif ($other_service_charges->type == 'main cash') {
    $arr["balance"] = bcdiv($other_service_charges->SearchOpeningBalanceByMain(), 1, 2);
} elseif ($other_service_charges->type == 'petty cash') {
    $arr["balance"] = bcdiv($other_service_charges->SearchOpeningBalanceByPetty(), 1, 2);
} elseif ($other_service_charges->type == 'transfer') {
    $arr["balance"] = bcdiv($other_service_charges->SearchOpeningBalanceByTransfer(), 1, 2);
}

// Process data if rows exist
if ($num > 0) {
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        extract($row);

        // Record data
        $d = [
            "date" => $date,
            "toe" => ($toe)?$toe:"",
            "account_head" => ($account_head)?$account_head:"",
            "head" => ($head)?$head:"",
            "particular" => ($particular)?$particular:"",
            "in_amt" => (float)$in_amt,
            "ex_amt" => (float)$ex_amt,
        ];
        $arr["records"][] = $d;

        // Aggregate data for records1
        $compositeKey = $account_head . '_' . $head;
        if (isset($arr["records1"][$compositeKey])) {
            $arr["records1"][$compositeKey]["amount"] += $d["in_amt"] + $d["ex_amt"];
        } else {
            $arr["records1"][$compositeKey] = [
                "R" => $account_head,
                "account_head" => $head,
                "amount" => $d["in_amt"] + $d["ex_amt"], // No formatting here for calculations
            ];
        }

        // Aggregate data for records2
        $compositeKey1 = $account_head;
        if (isset($arr["records2"][$compositeKey1])) {
            $arr["records2"][$compositeKey1]["amount"] += $d["in_amt"] + $d["ex_amt"];
        } else {
            $arr["records2"][$compositeKey1] = [
                "R" => $account_head,
                "account_head" => $head,
                "amount" => $d["in_amt"] + $d["ex_amt"], // No formatting here for calculations
            ];
        }
    }

    // Format amounts in `records1` and `records2` after aggregation
    foreach ($arr["records1"] as &$record) {
        $record["amount"] = ($record["amount"]);
    }

    foreach ($arr["records2"] as &$record) {
        $record["amount"] = ($record["amount"]);
    }
}

// Output response
echo json_encode($arr);
?>
