<?php
header('Content-Type: application/json; charset=utf-8');
require_once '../../db_connection.php';

$term = isset($_GET['term']) ? trim($_GET['term']) : '';
$sucursal_id = isset($_GET['sucursal_id']) ? (int)$_GET['sucursal_id'] : 0;

if (empty($term) || $sucursal_id === 0) {
    echo json_encode([]);
    exit;
}

$likeTerm = "%{$term}%";

// Esta consulta busca productos y lotes con stock en la sucursal de origen
$sql = "SELECT 
            p.id as producto_id,
            p.NombreComercial,
            l.id as lote_id,
            l.codigo_lote,
            i.stock_unidad_base
        FROM productos p
        JOIN lote l ON p.id = l.producto_id
        JOIN inventario i ON l.id = i.lote_id
        WHERE i.sucursal_id = ? 
          AND i.stock_unidad_base > 0
          AND (
              p.NombreComercial LIKE ? OR 
              p.CodigoInterno LIKE ? OR 
              p.CodigoBarra LIKE ? OR
              l.codigo_lote LIKE ?
          )
        LIMIT 10";

$stmt = $conn->prepare($sql);
$stmt->bind_param("issss", $sucursal_id, $likeTerm, $likeTerm, $likeTerm, $likeTerm);
$stmt->execute();
$result = $stmt->get_result();

$products = [];
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $products[] = $row;
    }
}

$stmt->close();
$conn->close();

echo json_encode($products);
?>
