<?php
session_start();
header('Content-Type: application/json');
include_once('../../includes/config.php');

if (!isset($_SESSION['uid'])) {
    echo json_encode(['success' => false, 'products' => [], 'message' => 'Not authenticated']);
    exit();
}

$response = ['success' => false, 'products' => []];

if (isset($_POST['query'])) {
    $query = mysqli_real_escape_string($con, $_POST['query']);
    
    // If query is empty, show all products (limit more for dropdown)
    $limit = empty($query) ? 50 : 20;
    
    $sql = "SELECT 
                i.ID, 
                i.ItemCode as ProductCode, 
                i.ItemName as ProductName, 
                i.ItemSearchName,
                i.SalesPrice as Rate,
                i.PurchasePrice,
                i.CurrentStock,
                i.AlertQuantity,
                i.MRP,
                i.SalesPrice,
                i.ShopRate,
                i.WholesaleRate,
                i.HSN as HSNCode,
                i.TaxID,
                COALESCE(t.TaxRate, 0) as TaxRate,
                u.UnitName as Unit,
                b.BrandName,
                c.CategoryName
            FROM tblitems i
            LEFT JOIN tblunits u ON i.UnitID = u.ID
            LEFT JOIN tblbrands b ON i.BrandID = b.ID
            LEFT JOIN tblcategories c ON i.CategoryID = c.ID
            LEFT JOIN tbltaxtypes t ON i.TaxID = t.ID
            WHERE i.Status = 'Active' 
            AND (i.ItemCode LIKE '%$query%' 
                 OR i.ItemName LIKE '%$query%' 
                 OR i.ItemSearchName LIKE '%$query%'
                 OR b.BrandName LIKE '%$query%'
                 OR c.CategoryName LIKE '%$query%'
                 OR i.Barcode LIKE '%$query%')
            ORDER BY i.ItemCode ASC
            LIMIT $limit";
    
    $result = mysqli_query($con, $sql);
    
    if ($result && mysqli_num_rows($result) > 0) {
        $products = [];
        while ($row = mysqli_fetch_assoc($result)) {
            // Add stock warning flag
            $row['isLowStock'] = ($row['CurrentStock'] <= $row['AlertQuantity']);
            $products[] = $row;
        }
        $response['success'] = true;
        $response['products'] = $products;
    }
}

echo json_encode($response);
?>
