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

$query = trim($_GET['query'] ?? '');
$limit = (int)($_GET['limit'] ?? 30);

try {
    $where = "1=1";
    $params = [];

    if (!empty($query)) {
        $words = explode(' ', $query);
        $conditions = [];
        foreach ($words as $w) {
            if (empty(trim($w))) continue;
            $conditions[] = "(p.NombreComercial LIKE ? OR p.NombreGenerico LIKE ? OR p.laboratorio LIKE ? OR p.CodigoInterno LIKE ? OR p.CodigoBarra LIKE ?)";
            $params[] = "%$w%";
            $params[] = "%$w%";
            $params[] = "%$w%";
            $params[] = "%$w%";
            $params[] = "%$w%";
        }
        if (!empty($conditions)) {
            $where = implode(' AND ', $conditions);
        }
    }

    $sql = "SELECT p.id, p.CodigoInterno, p.CodigoBarra, p.NombreComercial, p.NombreGenerico, 
                   p.laboratorio, p.exento_iva as es_exento_iva,
                   IFNULL(cpp.costo_promedio_unidad_base, 0) as cpp_unidad
            FROM productos p
            LEFT JOIN productos_costo_promedio cpp ON cpp.producto_id = p.id
            WHERE $where
            ORDER BY p.NombreComercial ASC
            LIMIT $limit";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // For each product, get its presentations
    foreach ($products as &$prod) {
        $stmtPres = $pdo->prepare("
            SELECT pp.presentacion_id, pr.nombre as presentacion_nombre, 
                   pp.factor_conversion, pp.precio_venta, NULL as margen_ganancia,
                   ROUND(IFNULL(?, 0) * pp.factor_conversion, 4) as costo_presentacion
            FROM producto_presentaciones pp
            JOIN presentaciones pr ON pr.id = pp.presentacion_id
            WHERE pp.producto_id = ? AND pp.activo = 1
            ORDER BY pp.factor_conversion ASC
        ");
        $stmtPres->execute([$prod['cpp_unidad'], $prod['id']]);
        $prod['presentaciones'] = $stmtPres->fetchAll(PDO::FETCH_ASSOC);
    }
    unset($prod);

    echo json_encode(['success' => true, 'data' => $products]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
