<?php
declare(strict_types=1);
require_once __DIR__.'/../auth.php';
require_login('../login.php');
if(session_status()===PHP_SESSION_ACTIVE)@session_write_close();
require_once __DIR__.'/../db_bootstrap.php';
require_once __DIR__.'/../device_admin_alerts_lib.php';
require_once __DIR__.'/../device_subscriber_confirmation_lib.php';
header('Content-Type: application/json; charset=utf-8');
try{
  $conn=ensure_db(true);$raw=file_get_contents('php://input');$payload=json_decode((string)$raw,true);if(!is_array($payload))$payload=$_POST;
  $events=is_array($payload['events']??null)?array_slice($payload['events'],0,20):[];$results=[];
  foreach($events as $event){
    if(!is_array($event))continue;$group=strtolower((string)($event['group']??''));$id=(int)($event['id']??0);$state=strtoupper((string)($event['state']??''));
    if($state==='DOWN'&&in_array($group,['sectors','receivers'],true)){
      $confirmation=ua_device_subscriber_confirmation($conn,$group,$id);
      if(empty($confirmation['allow_alert'])){$results[]=['ok'=>true,'suppressed'=>true,'reason'=>$confirmation['reason']??'unconfirmed','group'=>$group,'id'=>$id];continue;}
    }
    $results[]=device_admin_alert_process($conn,$event);
  }
  echo json_encode(['ok'=>true,'results'=>$results],JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
}catch(Throwable $e){http_response_code(500);echo json_encode(['ok'=>false,'error'=>'alert_event_failed'],JSON_UNESCAPED_UNICODE);}

