<?php
declare(strict_types=1);
require_once __DIR__.'/../lib/notices.php';$u=require_auth();
try{
 $s=notice_user_scope($u);$method=$_SERVER['REQUEST_METHOD']??'GET';$action=$_GET['action']??'list';[$where,$args]=notice_visibility($u,$s);$publisher=in_array($u['role'],['admin','staff','hod'],true);
 if($method==='GET'&&$action==='count')reply(200,['unread'=>notice_unread($u,$s)]);
 if($method==='GET'&&$action==='list'){
  $filter=($_GET['filter']??'all')==='unread'?' AND r.notification_id IS NULL':'';$offset=max(0,min(10000000,(int)($_GET['offset']??0)));
  $q=db()->prepare("SELECT n.id,n.kind,n.title,n.message,n.link,n.created_at,n.created_by,p.audience,p.priority,p.software_name,p.software_version,r.read_at,COALESCE(NULLIF(NULLIF(TRIM(a.full_name),'null'),''),a.username,'SLPS') AS author,(SELECT GROUP_CONCAT(c.campus_name ORDER BY c.campus_name SEPARATOR ', ') FROM notice_campuses nc JOIN campuses c ON c.id=nc.campus_id WHERE nc.notification_id=n.id) AS campus_names FROM notifications n LEFT JOIN notice_publications p ON p.notification_id=n.id LEFT JOIN notification_reads r ON r.notification_id=n.id AND r.user_id=? LEFT JOIN users a ON a.id=n.created_by WHERE ".$where.$filter.' ORDER BY n.id DESC LIMIT 51 OFFSET '.$offset);$q->execute(array_merge([$u['id']],$args));$rows=$q->fetchAll();$more=count($rows)>50;if($more)array_pop($rows);
  $campuses=$publisher?db()->query('SELECT id,campus_name FROM campuses WHERE is_active=1 ORDER BY campus_name')->fetchAll():[];
  reply(200,['notices'=>$rows,'unread'=>notice_unread($u,$s),'can_publish'=>$publisher,'campuses'=>$campuses,'next_offset'=>$more?$offset+50:null]);
 }
 if($method==='POST'){
  $data=post_data(40000);
  if($action==='publish'){
   if(!$publisher)reply(403,['message'=>'Only administrators and HODs can publish notices.']);
   $title=text_field($data,'title',200);$message=text_field($data,'message',15000);$kind=(string)($data['kind']??'announcement');$audience=(string)($data['audience']??'global');$priority=(string)($data['priority']??'normal');
   if(!$title||!$message||!in_array($kind,['announcement','software_release'],true)||!in_array($audience,['global','campuses'],true)||!in_array($priority,['normal','important'],true))throw new InvalidArgumentException('Complete the title, message and audience.');
   $software=text_field($data,'software_name',160);$version=text_field($data,'software_version',80);$url=notice_link(text_field($data,'link',1024));if($kind==='software_release'&&(!$software||!$version))throw new InvalidArgumentException('Enter the software name and release version.');
   $ids=$data['campus_ids']??[];if(!is_array($ids)||count($ids)>200)throw new InvalidArgumentException('Select valid campuses.');$ids=array_values(array_unique(array_map('intval',$ids)));if($audience==='campuses'&&!$ids)throw new InvalidArgumentException('Select at least one campus.');
   if($audience==='campuses'){foreach($ids as $id){$q=db()->prepare('SELECT id FROM campuses WHERE id=? AND is_active=1');$q->execute([$id]);if(!$q->fetch())throw new InvalidArgumentException('A selected campus is unavailable.');}}
   rate_limit('notice-publish',(string)$u['id'],40,3600);db()->beginTransaction();try{$q=db()->prepare('INSERT INTO notifications(kind,title,message,link,created_by) VALUES (?,?,?,?,?)');$q->execute([$kind,$title,$message,$url,$u['id']]);$id=db()->lastInsertId();$q=db()->prepare('INSERT INTO notice_publications(notification_id,audience,priority,software_name,software_version) VALUES (?,?,?,?,?)');$q->execute([$id,$audience,$priority,$kind==='software_release'?$software:null,$kind==='software_release'?$version:null]);if($audience==='campuses')foreach($ids as $campus){$q=db()->prepare('INSERT INTO notice_campuses(notification_id,campus_id) VALUES (?,?)');$q->execute([$id,$campus]);}db()->commit();}catch(Throwable $e){if(db()->inTransaction())db()->rollBack();throw $e;}reply(201,['message'=>'Notification published.','id'=>$id,'unread'=>notice_unread($u,$s)]);
  }
  if($action==='read'){
   $id=(int)($data['id']??0);$q=db()->prepare('SELECT n.id FROM notifications n LEFT JOIN notice_publications p ON p.notification_id=n.id WHERE n.id=? AND '.$where);$q->execute(array_merge([$id],$args));if(!$q->fetch())reply(404,['message'=>'Notification not found.']);$q=db()->prepare('INSERT IGNORE INTO notification_reads(notification_id,user_id) VALUES (?,?)');$q->execute([$id,$u['id']]);reply(200,['message'=>'Notification marked as read.','unread'=>notice_unread($u,$s)]);
  }
  if($action==='read_all'){
   // A snapshot prevents notices arriving after the user clicked from being marked read.
   $through=max(0,(int)($data['through']??0));$q=db()->prepare('INSERT IGNORE INTO notification_reads(notification_id,user_id) SELECT n.id,? FROM notifications n LEFT JOIN notice_publications p ON p.notification_id=n.id WHERE n.id<=? AND '.$where);$q->execute(array_merge([$u['id'],$through],$args));reply(200,['message'=>'Notifications marked as read.','unread'=>notice_unread($u,$s)]);
  }
 }
 reply(405,['message'=>'Unsupported action.']);
}catch(InvalidArgumentException $e){reply(422,['message'=>$e->getMessage()]);}catch(Throwable $e){error_log('SLPS notices: '.$e->getMessage());reply(503,['message'=>'Notifications are unavailable. Apply the notices migration and check database access.']);}
