<?php
declare(strict_types=1);

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

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

$uid = isset($_SESSION['mocker_user_id']) ? (int) $_SESSION['mocker_user_id'] : 0;
if ($uid <= 0) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'auth'], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $pdo = mocker_db();
} catch (Throwable $e) {
    http_response_code(503);
    echo json_encode(['ok' => false, 'error' => 'db'], JSON_UNESCAPED_UNICODE);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

if ($method === 'GET') {
    $limit = 50;
  $st = $pdo->prepare(
        'SELECT n.id, n.title, n.body, n.link_url, n.created_at,
                CASE WHEN r.read_at IS NULL THEN 0 ELSE 1 END AS is_read
         FROM site_notifications n
         LEFT JOIN user_notification_reads r
           ON r.notification_id = n.id AND r.user_id = :uid
         WHERE n.is_published = 1
         ORDER BY n.created_at DESC, n.id DESC
         LIMIT ' . (int) $limit
    );
    $st->execute([':uid' => $uid]);
    $items = [];
    $unreadCount = 0;
    foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $read = (int) $row['is_read'] === 1;
        if (!$read) {
            $unreadCount++;
        }
        $items[] = mocker_notification_row_to_public($row, $read);
    }

    echo json_encode(
        [
            'ok' => true,
            'items' => $items,
            'unreadCount' => $unreadCount,
        ],
        JSON_UNESCAPED_UNICODE
    );
    exit;
}

if ($method !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method'], JSON_UNESCAPED_UNICODE);
    exit;
}

mocker_require_csrf_post();

$input = json_decode((string) file_get_contents('php://input'), true) ?: [];
$action = (string) ($input['action'] ?? '');

if ($action === 'mark_read') {
    $now = time();
    $ids = $input['ids'] ?? null;
    if (!empty($input['markAll'])) {
        $st = $pdo->prepare(
            'INSERT OR IGNORE INTO user_notification_reads (user_id, notification_id, read_at)
             SELECT :uid, n.id, :t
             FROM site_notifications n
             WHERE n.is_published = 1'
        );
        $st->execute([':uid' => $uid, ':t' => $now]);
        echo json_encode(['ok' => true], JSON_UNESCAPED_UNICODE);
        exit;
    }
    if (!is_array($ids) || $ids === []) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'ids'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $ins = $pdo->prepare(
        'INSERT OR IGNORE INTO user_notification_reads (user_id, notification_id, read_at)
         VALUES (:uid, :nid, :t)'
    );
    foreach ($ids as $rawId) {
        $nid = (int) $rawId;
        if ($nid <= 0) {
            continue;
        }
        $ins->execute([':uid' => $uid, ':nid' => $nid, ':t' => $now]);
    }
    echo json_encode(['ok' => true], JSON_UNESCAPED_UNICODE);
    exit;
}

http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'action'], JSON_UNESCAPED_UNICODE);
