<?php
include('include/session.php');
include('connection.php');
$dbConnection = new DbConnection();
$connection = $dbConnection->connection;
if(isset($_POST['selectedYear'])) {
    
    $selectedYear = mysqli_real_escape_string($connection, $_POST['selectedYear']);

    // Adjusted query to fetch data based on the year part of the date
    $query = "SELECT category, product, variation, SUM(items) AS total_items, SUM(REPLACE(total_price, 'Rs ', '')) AS total_price 
              FROM order_summery 
              WHERE YEAR(created_on) = '$selectedYear'
              GROUP BY category, product, variation";

    $result = mysqli_query($connection, $query);

    if(mysqli_num_rows($result) > 0) {
        
        $data = array();

        while($row = mysqli_fetch_assoc($result)) {
            // Clean up data before adding it to the array
            $cleanedRow = array(
                '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;
        }

        // Sending JSON response
        echo json_encode($data);
    } else {
        // Sending JSON response if no data found for the selected year
        echo json_encode(array());
    }
} else {
    // Sending JSON response if no year is selected
    echo json_encode(array('error' => 'No year selected'));
}

// Close the database connection
mysqli_close($connection);
?>
