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

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

$sales = new Sales($db);    
$data = json_decode(file_get_contents("php://input"));

$sales->df = $data->df;
$sales->dt = $data->dt;
$sales->accounting_view = isset($_SESSION['accounting_view'])?$_SESSION['accounting_view']:"";
$sales->city = $data->city;


$stmt = $sales->SearchCashBookOffice();


$num = $stmt->rowCount();

$arr=array();
$arr["records"] = array();

// if($sales->city=='Main Office'){
//     $arr["balance"] = (int)$sales->SearchOpeningBalanceMainOffice();
// }else{
$arr["balance"] = (int)$sales->SearchOpeningBalanceOffice();
// }


if($num>0){
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row);
        $d=array(
            "date" => $date,
            "expense_reason" => $expense_reason,
            "head" => $head,
			"particular" => $particular,
			"in_amt" => (int)$in_amt,
			"ex_amt" => (int)$ex_amt
        );
        array_push($arr["records"], $d);
    }
}

// if($sales->city=='Main Office'){
//     $stmt1 = $sales->SearchCashBookByReasonMainOffice();
// }else{
    $stmt1 = $sales->SearchCashBookByReasonOffice();
// }

$num1 = $stmt1->rowCount();

$arr["records1"] = array();

if($num1>0){
    while ($row1 = $stmt1->fetch(PDO::FETCH_ASSOC)){
        extract($row1);
        $d1=array(
            "R" => $R,
            "expense_reason" => $S_R,
			"amount" => number_format($p)
        );
        array_push($arr["records1"], $d1);
    }
}

// if($sales->city=='Main Office'){
//     $stmt2 = $sales->SearchCashBookByTypeMainOffice();
// }else{
    $stmt2 = $sales->SearchCashBookByTypeOffice();
// }

$num2 = $stmt2->rowCount();

$arr["records2"] = array();

if($num2>0){
    while ($row2 = $stmt2->fetch(PDO::FETCH_ASSOC)){
        extract($row2);
        $d2=array(
            "R" => $R,
            "expense_reason" => $S_R,
			"amount" => number_format($p)
        );
        array_push($arr["records2"], $d2);
    }
}

echo json_encode($arr);
?>