<?php
include_once('shikanisha.kts.php');

if(isset($_POST['seller_name']) && isset($_POST['sale_date'])) {

    // Get the seller name and sale date from the Ajax request
    $seller_name = $_POST['seller_name'];
    $sale_date = $_POST['sale_date'];

    // Format the sale date as YYYY-MM-DD
    $formatted_date = date('Y-m-d', strtotime($sale_date));
 
    // Fetch order details from the database using prepared statements
    $sql = "SELECT 
        tr.seller_name,
        SUM(s.subtotal) AS total_sales_amount,
        s.product_id,
        s.product_name,
        SUM(s.quantity) AS total_products_sold
    FROM sales s
    JOIN transaction_receipts tr ON s.trans_id = tr.trans_id
    WHERE tr.seller_name = ? 
    AND DATE(tr.seller_date) = ?
    GROUP BY tr.seller_name, s.product_id
    ORDER BY s.product_name;";

    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, 'ss', $seller_name, $formatted_date);
    mysqli_stmt_execute($stmt);

    $result = mysqli_stmt_get_result($stmt);

    // Check if there are any results
    if (mysqli_num_rows($result) > 0) {
        // Loop through the results and store them in an array
        while ($row = mysqli_fetch_assoc($result)) {
            $order_details[] = $row;
        }

        // Return the order details as JSON
        echo json_encode($order_details);
    } else {
        // If there are no results, return an error message
        echo json_encode(['error' => 'No order details found']);
    }
} else {
    echo json_encode(['error' => 'Seller name or sale date not provided']);
}
?>
