<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../config/db.php';
$pdo = getDBConnection();

$query = trim($_GET['q'] ?? '');

if (strlen($query) < 2) {
    echo json_encode([]);
    exit;
}

try {
    $words = explode(' ', $query);
    $nameConditions = [];
    $params = [];

    foreach ($words as $word) {
        if (empty($word)) continue;
        $nameConditions[] = "(p.NombreComercial LIKE ? OR p.NombreGenerico LIKE ? OR p.laboratorio LIKE ?)";
        $params[] = "%$word%";
        $params[] = "%$word%";
        $params[] = "%$word%";
    }

    $nameSql = implode(' AND ', $nameConditions);

    $sql = "SELECT p.id, p.CodigoInterno, p.CodigoBarra, p.NombreComercial as nombre, 
                   p.laboratorio, p.NombreGenerico,
                   IFNULL(inv.stock_total, 0) as stock_bodega,
                   IFNULL(cpp.costo_promedio_unidad_base, 0) as cpp
            FROM productos p
            LEFT JOIN inventario_sucursal inv ON inv.producto_id = p.id AND inv.sucursal_id = 1
            LEFT JOIN productos_costo_promedio cpp ON cpp.producto_id = p.id
            WHERE (p.CodigoInterno = ? OR p.CodigoBarra = ? OR p.id = ?)
            OR ($nameSql)
            ORDER BY 
                (p.NombreComercial = ?) DESC,
                (p.NombreComercial LIKE ?) DESC,
                (p.NombreComercial LIKE ?) DESC,
                p.NombreComercial ASC
            LIMIT 50";
    
    $orderParams = [$query, "$query%", "%$query%"];
    $finalParams = array_merge([$query, $query, $query], $params, $orderParams);

    $stmt = $pdo->prepare($sql);
    $stmt->execute($finalParams);
    $results = $stmt->fetchAll();

    echo json_encode($results);
} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
?>
