<?php
declare(strict_types=1);
require_once __DIR__.'/../lib/suggestions.php';$u=require_auth();
try{
 if(!in_array($u['role'],['student','admin','hod','staff'],true))reply(403,['message'=>'Access denied.']);$action=$_GET['action']??'list';$method=$_SERVER['REQUEST_METHOD']??'GET';
 if($method==='GET'&&$action==='list'){
  $where='s.deleted_at IS NULL';$args=[$u['id']];$before=max(0,(int)($_GET['before']??0));if($before){$where.=' AND s.id<?';$args[]=$before;}if(($_GET['mine']??'0')==='1'){$where.=' AND s.user_id=?';$args[]=$u['id'];}
  $term=trim(substr((string)($_GET['q']??''),0,150));if($term!==''){$where.=' AND (s.title LIKE ? OR s.message LIKE ?)';$args[]='%'.$term.'%';$args[]='%'.$term.'%';}
  $category=(string)($_GET['category']??'');if($category!==''){if(!in_array($category,suggestion_categories(),true))throw new InvalidArgumentException('Choose a valid category.');$where.=' AND s.category=?';$args[]=$category;}
  $q=db()->prepare('SELECT s.id,s.user_id,s.title,s.message,s.category,s.likes_count,s.comments_count,s.created_at,'.suggestion_name_sql().' AS author,u.role AS author_role,EXISTS (SELECT 1 FROM suggestion_likes l WHERE l.suggestion_id=s.id AND l.user_id=?) AS liked FROM suggestions s JOIN users u ON u.id=s.user_id WHERE '.$where.' ORDER BY s.id DESC LIMIT 11');$q->execute($args);$rows=$q->fetchAll();$more=count($rows)>10;if($more)array_pop($rows);foreach($rows as &$row)$row['can_remove']=suggestion_can_remove($u,(int)$row['user_id']);unset($row);reply(200,['suggestions'=>$rows,'next_before'=>$more?(int)end($rows)['id']:null,'can_post'=>$u['role']==='student']);
 }
 if($method==='GET'&&$action==='comments'){
  $id=(int)($_GET['id']??0);suggestion_post($id);$before=max(0,(int)($_GET['before']??0));$args=[$id];$where='c.suggestion_id=? AND c.deleted_at IS NULL';if($before){$where.=' AND c.id<?';$args[]=$before;}
  $q=db()->prepare('SELECT c.id,c.suggestion_id,c.user_id,c.message,c.created_at,'.suggestion_name_sql().' AS author,u.role AS author_role FROM suggestion_comments c JOIN users u ON u.id=c.user_id WHERE '.$where.' ORDER BY c.id DESC LIMIT 21');$q->execute($args);$rows=$q->fetchAll();$more=count($rows)>20;if($more)array_pop($rows);foreach($rows as &$row)$row['can_remove']=suggestion_can_remove($u,(int)$row['user_id']);unset($row);reply(200,['comments'=>$rows,'next_before'=>$more?(int)end($rows)['id']:null]);
 }
 if($method!=='POST')reply(405,['message'=>'Unsupported action.']);$data=post_data(30000);
 if($action==='post'){
  if($u['role']!=='student')reply(403,['message'=>'Student accounts can post suggestions.']);$title=text_field($data,'title',160);$message=text_field($data,'message',5000);$category=(string)($data['category']??'other');if(!$title||!$message||!in_array($category,suggestion_categories(),true))throw new InvalidArgumentException('Enter a title, suggestion and category.');rate_limit('suggestion-post',(string)$u['id'],15,3600);$q=db()->prepare('INSERT INTO suggestions(user_id,title,message,category) VALUES (?,?,?,?)');$q->execute([$u['id'],$title,$message,$category]);reply(201,['message'=>'Your suggestion has been posted.','id'=>db()->lastInsertId()]);
 }
 $id=(int)($data['id']??0);
 if($action==='comment'){
  $message=text_field($data,'message',2000);if(!$message)throw new InvalidArgumentException('Write a comment first.');rate_limit('suggestion-comment',(string)$u['id'],80,3600);
  db()->beginTransaction();try{$post=suggestion_post($id,true);$q=db()->prepare('INSERT INTO suggestion_comments(suggestion_id,user_id,message) VALUES (?,?,?)');$q->execute([$id,$u['id'],$message]);$commentId=db()->lastInsertId();$q=db()->prepare('UPDATE suggestions SET comments_count=comments_count+1 WHERE id=?');$q->execute([$id]);db()->commit();}catch(Throwable $e){if(db()->inTransaction())db()->rollBack();throw $e;}
  $q=db()->prepare('SELECT c.id,c.suggestion_id,c.user_id,c.message,c.created_at,'.suggestion_name_sql().' AS author,u.role AS author_role FROM suggestion_comments c JOIN users u ON u.id=c.user_id WHERE c.id=?');$q->execute([$commentId]);$comment=$q->fetch();$comment['can_remove']=true;reply(201,['comment'=>$comment,'comments_count'=>(int)$post['comments_count']+1]);
 }
 if($action==='like'){
  if(!isset($data['liked'])||!is_bool($data['liked']))throw new InvalidArgumentException('Choose like or unlike.');rate_limit('suggestion-like',(string)$u['id'],300,3600);db()->beginTransaction();try{suggestion_post($id,true);if($data['liked']){$q=db()->prepare('INSERT IGNORE INTO suggestion_likes(suggestion_id,user_id) VALUES (?,?)');$q->execute([$id,$u['id']]);$delta=$q->rowCount()?1:0;}else{$q=db()->prepare('DELETE FROM suggestion_likes WHERE suggestion_id=? AND user_id=?');$q->execute([$id,$u['id']]);$delta=$q->rowCount()?-1:0;}if($delta){$q=db()->prepare('UPDATE suggestions SET likes_count=GREATEST(0,CAST(likes_count AS SIGNED)+?) WHERE id=?');$q->execute([$delta,$id]);}$post=suggestion_post($id);db()->commit();}catch(Throwable $e){if(db()->inTransaction())db()->rollBack();throw $e;}reply(200,['liked'=>$data['liked'],'likes_count'=>(int)$post['likes_count']]);
 }
 if(in_array($action,['remove_post','remove_comment'],true)){
  db()->beginTransaction();try{$post=suggestion_post($id,true);if($action==='remove_post'){if(!suggestion_can_remove($u,(int)$post['user_id'])){db()->rollBack();reply(403,['message'=>'You can only remove your own suggestions.']);}$q=db()->prepare('UPDATE suggestions SET deleted_at=CURRENT_TIMESTAMP WHERE id=?');$q->execute([$id]);}
  else{$cid=(int)($data['comment_id']??0);$q=db()->prepare('SELECT user_id FROM suggestion_comments WHERE id=? AND suggestion_id=? AND deleted_at IS NULL FOR UPDATE');$q->execute([$cid,$id]);$comment=$q->fetch();if(!$comment){db()->rollBack();reply(404,['message'=>'Comment no longer available.']);}if(!suggestion_can_remove($u,(int)$comment['user_id'])){db()->rollBack();reply(403,['message'=>'You can only remove your own comments.']);}$q=db()->prepare('UPDATE suggestion_comments SET deleted_at=CURRENT_TIMESTAMP WHERE id=?');$q->execute([$cid]);$q=db()->prepare('UPDATE suggestions SET comments_count=GREATEST(0,CAST(comments_count AS SIGNED)-1) WHERE id=?');$q->execute([$id]);}$latest=$action==='remove_comment'?suggestion_post($id):null;
  db()->commit();}catch(Throwable $e){if(db()->inTransaction())db()->rollBack();throw $e;}reply(200,['message'=>'Removed.','comments_count'=>$action==='remove_comment'?(int)$latest['comments_count']:0]);
 }
 reply(405,['message'=>'Unsupported action.']);
}catch(InvalidArgumentException $e){reply(422,['message'=>$e->getMessage()]);}catch(Throwable $e){error_log('SLPS suggestions: '.$e->getMessage());reply(503,['message'=>'Suggestion Box is unavailable. Apply the suggestion-box migration and check database access.']);}
