<?php
require_once __DIR__ . '/../../config/config.php';
requireLogin();
header('Content-Type: application/json');

$examenes = isset($_GET['examenes']) ? $_GET['examenes'] : '';
if (empty($examenes)) {
    echo json_encode(['insumos' => []]);
    exit;
}

$db = getDB();
$examenes_ids = explode(',', $examenes);
$examenes_ids = array_filter(array_map('intval', $examenes_ids));

if (empty($examenes_ids)) {
    echo json_encode(['insumos' => []]);
    exit;
}

$placeholders = implode(',', array_fill(0, count($examenes_ids), '?'));

$stmt = $db->prepare("
    SELECT ei.*, i.nombre, i.unidad_medida, i.stock_actual
    FROM examenes_insumos ei
    JOIN insumos i ON ei.insumo_id = i.id
    WHERE ei.examen_id IN ($placeholders)
    ORDER BY i.nombre
");

$stmt->execute($examenes_ids);
$insumos = $stmt->fetchAll();

echo json_encode(['insumos' => $insumos]);
