<?php
/**
 * Search Product by Barcode/QR Code API
 * Handles product search for scanner integration
 */

session_start();
include_once('../../includes/config.php');

// Set JSON header
header('Content-Type: application/json');

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    echo json_encode([
        'success' => false,
        'message' => 'User not authenticated'
    ]);
    exit();
}

// Get search code
$code = isset($_POST['code']) ? trim($_POST['code']) : '';
$salesType = isset($_POST['salesType']) ? trim($_POST['salesType']) : 'GST';

if (empty($code)) {
    echo json_encode([
        'success' => false,
        'message' => 'Code is required'
    ]);
    exit();
}

try {
    // Escape code for SQL
    $code = mysqli_real_escape_string($con, $code);
    
    // Search product by barcode or product code
    // Search in multiple fields for better matches
    $query = "SELECT 
                i.ID as id,
                i.ItemCode as code,
                i.Barcode as barcode,
                i.ItemName as name,
                i.ItemSearchName,
                c.CategoryName as category,
                b.BrandName as subcategory,
                u.UnitName as unit,
                i.SalesPrice as selling_price,
                i.MRP as mrp,
                i.WholesaleRate as wholesale_price,
                i.ShopRate as shop_rate,
                i.PurchasePrice as purchase_price,
                i.CurrentStock as stock,
                COALESCE(t.TaxRate, 0) as tax,
                i.HSN as hsn,
                i.ItemImage as image
              FROM tblitems i
              LEFT JOIN tblcategories c ON i.CategoryID = c.ID
              LEFT JOIN tblbrands b ON i.BrandID = b.ID
              LEFT JOIN tblunits u ON i.UnitID = u.ID
              LEFT JOIN tbltaxtypes t ON i.TaxID = t.ID
              WHERE (i.Barcode = '$code' 
                     OR i.ItemCode = '$code'
                     OR i.ItemSearchName LIKE '%$code%')
              AND i.Status = 'Active'
              ORDER BY i.ID DESC";
    
    $result = mysqli_query($con, $query);
    
    if (!$result) {
        throw new Exception('Database query failed: ' . mysqli_error($con));
    }
    
    $products = [];
    while ($row = mysqli_fetch_assoc($result)) {
        // Determine price based on sales type
        $price = $row['selling_price'];
        
        if ($salesType === 'WHOLESALE') {
            $price = $row['wholesale_price'] > 0 ? $row['wholesale_price'] : $row['selling_price'];
        } elseif ($salesType === 'MRP') {
            $price = $row['mrp'] > 0 ? $row['mrp'] : $row['selling_price'];
        } elseif ($salesType === 'SHOP') {
            $price = $row['shop_rate'] > 0 ? $row['shop_rate'] : $row['selling_price'];
        }
        
        $products[] = [
            'id' => $row['id'],
            'code' => $row['code'],
            'barcode' => $row['barcode'],
            'name' => $row['name'],
            'category' => $row['category'],
            'subcategory' => $row['subcategory'],
            'unit' => $row['unit'],
            'price' => $price,
            'selling_price' => $row['selling_price'],
            'mrp' => $row['mrp'],
            'wholesale_price' => $row['wholesale_price'],
            'shop_rate' => $row['shop_rate'],
            'purchase_price' => $row['purchase_price'],
            'stock' => $row['stock'],
            'tax' => $row['tax'],
            'hsn' => $row['hsn'],
            'image' => $row['image']
        ];
    }
    
    if (count($products) === 0) {
        // No products found
        echo json_encode([
            'success' => false,
            'message' => 'Product not found with code: ' . $code
        ]);
        exit();
    }
    
    if (count($products) === 1) {
        // Single product found
        echo json_encode([
            'success' => true,
            'product' => $products[0],
            'message' => 'Product found'
        ]);
    } else {
        // Multiple products found
        echo json_encode([
            'success' => true,
            'multiple' => true,
            'products' => $products,
            'message' => 'Multiple products found'
        ]);
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>
