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

session_start();
$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';

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

if (!$doctorAuth->check()) {
    echo json_encode(['success' => false, 'error' => 'غير مصرح']);
    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);
