<?php
/**
 * POST /api/lab/ingest_diagnosticos.php
 * Recibe un lote de diagnósticos CIE-10 desde RIPS Manager y los upserta en cie10_diagnosticos.
 * Body: { "rows": [{"cod": "A000", "concepto": "..."}, ...] }
 */

ob_start();
require_once __DIR__ . '/../../config/config.php';

error_reporting(E_ERROR | E_PARSE);
ini_set('display_errors', '0');

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

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

$keyHeader = $_SERVER['HTTP_X_LAB_KEY'] ?? $_SERVER['HTTP_X_LAB_SYNC_KEY'] ?? '';
if (!$keyHeader || !hash_equals(LAB_SYNC_KEY, $keyHeader)) {
    http_response_code(401);
    ob_clean();
    echo json_encode(['ok' => false, 'error' => 'API key inválida']);
    exit;
}

function db(): \PDO {
    return Database::getInstance()->getConnection();
}

$data = json_decode(file_get_contents('php://input'), true);
if (!is_array($data) || empty($data['rows']) || !is_array($data['rows'])) {
    http_response_code(400);
    ob_clean();
    echo json_encode(['ok' => false, 'error' => 'Body inválido: se espera {rows: [...]}']);
    exit;
}

try {
    $pdo = db();
    $stmt = $pdo->prepare(
        "INSERT INTO cie10_diagnosticos (cod_diag, concepto)
         VALUES (?, ?)
         ON DUPLICATE KEY UPDATE concepto = VALUES(concepto)"
    );
    if (!$stmt) {
        $info = $pdo->errorInfo();
        throw new \RuntimeException("Prepare falló [{$info[0]}]: {$info[2]}");
    }

    $insertados = 0;
    foreach ($data['rows'] as $row) {
        $cod      = trim($row['cod']      ?? '');
        $concepto = trim($row['concepto'] ?? '');
        if (!$cod || !$concepto) continue;
        $stmt->execute([$cod, $concepto]);
        $insertados++;
    }

    ob_clean();
    echo json_encode(['ok' => true, 'insertados' => $insertados]);
} catch (\Throwable $e) {
    ob_clean();
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}
