<?php
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");
session_start();
include_once '../config/database.php';
include_once '../objects/sales.php';
date_default_timezone_set('Asia/Rangoon'); 

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

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

$branch_id = $data->branch_id; 
$df = $data->df; // expecting '2024-10' format from the input
$dt = $data->dt; 

$container_category = array();
$container_amount = array();
$totalAmount = 0;

$query = "SELECT account_type,SUM(ifnull(amount,0)) AS tamount FROM (SELECT account_code,SUM(quantity*unit_price) AS amount FROM expense 
WHERE branch_id=:branch_id AND date>=:df and date<=:dt AND SUBSTRING(account_code,1,2) = '7-' GROUP BY account_code) AS a
right JOIN (SELECT * FROM coa where SUBSTRING(account_code,1,2) = '7-') as coa ON a.account_code=coa.account_code GROUP BY account_type";

$stmt = $db->prepare($query);
$stmt->bindParam(':branch_id', $branch_id);
$stmt->bindParam(':df', $df);
$stmt->bindParam(':dt', $dt);
$stmt->execute();

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    extract($row);
    $category_data = array(
        "category" => $account_type,
        "amount" => number_format($tamount,2)
    );

    $totalAmount += $tamount;
    array_push($container_category, $account_type);
    array_push($container_amount, number_format($tamount,2));
}

$response = array(
    "container_category" => $container_category,
    "container_amount" => $container_amount,
    "total_amount" => number_format($totalAmount,2)
);

echo json_encode($response);
?>
