<?php
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

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

require_once __DIR__ . '/db.php';

if (empty($_SESSION['user_id'])) {
    echo json_encode(['ok' => false, 'msg' => 'session expired']);
    exit;
}

if (!function_exists('db')) {
    echo json_encode(['ok' => false, 'msg' => 'db function missing']);
    exit;
}

try {
    $pdo = db();
    if (!$pdo instanceof PDO) {
        echo json_encode(['ok' => false, 'msg' => 'db not ready']);
        exit;
    }

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

    $employeeId = (int)($_SESSION['user_id'] ?? 0);
    $messageId  = (int)($_POST['message_id'] ?? 0);

    if ($employeeId <= 0 || $messageId <= 0) {
        echo json_encode(['ok' => false, 'msg' => 'invalid data']);
        exit;
    }

    $st = $pdo->prepare("
        INSERT IGNORE INTO owner_popup_message_reads (message_id, employee_id)
        VALUES (?, ?)
    ");
    $st->execute([$messageId, $employeeId]);

    echo json_encode(['ok' => true]);
} catch (Throwable $e) {
    echo json_encode(['ok' => false, 'msg' => 'server error']);
}