<?php
/**
 * API للتنبيهات - Smart Doctor
 * يُستخدم للـ polling والتحقق من النتائج الحرجة
 */
header('Content-Type: application/json; charset=utf-8');

$config = require dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/src/Core/Database.php';
require_once dirname(__DIR__) . '/src/Core/Session.php';
require_once dirname(__DIR__) . '/src/Core/Csrf.php';
require_once dirname(__DIR__) . '/src/Core/Auth.php';
require_once dirname(__DIR__) . '/src/Core/DoctorAuth.php';
require_once dirname(__DIR__) . '/src/Core/UnifiedAuth.php';
require_once dirname(__DIR__) . '/src/Core/Tenant.php';
\App\Core\Session::start();

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

if (!$doctorAuth->check()) {
    if (!($unifiedAuth->isLoggedIn() && in_array('doctor', $unifiedAuth->availablePortals(), true) && $unifiedAuth->activatePortal('doctor') && $doctorAuth->check())) {
        echo json_encode(['success' => false, 'error' => 'غير مصرح']);
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $host = strtolower((string)($_SERVER['HTTP_HOST'] ?? ''));
    $origin = $_SERVER['HTTP_ORIGIN'] ?? '';
    $referer = $_SERVER['HTTP_REFERER'] ?? '';
    $originHost = strtolower((string)(parse_url($origin, PHP_URL_HOST) ?? ''));
    $refererHost = strtolower((string)(parse_url($referer, PHP_URL_HOST) ?? ''));
    if (($origin !== '' || $referer !== '') && $host !== '' && $originHost !== $host && $refererHost !== $host) {
        http_response_code(403);
        echo json_encode(['success' => false, 'error' => 'طلب غير صالح']);
        exit;
    }
    $csrfToken = $_POST['_csrf'] ?? ($_SERVER['HTTP_X_CSRF_TOKEN'] ?? null);
    if (!is_string($csrfToken) || $csrfToken === '' || !\App\Core\Csrf::isValid($csrfToken)) {
        http_response_code(419);
        echo json_encode(['success' => false, 'error' => 'CSRF']);
        exit;
    }
}

$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) {}
    }
}

echo json_encode([
    'success' => true,
    'critical_count' => $criticalCount,
    'offline' => false
], JSON_UNESCAPED_UNICODE);
