<?php
include 'php/db_connection.php';

$search = $_GET['search'] ?? '';

if ($search) {
    $search = "%$search%";
    // নাম দিয়ে সার্চ করলে লেটার অনুযায়ী দেখাবে
    $stmt = $con->prepare("SELECT Product_id, name as Product_name, price, purchase_price,
                          COALESCE(SUM(Quantity), 0) as available_quantity 
                          FROM product 
                          WHERE (name LIKE ? OR Product_id LIKE ?) 
                          AND status != 'cancelled'
                          AND (Expiration_date IS NULL OR Expiration_date = '' OR Expiration_date >= CURDATE())
                          GROUP BY Product_id
                          ORDER BY name ASC
                          LIMIT 15");
    $stmt->bind_param("ss", $search, $search);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $products = [];
    while ($row = $result->fetch_assoc()) {
        $products[] = $row;
    }
    
    echo json_encode($products);
} else {
    echo json_encode([]);
}
?>