<?php
/**
 * جسر تكامل JSON (أسلوب FHIR Bundle مبسّط) — نفس مصادقة clinic_results
 * GET api/integration_bridge.php?order_number=XXX
 * Header: X-API-Key
 */
header('Content-Type: application/json; charset=utf-8');
header('Vary: Origin');

$config = require __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../src/Core/Database.php';

$db = \App\Core\Database::getInstance($config['db'])->connection();

$apiKey = trim((string)($_SERVER['HTTP_X_API_KEY'] ?? ''));
if ($apiKey === '' && !empty($_SERVER['HTTP_AUTHORIZATION'])) {
    $h = trim((string)$_SERVER['HTTP_AUTHORIZATION']);
    if (stripos($h, 'Bearer ') === 0) {
        $apiKey = trim(substr($h, 7));
    }
}
$orderNumber = trim((string)($_GET['order_number'] ?? ''));
$orderId = (int)($_GET['order_id'] ?? 0);

if ($apiKey === '') {
    http_response_code(400);
    echo json_encode(['resourceType' => 'OperationOutcome', 'issue' => [['severity' => 'error', 'diagnostics' => 'api_key required']]], JSON_UNESCAPED_UNICODE);
    exit;
}

$stmt = $db->prepare('SELECT * FROM clinic_api_keys WHERE api_key = ? AND is_active = 1 LIMIT 1');
$stmt->execute([$apiKey]);
$keyRow = $stmt->fetch();
if (!$keyRow) {
    http_response_code(401);
    echo json_encode(['resourceType' => 'OperationOutcome', 'issue' => [['severity' => 'error', 'diagnostics' => 'invalid key']]], JSON_UNESCAPED_UNICODE);
    exit;
}

$tenantId = (int)($keyRow['tenant_id'] ?? 1);

if ($orderNumber === '' && $orderId <= 0) {
    http_response_code(400);
    echo json_encode(['resourceType' => 'OperationOutcome', 'issue' => [['severity' => 'error', 'diagnostics' => 'order_number or order_id']]], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($orderNumber !== '') {
    $stmt = $db->prepare('SELECT id FROM lab_orders WHERE tenant_id = ? AND order_number = ? LIMIT 1');
    $stmt->execute([$tenantId, $orderNumber]);
} else {
    $stmt = $db->prepare('SELECT id FROM lab_orders WHERE tenant_id = ? AND id = ? LIMIT 1');
    $stmt->execute([$tenantId, $orderId]);
}
$oid = $stmt->fetchColumn();
if (!$oid) {
    http_response_code(404);
    echo json_encode(['resourceType' => 'OperationOutcome', 'issue' => [['severity' => 'error', 'diagnostics' => 'order not found']]], JSON_UNESCAPED_UNICODE);
    exit;
}
$orderId = (int)$oid;

$stmt = $db->prepare(
    'SELECT o.order_number, o.status, o.order_date, p.full_name AS patient_name, p.id AS patient_id
     FROM lab_orders o JOIN patients p ON p.id = o.patient_id WHERE o.id = ? AND o.tenant_id = ?'
);
$stmt->execute([$orderId, $tenantId]);
$order = $stmt->fetch();
if (!$order) {
    http_response_code(404);
    exit;
}

$stmt = $db->prepare(
    'SELECT t.name AS test_name, t.test_code, r.result_value, r.unit, r.flag
     FROM order_items oi
     JOIN tests t ON t.id = oi.test_id
     LEFT JOIN results r ON r.order_item_id = oi.id
     WHERE oi.order_id = ?'
);
$stmt->execute([$orderId]);
$rows = $stmt->fetchAll();

$observations = [];
$n = 0;
foreach ($rows as $r) {
    $n++;
    $observations[] = [
        'resourceType' => 'Observation',
        'id' => 'obs-' . $orderId . '-' . $n,
        'code' => ['text' => $r['test_name'], 'coding' => [['code' => $r['test_code'], 'display' => $r['test_name']]]],
        'valueString' => (string)($r['result_value'] ?? ''),
        'valueQuantity' => isset($r['result_value']) ? ['value' => $r['result_value'], 'unit' => $r['unit']] : null,
        'interpretation' => $r['flag'] ? [['coding' => [['code' => $r['flag']]]]] : [],
    ];
}

echo json_encode([
    'resourceType' => 'Bundle',
    'type' => 'collection',
    'timestamp' => gmdate('c'),
    'entry' => array_map(static fn($o) => ['resource' => $o], $observations),
    'order' => [
        'resourceType' => 'ServiceRequest',
        'id' => (string)$orderId,
        'identifier' => [['value' => $order['order_number']]],
        'status' => $order['status'],
        'subject' => ['display' => $order['patient_name'], 'reference' => 'Patient/' . $order['patient_id']],
    ],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
