<?php
/**
 * بحث عالمي - API لـ Ctrl+K
 * يرجع JSON: مرضى، طلبات، فحوصات
 */
header('Content-Type: application/json; charset=utf-8');
$config = require __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../src/Core/Database.php';
require_once __DIR__ . '/../src/Core/Session.php';
require_once __DIR__ . '/../src/Core/Auth.php';
require_once __DIR__ . '/../src/Core/Tenant.php';

\App\Core\Session::start();

$db = \App\Core\Database::getInstance($config['db'])->connection();
\App\Core\Tenant::resolve($db);
$auth = new \App\Core\Auth($db);

$q = trim($_GET['q'] ?? $_GET['term'] ?? '');
$out = ['patients' => [], 'orders' => [], 'tests' => [], 'error' => null];

if (!$auth->check()) {
    $out['error'] = 'يجب تسجيل الدخول';
    echo json_encode($out, JSON_UNESCAPED_UNICODE);
    exit;
}

$tenantId = (int)\App\Core\Tenant::id();

if (strlen($q) < 2) {
    echo json_encode($out, JSON_UNESCAPED_UNICODE);
    exit;
}

$like = '%' . $q . '%';

try {
    $tenantAnd = '';
    try { $db->query('SELECT tenant_id FROM patients LIMIT 1'); $tenantAnd = ' AND tenant_id = ' . $tenantId; } catch (Throwable $e) {}
    $stmt = $db->prepare('SELECT id, patient_code, full_name, phone FROM patients WHERE (full_name LIKE ? OR patient_code LIKE ? OR phone LIKE ?)' . $tenantAnd . ' ORDER BY id DESC LIMIT 8');
    $stmt->execute([$like, $like, $like]);
    $out['patients'] = $stmt->fetchAll();

    $ordAnd = '';
    try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $ordAnd = ' AND o.tenant_id = ' . $tenantId; } catch (Throwable $e) {}
    $stmt = $db->prepare(
        'SELECT o.id, o.order_number, o.order_date, p.full_name AS patient_name
         FROM lab_orders o JOIN patients p ON p.id = o.patient_id
         WHERE (o.order_number LIKE ? OR p.full_name LIKE ?)' . $ordAnd . '
         ORDER BY o.id DESC LIMIT 8'
    );
    $stmt->execute([$like, $like]);
    $out['orders'] = $stmt->fetchAll();

    $testAnd = '';
    try { $db->query('SELECT tenant_id FROM tests LIMIT 1'); $testAnd = ' AND tenant_id = ' . $tenantId; } catch (Throwable $e) {}
    $stmt = $db->prepare('SELECT id, test_code, name FROM tests WHERE (name LIKE ? OR test_code LIKE ?)' . $testAnd . ' ORDER BY name LIMIT 6');
    $stmt->execute([$like, $like]);
    $out['tests'] = $stmt->fetchAll();
} catch (Throwable $e) {
    $out['error'] = $e->getMessage();
}

echo json_encode($out, JSON_UNESCAPED_UNICODE);
