<?php
/**
 * POST /api/lab/link_ordenes_domicilio.php
 * Vincula múltiples órdenes médicas a un domicilio (domicilio_id).
 * Body JSON: { domicilio_id: int, orden_ids: int[] }
 */
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../classes/Database.php';

header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');

requireAuthentication();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Método no permitido']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
if (empty($input['domicilio_id']) || empty($input['orden_ids']) || !is_array($input['orden_ids'])) {
    echo json_encode(['success' => false, 'error' => 'domicilio_id y orden_ids[] requeridos']);
    exit;
}

$domicilioId = (int)$input['domicilio_id'];
$ordenIds    = array_map('intval', $input['orden_ids']);
$ordenIds    = array_filter($ordenIds, fn($v) => $v > 0);

if (!$domicilioId || empty($ordenIds)) {
    echo json_encode(['success' => false, 'error' => 'Valores inválidos']);
    exit;
}

try {
    $db          = Database::getInstance();
    $placeholders = implode(',', array_fill(0, count($ordenIds), '?'));
    $params       = array_merge([$domicilioId], array_values($ordenIds));

    $db->execute(
        "UPDATE lab_ordenes_medicas SET domicilio_id = ? WHERE id IN ($placeholders)",
        $params
    );

    echo json_encode(['success' => true, 'vinculadas' => count($ordenIds)]);
} catch (Exception $e) {
    error_log('[link_ordenes_domicilio] ' . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Error interno']);
}
