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

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

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

if (isset($_POST['code'])) {
    $code = mysqli_real_escape_string($con, $_POST['code']);
    
    $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.Status,
                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 = '$code' OR i.Barcode = '$code' OR i.ItemSearchName LIKE '%$code%')";
    
    $result = mysqli_query($con, $sql);
    
    if ($result && mysqli_num_rows($result) > 0) {
        $products = [];
        while ($row = mysqli_fetch_assoc($result)) {
            $products[] = $row;
        }
        
        // Check if multiple products found with same barcode
        if (count($products) > 1) {
            // Multiple products found - customer needs to choose
            $response['success'] = true;
            $response['multiple'] = true;
            $response['products'] = $products;
            $response['message'] = 'Multiple products found. Please select one.';
        } else {
            // Single product found
            $product = $products[0];
            
            // For Purchase module, allow all items regardless of stock
            $response['success'] = true;
            $response['product'] = $product;
            
            // Add stock info
            if ($product['CurrentStock'] <= 0) {
                $response['info'] = 'Item is out of stock. Current stock: ' . $product['CurrentStock'];
            } else if ($product['CurrentStock'] <= $product['AlertQuantity']) {
                $response['warning'] = 'Low stock: Only ' . $product['CurrentStock'] . ' units remaining';
            }
        }
    } else {
        $response['message'] = 'Item not found';
    }
}

echo json_encode($response);
?>
