<?php
/**
 * بحث عالمي - API لـ Ctrl+K
 * يرجع JSON: مرضى، طلبات، فحوصات
 */
$config = require __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../src/Core/Database.php';
require_once __DIR__ . '/../src/Core/Auth.php';
require_once __DIR__ . '/../src/Core/Tenant.php';
require_once __DIR__ . '/../src/Core/ErrorHandler.php';
require_once __DIR__ . '/../src/Core/Logger.php';
require_once __DIR__ . '/../src/Core/RateLimiter.php';
require_once __DIR__ . '/../src/Core/ApiResponse.php';
require_once __DIR__ . '/../src/Core/SecurityHeaders.php';

// تعريف DEBUG_MODE
define('DEBUG_MODE', $config['debug'] ?? false);

// تهيئة Logger و Error Handler
$logger = new \App\Core\Logger(__DIR__ . '/../logs/app.log');
\App\Core\ErrorHandler::register($logger);

// إضافة Security Headers للـ API
\App\Core\SecurityHeaders::setForApi();

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

if (session_status() === PHP_SESSION_NONE) {
    $sessionConfig = $config['session'] ?? [];
    ini_set('session.cookie_httponly', $sessionConfig['cookie_httponly'] ?? 1);
    ini_set('session.cookie_secure', ($sessionConfig['cookie_secure'] ?? true) && isset($_SERVER['HTTPS']) ? 1 : 0);
    ini_set('session.cookie_samesite', $sessionConfig['cookie_samesite'] ?? 'Strict');
    session_start();
}

$auth = new \App\Core\Auth($db);

if (!$auth->check()) {
    \App\Core\ApiResponse::unauthorized('يجب تسجيل الدخول');
}

// Rate Limiting
$rateLimiter = new \App\Core\RateLimiter($db);
$clientIp = \App\Core\RateLimiter::getClientIp();
$rateLimitConfig = $config['rate_limiting'] ?? [];
$check = $rateLimiter->check(
    $clientIp . '_' . ($auth->userId() ?? 0),
    'search',
    $rateLimitConfig['search_max_attempts'] ?? 30,
    $rateLimitConfig['search_window_seconds'] ?? 60
);

if (!$check['allowed']) {
    $rateLimiter->record($clientIp . '_' . ($auth->userId() ?? 0), 'search', $rateLimitConfig['search_window_seconds'] ?? 60);
    \App\Core\ApiResponse::rateLimitExceeded('تم تجاوز حد البحث');
}

$rateLimiter->record($clientIp . '_' . ($auth->userId() ?? 0), 'search', $rateLimitConfig['search_window_seconds'] ?? 60);

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

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

if (strlen($q) < 2) {
    \App\Core\ApiResponse::success($out);
}

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

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

    $hasTenantOrd = false;
    try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $hasTenantOrd = true; } catch (Throwable $e) {}
    
    if ($hasTenantOrd) {
        $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 ?) AND o.tenant_id = ?
             ORDER BY o.id DESC LIMIT 8'
        );
        $stmt->execute([$like, $like, $tenantId]);
    } else {
        $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 ?)
             ORDER BY o.id DESC LIMIT 8'
        );
        $stmt->execute([$like, $like]);
    }
    $out['orders'] = $stmt->fetchAll();

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

\App\Core\ApiResponse::success($out);
