<?php
require_once dirname(__DIR__,2).'/config.php';
if(!isset($_SESSION['user'])){http_response_code(403);exit('no user');}
$userId=$_SESSION['user'];
$role=$USERS[$userId]['role']??'user';
$path=dirname(__DIR__,2).'/data/push/subscription.json';
$dir=dirname($path);
if(!is_dir($dir))mkdir($dir,0755,true);
$input=json_decode(file_get_contents('php://input'),true);
if(!$input||empty($input['endpoint'])){http_response_code(400);exit('invalid');}
$input['user_id']=$userId;
$input['role']=$role;
$list=[];
if(file_exists($path)){$list=json_decode(file_get_contents($path),true);if(!is_array($list))$list=[];}
$found=false;
foreach($list as &$item){if(isset($item['endpoint'])&&$item['endpoint']===$input['endpoint']){$item=$input;$found=true;break;}}
if(!$found)$list[]=$input;
file_put_contents($path,json_encode($list,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE),LOCK_EX);
echo"ok";
