<?php
require_once 'auth.php';
include 'db.php';
requireLogin($conn);

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

$action = trim((string) ($_GET['action'] ?? $_POST['action'] ?? ''));
if ($action !== 'read_all') {
    echo json_encode(['ok' => false, 'message' => 'invalid_action']);
    exit();
}

$user_id = (int) ($_SESSION['user_id'] ?? 0);
if ($user_id <= 0) {
    echo json_encode(['ok' => false, 'message' => 'unauthorized']);
    exit();
}

$raw_keys = $_POST['notification_keys'] ?? '[]';
$keys = json_decode((string) $raw_keys, true);
if (!is_array($keys)) {
    $keys = [];
}

$keys = array_values(array_unique(array_filter(array_map(function ($key) {
    $key = trim((string) $key);
    return preg_match('/^[a-z0-9_-]{1,100}$/i', $key) ? $key : '';
}, $keys))));

if (empty($keys)) {
    echo json_encode(['ok' => true, 'read_count' => 0]);
    exit();
}

$stmt = mysqli_prepare($conn, "INSERT IGNORE INTO user_notification_reads (user_id, notification_key, read_at) VALUES (?, ?, NOW())");
if (!$stmt) {
    echo json_encode(['ok' => false, 'message' => 'prepare_failed']);
    exit();
}

$read_count = 0;
foreach ($keys as $key) {
    mysqli_stmt_bind_param($stmt, "is", $user_id, $key);
    if (mysqli_stmt_execute($stmt)) {
        $read_count += mysqli_stmt_affected_rows($stmt) > 0 ? 1 : 0;
    }
}

echo json_encode(['ok' => true, 'read_count' => $read_count]);
exit();
