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

// Check for the actual data being posted rather than 'datefilter'
if(isset($_POST['branch'], $_POST['start'], $_POST['end'])){
    $seller_name = $_POST['branch'];
    $start_date = $_POST['start'];
    $end_date = $_POST['end'];
    $start_datetime = date('Y-m-d H:i:s', strtotime($start_date));
    $end_datetime = date('Y-m-d H:i:s', strtotime($end_date));

    // Adjusted SQL query with conditional branch filter
    $sql = "SELECT
        p.product_id,
        p.product_name,
        p.buying_price,
        p.selling_price,
        p.company,
        p.shop_quantity,
        p.store_quantity,
        p.category,
        p.img,
        p.branch,
        p.mfg,
        p.exp,
        p.shelf,
        b.branch_name,
        COALESCE(SUM(s.subtotal), 0) AS total_sales_amount,
        COALESCE(SUM(s.quantity), 0) AS total_products_sold
    FROM products p
    LEFT JOIN sales s ON p.product_id = s.product_id
    LEFT JOIN transaction_receipts tr ON s.trans_id = tr.trans_id
    LEFT JOIN branch b ON p.branch = b.branch_name
    WHERE 
        (? = 'all' OR p.branch = ?)  -- If branch is 'all', don't filter by branch
        AND tr.seller_date BETWEEN ? AND ?
    GROUP BY p.product_id, p.branch
    ORDER BY p.product_name;";

    $stmt = $conn->prepare($sql);
    if ($stmt === false) {
        // Handle error here
        error_log('mysqli prepare() failed: ');
        error_log( print_r( htmlspecialchars($stmt->error), true ) );
        exit('Error: Check your server logs.');
    }

    // Bind parameters based on whether the branch is 'all'
    if ($seller_name === 'all') {
        $stmt->bind_param("ssss", $seller_name, $seller_name, $start_datetime, $end_datetime);
    } else {
        $stmt->bind_param("ssss", $seller_name, $seller_name, $start_datetime, $end_datetime);
    }

    $stmt->execute();
    $result = $stmt->get_result();

    $sales_data = array();
    while($row = $result->fetch_assoc()) {
        $sales_data[] = $row;
    }

    // Now you can echo out the data or handle it as needed
    header('Content-Type: application/json');
    echo json_encode($sales_data);
    $stmt->close();
}
?>
