<?php
include 'connect.php';

    $fromDate = $_GET['from'];
    $toDate = $_GET['to'];
    $deliveryChargeQuery = "SELECT Charge FROM a_deliverycharge";
    $deliveryChargeResult = mysqli_query($con, $deliveryChargeQuery);

    if (!$deliveryChargeResult) {
        printf("Error: %s\n", mysqli_error($con));
        exit();
    }

    // Fetch delivery charge
    $deliveryCharge = mysqli_fetch_assoc($deliveryChargeResult)['Charge'];
    $query = "SELECT *, SUM(OrderPrice) AS total_price,SUM(OrderDelivery) AS order_delivery 
              FROM a_orders 
              WHERE OrderDate BETWEEN '$fromDate' AND '$toDate' 
              GROUP BY OrderID"; 

    $result = mysqli_query($con, $query);
    
    if (!$result) {
        printf("Error: %s\n", mysqli_error($con));
        exit();
    }
    
    $ordersData = [];
    $subtotal = 0;
    $deliveryCharges=0;
    while ($row = mysqli_fetch_assoc($result)) {
        $subtotal += floatval($row['total_price']);
        $deliveryCharges += floatval($row['order_delivery']);
        $ordersData[] = $row;
    }

    // Calculate order count
    $orderCount = count($ordersData);
 //$totalDeliveryCharge = $deliveryCharge * $orderCount;
    // Include subtotal and order count within each order's data
    foreach ($ordersData as &$order) {
        $order['subtotal'] = number_format($subtotal, 2);
         $order['deliveryCharges'] = number_format($deliveryCharges, 2);
        $order['orderCount'] = $orderCount;
         //$order['deliveryCharge'] = number_format($totalDeliveryCharge, 2);
    }
    unset($order); // Unset reference
    echo json_encode($ordersData);


?>