<?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/purchase.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_date = array();
$container_purchase = array();
$container_payment = array();
$container_payable = array();
// $totalPurchase = 0;
// $totalSales = 0;

$query = "SELECT sum(IFNULL(purchase,0)-IFNULL(purchase_return,0)) as purchase,sum(IFNULL(payment,0)) as payment,
sum(IFNULL(purchase,0)) - sum(IFNULL(payment,0)) - sum(IFNULL(purchase_return,0)) as payable FROM (
SELECT 0 AS purchase,SUM(amount) AS payment,0 as purchase_return FROM purchase_payment WHERE branch_id = :branch_id
AND date >= :df AND date <= :dt 
UNION ALL
SELECT 0 AS purchase,0 AS payment,SUM(amount) AS purchase_return FROM purchase_return_payment WHERE branch_id = :branch_id
AND date >= :df AND date <= :dt 
) AS a
";

$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(
        // "date" => $date,
        "purchase" => number_format($purchase,2),
        "payment" => number_format( $payment,2),
        "payable" => number_format( $payable,2)
    );

    // $totalPurchase += $purchase;
    // $totalSales += $sales;
    // array_push($container_date, $date);
    array_push($container_purchase, number_format($purchase,2));
    array_push($container_payment, number_format($payment,2));
    array_push($container_payable, number_format($payable,2));
}

$response = array(
    // "container_date" => $container_date,
    "container_purchase" => $container_purchase,
    "container_payment" => $container_payment,
    "container_payable" => $container_payable
    // "totalPurchase" => number_format($totalPurchase),
    // "totalSales" => number_format($totalSales)
);

echo json_encode($response);
?>
