<?php
header('Content-Type: application/json; charset=UTF-8');
header('Cache-Control: no-store');
$raw = file_get_contents('php://input');
$data = json_decode((string)$raw, true);
$endpoint = is_array($data) ? (string)($data['endpoint'] ?? '') : '';
if ($endpoint === '') { http_response_code(400); echo json_encode(['ok'=>false,'error'=>'missing endpoint']); exit; }
$cacheDir = __DIR__ . '/cache';
if (!is_dir($cacheDir)) mkdir($cacheDir, 0775, true);
$file = $cacheDir . '/push_subscriptions.json';
$subs = is_file($file) ? json_decode((string)file_get_contents($file), true) : [];
if (!is_array($subs)) $subs = [];
if (!empty($data['_delete'])) {
    $subs = array_values(array_filter($subs, fn($s)=>!is_array($s) || ($s['endpoint'] ?? '') !== $endpoint));
} else {
    $found = false;
    foreach ($subs as &$sub) {
        if (is_array($sub) && ($sub['endpoint'] ?? '') === $endpoint) { $sub = $data; $found = true; break; }
    }
    unset($sub);
    if (!$found) $subs[] = $data;
}
file_put_contents($file, json_encode($subs, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), LOCK_EX);
chmod($file, 0664);
echo json_encode(['ok'=>true,'count'=>count($subs)]);
