<?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/coa.php';
session_start();

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

$coa = new COA($db);    
$data = json_decode(file_get_contents("php://input"));

$coa->df = $data->df;
$coa->dt = $data->dt;
$coa->type = $data->type;

$stmt = $coa->SearchGeneralLedger();


$num = $stmt->rowCount();

$arr=array();
$arr["records"] = array();
// $arr["records1"] = array();
// $arr["records2"] = array();

// if($coa->type=='all'){
    // $arr["balance"] = (int)$coa->SearchOpeningBalance();
// }else if($coa->type=='main cash'){
//     $arr["balance"] = (int)$coa->SearchOpeningBalanceByMain();
// }else if($coa->type=='petty cash'){
//     $arr["balance"] = (int)$coa->SearchOpeningBalanceByPetty();
// }

$total_debit=$total_credit=0;

if($num>0){
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row);
        $d=array(
            "account_type" => $account_type,
            "account_code" => $account_code,
            "account_head" => $account_head,
			"debit" => (int)$debit,
			"credit" => (int)$credit
        );
        $total_debit += $debit;
        $total_credit += $credit;

        array_push($arr["records"], $d);

        // $compositeKey = $expense_reason . '_' . $head;
        // if (isset($arr["records1"][$compositeKey])) {
        //     $arr["records1"][$compositeKey]["amount"] += $d["in_amt"] + $d["ex_amt"];
        // } else {
        //     $arr["records1"][$compositeKey] = array(
        //         "R" => $expense_reason,
        //         "expense_reason" => $head,
        //         "amount" => $d["in_amt"] + $d["ex_amt"]
        //     );
        // }

        // $compositeKey1 = $expense_reason;
        // if (isset($arr["records2"][$compositeKey1])) {
        //     $arr["records2"][$compositeKey1]["amount"] += $d["in_amt"] + $d["ex_amt"];
        // } else {
        //     $arr["records2"][$compositeKey1] = array(
        //         "R" => $expense_reason,
        //         "expense_reason" => $head,
        //         "amount" => $d["in_amt"] + $d["ex_amt"]
        //     );
        // }

    }
    $arr["total_debit"] = number_format($total_debit);
    $arr["total_credit"] = number_format($total_credit);


}


echo json_encode($arr);
?>