<?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_date = array();
$container_sales = array();
$container_payment = array();
$container_receivable = array();
// $totalPurchase = 0;
// $totalSales = 0;

$query = "SELECT sum(IFNULL(sales,0)) - sum(IFNULL(sales_return,0)) as sales,sum(IFNULL(payment,0)) as payment,
sum(IFNULL(sales,0)) - sum(IFNULL(sales_return,0)) -sum(IFNULL(payment,0)) as receivable FROM (
SELECT 0 AS sales,SUM(amount) AS payment,0 AS sales_return FROM payment WHERE branch_id = :branch_id
AND date >= :df AND date <= :dt  
UNION ALL
SELECT 0 AS sales,0 AS payment,SUM(amount) AS sales_return FROM sales_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,
        "sales" => number_format($sales,2),
        "payment" => number_format( $payment,2),
        "receivable" => number_format( $receivable,2)
    );

    // $totalPurchase += $purchase;
    // $totalSales += $sales;
    // array_push($container_date, $date);
    array_push($container_sales, number_format($sales,2));
    array_push($container_payment, number_format($payment,2));
    array_push($container_receivable, number_format($receivable,2));
}

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

echo json_encode($response);
?>
