<?php
// Include your database connection code (shikanisha.kts.php) here
require 'shikanisha.kts.php';

// Check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get start_date and end_date from POST data
    $start_date = date('Y-m-d', strtotime($_POST['start_date']));
    $end_date = date('Y-m-d', strtotime($_POST['end_date']));

    // Prepare SQL query with GROUP BY clause
    $sql = "SELECT productname, price, SUM(quantity) as quantity, SUM(subtotal) as subtotal
            FROM purchase_orders
            WHERE purchase_date BETWEEN ? AND ?
            GROUP BY productname, price";

    // Use prepared statements to avoid SQL injection
    $stmt = $conn->prepare($sql);

    // Check for errors in the prepared statement
    if ($stmt === false) {
        die('Error in preparing the SQL statement');
    }

    // Bind parameters
    $stmt->bind_param("ss", $start_date, $end_date);

    // Execute query
    $stmt->execute();

    // Get result
    $result = $stmt->get_result();

    // Fetch data into an associative array
    $data = array();
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }

    // Close statement and database connection
    $stmt->close();
    $conn->close();

    // Send JSON response
    echo json_encode($data);
} else {
    // If the request method is not POST, return an error or handle accordingly
    echo json_encode(array('error' => 'Invalid request method'));
}
?>
