<?php
require __DIR__ . '/app/bootstrap.php';

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

$user = current_user();
if (!$user) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'unread' => 0, 'notifications' => []], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $query = db()->prepare("SELECT id,title,message,type,link_url,created_at
        FROM notifications
        WHERE (user_id=? OR user_id IS NULL) AND read_at IS NULL
        ORDER BY id DESC LIMIT 20");
    $query->execute([(int)$user['id']]);
    $items = [];
    $maximumId = 0;
    foreach ($query->fetchAll() as $row) {
        $id = (int)$row['id'];
        $maximumId = max($maximumId, $id);
        $items[] = [
            'id' => $id,
            'title' => (string)$row['title'],
            'message' => (string)$row['message'],
            'type' => (string)$row['type'],
            'link' => 'notification_open.php?id=' . $id,
            'created_at' => (string)$row['created_at'],
        ];
    }
    echo json_encode([
        'ok' => true,
        'unread' => count($items),
        'revision' => $maximumId,
        'notifications' => $items,
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $error) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'unread' => 0, 'notifications' => []], JSON_UNESCAPED_UNICODE);
}
