<?php
declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/../db.php';

header('Content-Type: application/json; charset=utf-8');

if (empty($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'message' => 'Unauthorized'], JSON_UNESCAPED_UNICODE);
    exit;
}

$pdo = db();
if (!$pdo instanceof PDO) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'message' => 'DB not ready'], JSON_UNESCAPED_UNICODE);
    exit;
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$userId = (int)($_SESSION['user_id'] ?? 0);
$roomId = (int)($_POST['room_id'] ?? 0);

if ($roomId <= 0) {
    echo json_encode(['ok' => false, 'message' => 'room_id required'], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $st = $pdo->prepare("
        UPDATE chat_notifications
        SET is_read = 1
        WHERE employee_id = ?
          AND room_id = ?
          AND is_read = 0
    ");
    $st->execute([$userId, $roomId]);

    echo json_encode(['ok' => true], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode([
        'ok' => false,
        'message' => $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}