<?php
/**
 * API للعيادات - استلام النتائج برقم الطلب أو المريض
 * نسخة مطورة مع دعم IP whitelist و rate limiting و logging
 * 
 * استدعاء: GET api/clinic_results.php?api_key=XXX&order_number=O12345
 * أو: POST api/clinic_results.php مع JSON body
 */
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

$config = require __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../src/Core/Database.php';
require_once __DIR__ . '/../src/Core/ErrorHandler.php';
require_once __DIR__ . '/../src/Core/Logger.php';
require_once __DIR__ . '/../src/Core/ApiMiddleware.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();
$middleware = new \App\Core\ApiMiddleware($db, $config);
$middleware->handleCors();

$startTime = microtime(true);
$response = ['success' => false, 'error' => '', 'data' => null];
$httpStatus = 200;
$logData = [
    'request_method' => $_SERVER['REQUEST_METHOD'],
    'request_url' => $_SERVER['REQUEST_URI'] ?? '',
    'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '',
    'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? ''
];

// قراءة المعاملات من GET أو POST
$apiKey = '';
$orderNumber = '';
$patientId = 0;
$orderId = 0;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = file_get_contents('php://input');
    $logData['request_params'] = $input;
    $postData = json_decode($input, true);
    if ($postData) {
        $apiKey = trim($postData['api_key'] ?? '');
        $orderNumber = trim($postData['order_number'] ?? '');
        $patientId = !empty($postData['patient_id']) ? (int)$postData['patient_id'] : 0;
        $orderId = !empty($postData['order_id']) ? (int)$postData['order_id'] : 0;
    }
} else {
    $apiKey = trim($_GET['api_key'] ?? '');
    $orderNumber = trim($_GET['order_number'] ?? '');
    $patientId = (int)($_GET['patient_id'] ?? 0);
    $orderId = (int)($_GET['order_id'] ?? 0);
    $logData['request_params'] = http_build_query($_GET);
}

// التحقق من وجود مفتاح API
if ($apiKey === '') {
    \App\Core\ApiResponse::error('api_key مطلوب', 400);
}

try {
    // التحقق من API Key
    $keyRow = $middleware->validateApiKey($apiKey);
    
    if (!$keyRow) {
        \App\Core\ApiResponse::unauthorized('مفتاح API غير صالح');
    }
    
    $apiKeyId = (int)$keyRow['id'];
    $clinicName = $keyRow['clinic_name'];
    $tenantId = (int)($keyRow['tenant_id'] ?? 1);
    $rateLimit = (int)($keyRow['rate_limit_per_hour'] ?? 100);
    
    $logData['api_key_id'] = $apiKeyId;
    $logData['clinic_name'] = $clinicName;
    
    // Rate Limiting
    $clientIp = \App\Core\RateLimiter::getClientIp();
    $check = $middleware->checkRateLimit($clientIp . '_' . $apiKeyId, 'clinic_api');
    if (!$check['allowed']) {
        $middleware->recordApiCall($clientIp . '_' . $apiKeyId, 'clinic_api');
        $logData['error_message'] = 'Rate limit exceeded';
        $logData['response_status'] = 429;
        $middleware->logApiRequest($logData);
        \App\Core\ApiResponse::rateLimitExceeded('تم تجاوز حد الطلبات (' . $rateLimit . ' طلب/ساعة)');
    }
    $middleware->recordApiCall($clientIp . '_' . $apiKeyId, 'clinic_api');
    
    $tenantCond = '';
    try {
        $db->query('SELECT tenant_id FROM lab_orders LIMIT 1');
        $tenantCond = ' AND o.tenant_id = ' . (int)$tenantId;
    } catch (Throwable $e) {}
    
    // جلب البيانات
    if ($orderId > 0 || $orderNumber !== '' || $patientId > 0) {
        $sql = 'SELECT o.id, o.order_number, o.order_date, o.status, o.patient_id, p.full_name AS patient_name, p.phone, d.full_name AS doctor_name, d.clinic_name AS doctor_clinic
                 FROM lab_orders o
                 JOIN patients p ON p.id = o.patient_id
                 LEFT JOIN doctors d ON d.id = o.doctor_id
                 WHERE 1=1' . $tenantCond;
        $params = [];
        
        if ($orderId > 0) {
            $sql .= ' AND o.id = ?';
            $params[] = $orderId;
        } elseif ($orderNumber !== '') {
            $sql .= ' AND o.order_number = ?';
            $params[] = $orderNumber;
        } elseif ($patientId > 0) {
            $sql .= ' AND o.patient_id = ? ORDER BY o.order_date DESC LIMIT 1';
            $params[] = $patientId;
        }
        
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $result = [];
        foreach ($orders as $ord) {
            $stmt = $db->prepare('SELECT t.name AS test_name, r.result_value, r.flag, t.unit, t.reference_range, r.result_date, r.validated_at
                                 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([$ord['id']]);
            $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $result[] = [
                'order' => [
                    'id' => (int)$ord['id'],
                    'order_number' => $ord['order_number'],
                    'order_date' => $ord['order_date'],
                    'status' => $ord['status'],
                    'patient' => [
                        'id' => (int)$ord['patient_id'],
                        'name' => $ord['patient_name'],
                        'phone' => $ord['phone']
                    ],
                    'doctor' => $ord['doctor_name'] ? [
                        'name' => $ord['doctor_name'],
                        'clinic' => $ord['doctor_clinic']
                    ] : null
                ],
                'results' => array_map(function($item) {
                    return [
                        'test_name' => $item['test_name'],
                        'result_value' => $item['result_value'],
                        'unit' => $item['unit'],
                        'reference_range' => $item['reference_range'],
                        'flag' => $item['flag'],
                        'result_date' => $item['result_date'],
                        'validated_at' => $item['validated_at']
                    ];
                }, $items)
            ];
        }
        
        $response['success'] = true;
        $response['data'] = count($result) === 1 ? $result[0] : $result;
        
        // تحديث آخر استخدام وعدد الطلبات
        $middleware->updateApiKeyStats($apiKeyId);
        
    } else {
        \App\Core\ApiResponse::error('حدد order_id أو order_number أو patient_id', 400);
    }
    
} catch (\Throwable $e) {
    $logger->exception($e);
    $logData['error_message'] = $e->getMessage();
    $middleware->handleError($e);
}

// تسجيل الطلب
$executionTime = (int)((microtime(true) - $startTime) * 1000);
$logData['execution_time_ms'] = $executionTime;
$logData['response_status'] = $response['success'] ? 200 : ($httpStatus ?? 500);
$logData['response_data'] = json_encode($response, JSON_UNESCAPED_UNICODE);

$middleware->logApiRequest($logData);

if ($response['success']) {
    \App\Core\ApiResponse::success($response['data']);
} else {
    \App\Core\ApiResponse::error($response['error'], $httpStatus ?? 500);
}
