<?php
/**
 * API للتنبيهات - Smart Doctor
 * يُستخدم للـ polling والتحقق من النتائج الحرجة
 */
$config = require dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/src/Core/Database.php';
require_once dirname(__DIR__) . '/src/Core/DoctorAuth.php';
require_once dirname(__DIR__) . '/src/Core/Tenant.php';
require_once dirname(__DIR__) . '/src/Core/ErrorHandler.php';
require_once dirname(__DIR__) . '/src/Core/Logger.php';
require_once dirname(__DIR__) . '/src/Core/RateLimiter.php';
require_once dirname(__DIR__) . '/src/Core/ApiResponse.php';
require_once dirname(__DIR__) . '/src/Core/SecurityHeaders.php';

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

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

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

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();
}

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

if (!$doctorAuth->check()) {
    \App\Core\ApiResponse::unauthorized('غير مصرح');
}

// Rate Limiting
$rateLimiter = new \App\Core\RateLimiter($db);
$clientIp = \App\Core\RateLimiter::getClientIp();
$accountId = $doctorAuth->accountId();
$rateLimitConfig = $config['rate_limiting'] ?? [];
$check = $rateLimiter->check(
    $clientIp . '_' . $accountId,
    'doctor_notifications',
    $rateLimitConfig['api_max_attempts'] ?? 100,
    $rateLimitConfig['api_window_seconds'] ?? 3600
);

if (!$check['allowed']) {
    $rateLimiter->record($clientIp . '_' . $accountId, 'doctor_notifications', $rateLimitConfig['api_window_seconds'] ?? 3600);
    \App\Core\ApiResponse::rateLimitExceeded();
}

$rateLimiter->record($clientIp . '_' . $accountId, 'doctor_notifications', $rateLimitConfig['api_window_seconds'] ?? 3600);

$doctorId = $doctorAuth->doctorId();
$tenantId = $doctorAuth->tenantId();
\App\Core\Tenant::setId($tenantId);

$tenantCond = ' AND o.tenant_id = ' . (int)$tenantId;
$doctorCond = ' AND o.doctor_id = ' . (int)$doctorId;

$criticalCount = 0;
try {
    $stmt = $db->prepare("SELECT COUNT(*) FROM results r 
        JOIN order_items oi ON oi.id = r.order_item_id 
        JOIN lab_orders o ON o.id = oi.order_id 
        WHERE r.flag = 'C' AND r.flag IS NOT NULL $tenantCond $doctorCond");
    $stmt->execute();
    $criticalCount = (int)$stmt->fetchColumn();
} catch (Throwable $e) {}

// حفظ اشتراك Push إذا أُرسل
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['push_subscription'])) {
    $sub = $_POST['push_subscription'];
    if (is_string($sub)) $sub = json_decode($sub, true);
    if (is_array($sub) && !empty($sub['endpoint'])) {
        try {
            $db->exec("CREATE TABLE IF NOT EXISTS doctor_push_subscriptions (
                id INT AUTO_INCREMENT PRIMARY KEY,
                doctor_account_id INT NOT NULL,
                endpoint TEXT NOT NULL,
                p256dh VARCHAR(255) NULL,
                auth VARCHAR(255) NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                UNIQUE KEY uk_endpoint (doctor_account_id, endpoint(255))
            )");
            $stmt = $db->prepare('INSERT INTO doctor_push_subscriptions (doctor_account_id, endpoint, p256dh, auth) VALUES (?, ?, ?, ?) 
                ON DUPLICATE KEY UPDATE p256dh=VALUES(p256dh), auth=VALUES(auth)');
            $keys = $sub['keys'] ?? [];
            $stmt->execute([
                $doctorAuth->accountId(),
                $sub['endpoint'],
                $keys['p256dh'] ?? null,
                $keys['auth'] ?? null
            ]);
        } catch (\Throwable $e) {
            $logger->error('Push subscription error', ['error' => $e->getMessage()]);
        }
    }
}

\App\Core\ApiResponse::success([
    'critical_count' => $criticalCount,
    'offline' => false
]);
