<?php
// include('include/session.php');
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

include('connection.php');
$dbConnection = new DbConnection();
$connection = $dbConnection->connection;

if(isset($_POST['selectedMonth'])) {
    $selectedMonth = $_POST['selectedMonth'];

    $yearMonth = explode('-', $selectedMonth);
    $year = $yearMonth[0];
    $month = $yearMonth[1];

    $startDate = $year . '-' . $month . '-01';
    $endDate = date('Y-m-t', strtotime($startDate));

    $sql = "SELECT DATE(created_on) as date, category, product, variation, 
            SUM(items) AS total_items, 
            SUM(REPLACE(total_price, 'Rs ', '')) AS total_price 
        FROM order_summery 
        WHERE created_on BETWEEN ? AND ?
        GROUP BY DATE(created_on), category, product, variation";

    $stmt = $connection->prepare($sql);
    $stmt->bind_param('ss', $startDate, $endDate);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $data = array();
        while ($row = $result->fetch_assoc()) {
            $cleanedRow = array(
                'date' => $row['date'],
                'category' => trim(str_replace(',', '', $row['category'])),
                'product' => trim(str_replace(',', '', $row['product'])),
                'variation' => trim(str_replace(',', '', $row['variation'])),
                'total_items' => $row['total_items'],
                'total_price' => $row['total_price']
            );
            $data[] = $cleanedRow;
        }
        header('Content-Type: application/json');
        echo json_encode($data);
    } else {
        echo json_encode(array());
    }
}
?>
