<?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';
date_default_timezone_set('Asia/Bangkok');
session_start();
$database = new Database();
$db = $database->getConnection();
 
$other_service_charges = new OtherServiceCharges($db);
$data = json_decode(file_get_contents("php://input"));

$other_service_charges->df = $data->df;
$other_service_charges->dt = $data->dt;

$opbalance = 0;

$stmt = $other_service_charges->searchCashIn();
$num = $stmt->rowCount();

$arr = array();
$arr["records_in"] = array();
$arr["records_out"] = array();
$cash_in_total = 0;

if ($num > 0) {
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        extract($row);
        $CI = array(
            "description" => ($description) ? $description : "",
            "cash_in" => is_numeric($p) ? number_format((float)$p, 2, '.', '') : "",
        );
        $cash_in_total += $p;
        array_push($arr["records_in"], $CI);
    }
}

$cash_in_total = number_format($cash_in_total, 2, '.', '');

$stmt = $other_service_charges->searchCashOut();
$num = $stmt->rowCount();
$cash_out_total = 0;

if ($num > 0) {
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        extract($row);
        $CO = array(
            "description" => ($description) ? $description : "",
            "cash_out" => is_numeric($p) ? number_format((float)$p, 2, '.', '') : "",
        );
        $cash_out_total += $p;
        array_push($arr["records_out"], $CO);
    }
}

$cash_out_total = number_format($cash_out_total + $opbalance, 2, '.', '');
$cash_balance = number_format($cash_in_total - $cash_out_total - $opbalance, 2, '.', '');
$opening_balance = number_format($opbalance, 2, '.', '');

$arr["cash_in_total"] = $cash_in_total;
$arr["cash_out_total"] = $cash_out_total;
$arr["cash_balance"] = $cash_balance;
$arr["opening_balance"] = $opening_balance;

echo json_encode($arr);
?>
