<?php
declare(strict_types=1);
require_once __DIR__.'/it_bootstrap.php';
function respond(array $body,int $code=200): never {http_response_code($code);header('Content-Type: application/json; charset=utf-8');header('Cache-Control: no-store');echo json_encode($body,JSON_THROW_ON_ERROR);exit;}
$written=null;$committed=false;
try {
 $a=it_actor($pdo);$op=(string)($_GET['op']??'tickets');$method=$_SERVER['REQUEST_METHOD']??'GET';
 if($method==='GET'){
  if($op==='me')respond(['user'=>$a,'trackers'=>it_rows($pdo,'SELECT * FROM it_trackers ORDER BY name'),'max_file_bytes'=>IT_MAX_FILE]);
  if($op==='people'){
   $q=trim((string)($_GET['q']??''));if(strlen($q)<2)respond(['items'=>[]]);
   respond(['items'=>it_rows($pdo,'SELECT id,full_name AS name,email FROM users WHERE full_name ILIKE ? OR email ILIKE ? ORDER BY full_name,id LIMIT 20',['%'.substr($q,0,100).'%','%'.substr($q,0,100).'%'])]);
  }
  if($op==='members'){
   $offset=max(0,(int)($_GET['offset']??0));$q='%'.substr((string)($_GET['q']??''),0,100).'%';
   $rows=it_rows($pdo,"SELECT m.user_id AS id,u.full_name AS name,u.email,m.role FROM it_members m JOIN users u ON u.id=m.user_id WHERE u.full_name ILIKE ? OR u.email ILIKE ? ORDER BY m.role,u.full_name,m.user_id LIMIT 101 OFFSET $offset",[$q,$q]);$more=count($rows)>100;
   respond(['items'=>array_slice($rows,0,100),'has_more'=>$more]);
  }
  if($op==='tickets'){
   $args=[];$where=it_acl($a,$args);
   foreach(['status','campus'] as $f)if(!empty($_GET[$f])){$where.=" AND t.$f=?";$args[]=(string)$_GET[$f];}
   if(!empty($_GET['tracker'])){$where.=' AND t.tracker_id=?';$args[]=(int)$_GET['tracker'];}
   if(($_GET['scope']??'')==='assigned'){$where.=' AND t.assignee_id=?';$args[]=$a['id'];}
   if(($_GET['scope']??'')==='reported'){$where.=' AND t.reporter_id=?';$args[]=$a['id'];}
   if(($_GET['scope']??'')==='watching'){$where.=' AND EXISTS(SELECT 1 FROM it_watchers w WHERE w.ticket_id=t.id AND w.user_id=?)';$args[]=$a['id'];}
   if(!empty($_GET['q'])){$where.=' AND (t.subject ILIKE ? OR t.description ILIKE ?)';$term='%'.substr((string)$_GET['q'],0,100).'%';$args[]=$term;$args[]=$term;}
   $offset=max(0,(int)($_GET['offset']??0));
   $rows=it_rows($pdo,"SELECT t.*,r.name AS tracker,u.full_name AS reporter,v.full_name AS assignee FROM it_tickets t JOIN it_trackers r ON r.id=t.tracker_id JOIN users u ON u.id=t.reporter_id LEFT JOIN users v ON v.id=t.assignee_id WHERE $where ORDER BY t.updated_at DESC,t.id DESC LIMIT 31 OFFSET $offset",$args);
   respond(['items'=>array_slice($rows,0,30),'has_more'=>count($rows)>30]);
  }
  if($op==='ticket'){
   $id=(int)($_GET['id']??0);$t=it_ticket($pdo,$a,$id);
   $names=it_one($pdo,'SELECT r.name AS tracker,u.full_name AS reporter,v.full_name AS assignee,z.full_name AS assigner FROM it_tickets t JOIN it_trackers r ON r.id=t.tracker_id JOIN users u ON u.id=t.reporter_id LEFT JOIN users v ON v.id=t.assignee_id LEFT JOIN users z ON z.id=t.assigner_id WHERE t.id=?',[$id]);
   $t=array_merge($t,$names??[]);$t['can_assign']=it_manager($a);$t['can_progress']=it_progress_allowed($a,$t);$t['can_watch']=it_watch_allowed($a,$t);
   $watchers=it_rows($pdo,'SELECT w.user_id AS id,u.full_name AS name,u.email,w.added_by FROM it_watchers w JOIN users u ON u.id=w.user_id WHERE w.ticket_id=? ORDER BY u.full_name',[$id]);
   $files=it_rows($pdo,'SELECT id,filename,mime,size_bytes,sha256,created_at FROM it_attachments WHERE ticket_id=? ORDER BY id',[$id]);
   respond(['ticket'=>$t,'watchers'=>$watchers,'attachments'=>$files]);
  }
  if($op==='activity'){
   $id=(int)($_GET['id']??0);it_ticket($pdo,$a,$id);$kind=($_GET['kind']??'messages')==='events'?'events':'messages';$offset=max(0,(int)($_GET['offset']??0));
   $sql=$kind==='messages'?'SELECT x.*,u.full_name AS author,r.full_name AS recipient FROM it_messages x JOIN users u ON u.id=x.author_id JOIN users r ON r.id=x.recipient_id':'SELECT x.*,u.full_name AS author FROM it_events x JOIN users u ON u.id=x.actor_id';
   $rows=it_rows($pdo,$sql." WHERE x.ticket_id=? ORDER BY x.id DESC LIMIT 31 OFFSET $offset",[$id]);respond(['items'=>array_slice($rows,0,30),'has_more'=>count($rows)>30]);
  }
  if($op==='notifications'){
   $args=[];$acl=it_acl($a,$args);array_unshift($args,$a['id']);
   respond(['items'=>it_rows($pdo,"SELECT n.* FROM it_notifications n JOIN it_tickets t ON t.id=n.ticket_id WHERE n.user_id=? AND $acl ORDER BY n.id DESC LIMIT 50",$args)]);
  }
  if($op==='download'){
   $f=it_one($pdo,'SELECT * FROM it_attachments WHERE id=?',[(int)($_GET['id']??0)]);if(!$f)throw new RuntimeException('Attachment unavailable.',404);
   it_ticket($pdo,$a,(int)$f['ticket_id']);$path=it_root().DIRECTORY_SEPARATOR.$f['storage_key'];
   if(!is_file($path)||filesize($path)!==(int)$f['size_bytes'])throw new RuntimeException('Attachment unavailable.',404);
   header('Content-Type: application/octet-stream');header('X-Content-Type-Options: nosniff');header('Cache-Control: no-store');header("Content-Disposition: attachment; filename*=UTF-8''".rawurlencode($f['filename']));header('Content-Length: '.$f['size_bytes']);readfile($path);exit;
  }
  throw new RuntimeException('Unknown operation.',404);
 }
 if($method!=='POST')throw new RuntimeException('Method not allowed.',405);
 it_require_csrf();
 // All writes are POST + authenticated headers. Ensure the shared auth adapter also
 // enforces CSRF for cookie sessions; bearer-token APIs do not use cookie CSRF.
 if($op==='attach'){
  $in=$_POST;$f=$_FILES['file']??null;
  if(!$f||$f['error']!==UPLOAD_ERR_OK||!is_uploaded_file($f['tmp_name']))throw new RuntimeException('Upload failed; choose a file up to 5 MB.',422);
  $size=filesize($f['tmp_name']);if($size<1||$size>IT_MAX_FILE)throw new RuntimeException('Each attachment must be 1 byte to 5 MB.',413);
  $name=basename(str_replace('\\','/',(string)$f['name']));$name=preg_replace('/[\x00-\x1f\x7f]/','',$name);
  if($name===''||strlen($name)>200)throw new RuntimeException('Invalid filename.',422);
  $ext=strtolower(pathinfo($name,PATHINFO_EXTENSION));
  if(!in_array($ext,['pdf','doc','docx','xls','xlsx','ppt','pptx','txt','csv','log','zip','png','jpg','jpeg','webp','gif'],true))throw new RuntimeException('Unsupported attachment type.',422);
  $sha=hash_file('sha256',$f['tmp_name']);$in['filename']=$name;$in['sha256']=$sha;$in['size_bytes']=$size;
 }else{
  $raw=file_get_contents('php://input',false,null,0,262145);if(strlen($raw)>262144)throw new RuntimeException('Request too large.',413);
  $in=json_decode($raw,true,32,JSON_THROW_ON_ERROR);if(!is_array($in))throw new RuntimeException('Invalid JSON.',400);
 }
 $key=(string)($in['client_key']??'');if(!preg_match('/^[a-f0-9]{32}$/D',$key))throw new RuntimeException('Invalid request identity.',422);
 $hash=hash('sha256',$op.'|'.json_encode($in,JSON_THROW_ON_ERROR));
 $pdo->beginTransaction();
 $pdo->prepare('SELECT pg_advisory_xact_lock(hashtextextended(?,0))')->execute(['it:'.$a['id'].':'.$key]);
 $old=it_one($pdo,'SELECT request_hash,result FROM it_receipts WHERE user_id=? AND client_key=?',[$a['id'],$key]);
 if($old){if(!hash_equals($old['request_hash'],$hash))throw new RuntimeException('Request identity already used for different content.',409);$pdo->commit();$committed=true;respond(json_decode($old['result'],true,32,JSON_THROW_ON_ERROR));}
 $result=['ok'=>true];
 if($op==='member'){
  $id=(int)($in['user_id']??0);it_person($pdo,$id);
  // Everyone can add a regular member. This never grants technician/manager access.
  it_exec($pdo,"INSERT INTO it_members(user_id,role,added_by) VALUES (?,'member',?) ON CONFLICT(user_id) DO NOTHING",[$id,$a['id']]);
 }elseif($op==='role'){
  if(!it_manager($a))throw new RuntimeException('Only the IT manager can change roles.',403);
  $pdo->query('SELECT pg_advisory_xact_lock(880114)');
  $currentRole=it_one($pdo,'SELECT role FROM it_members WHERE user_id=?',[$a['id']]);if(($currentRole['role']??'')!=='manager')throw new RuntimeException('Manager role was removed.',403);
  $id=(int)($in['user_id']??0);$role=(string)($in['role']??'');
  if(!in_array($role,['member','technician','manager'],true))throw new RuntimeException('Invalid role.',422);
  $oldMember=it_one($pdo,'SELECT * FROM it_members WHERE user_id=? FOR UPDATE',[$id]);if(!$oldMember)throw new RuntimeException('Add this member first.',422);
  if($oldMember['role']==='manager'&&$role!=='manager'&&(int)$pdo->query("SELECT count(*) FROM it_members WHERE role='manager'")->fetchColumn()<=1)throw new RuntimeException('At least one IT manager must remain.',422);
  it_exec($pdo,'UPDATE it_members SET role=? WHERE user_id=?',[$role,$id]);
 }elseif($op==='tracker'){
  if(!it_manager($a))throw new RuntimeException('Manager access required.',403);
  $name=it_text($in,'name',80);it_exec($pdo,'INSERT INTO it_trackers(name) VALUES (?) ON CONFLICT(name) DO NOTHING',[$name]);
 }elseif($op==='create'){
  $subject=it_text($in,'subject',200);$description=it_text($in,'description',20000);$campus=it_text($in,'campus',180);$tracker=(int)($in['tracker_id']??0);$priority=(string)($in['priority']??'normal');
  if(!it_one($pdo,'SELECT id FROM it_trackers WHERE id=?',[$tracker])||!in_array($priority,['low','normal','high','urgent'],true))throw new RuntimeException('Invalid tracker or priority.',422);
  $t=it_one($pdo,'INSERT INTO it_tickets(subject,description,campus,tracker_id,priority,reporter_id) VALUES (?,?,?,?,?,?) RETURNING *',[$subject,$description,$campus,$tracker,$priority,$a['id']]);
  it_event($pdo,$a,(int)$t['id'],'created');it_notify($pdo,$a,$t,'New support request: '.$subject);$result['ticket_id']=(int)$t['id'];
 }elseif($op==='read_notification'){
  it_exec($pdo,'UPDATE it_notifications SET is_read=true WHERE id=? AND user_id=?',[(int)($in['id']??0),$a['id']]);
 }else{
  $id=(int)($in['ticket_id']??0);$t=it_ticket($pdo,$a,$id,true);$result['ticket_id']=$id;
  if($op==='assign'){
   if(!it_manager($a))throw new RuntimeException('Only the IT manager may assign tickets.',403);it_version($in,$t);
   if($t['status']==='closed')throw new RuntimeException('Reopen the ticket before reassigning it.',422);
   $assignee=(int)($in['assignee_id']??0);$m=it_one($pdo,"SELECT user_id FROM it_members WHERE user_id=? AND role IN ('technician','manager')",[$assignee]);if(!$m)throw new RuntimeException('Choose an IT technician or manager.',422);
   $watchers=$in['watchers']??[];if(!is_array($watchers)||count($watchers)<1)throw new RuntimeException('Add at least one watcher when assigning.',422);
   $due=trim((string)($in['due_date']??''));if($due!==''&&(!preg_match('/^\d{4}-\d{2}-\d{2}$/D',$due)||date('Y-m-d',strtotime($due))!==$due))throw new RuntimeException('Invalid due date.',422);
   it_exec($pdo,"UPDATE it_tickets SET assignee_id=?,assigner_id=?,due_date=?,status=CASE WHEN status='new' THEN 'assigned' ELSE status END,version=version+1,updated_at=now() WHERE id=?",[$assignee,$a['id'],$due===''?null:$due,$id]);
   it_watchers($pdo,$a,$id,$watchers);it_event($pdo,$a,$id,'assigned',['assignee_id'=>$assignee,'watchers'=>$watchers,'due_date'=>$due]);
  }elseif($op==='watchers'){
   if(!it_watch_allowed($a,$t))throw new RuntimeException('Only the assigner or manager may change watchers.',403);it_version($in,$t);
   if(!is_array($in['watchers']??null))throw new RuntimeException('Invalid watchers.',422);it_watchers($pdo,$a,$id,$in['watchers']);
   it_exec($pdo,'UPDATE it_tickets SET version=version+1,updated_at=now() WHERE id=?',[$id]);it_event($pdo,$a,$id,'watchers_updated',['watchers'=>$in['watchers']]);
  }elseif($op==='progress'){
   if(!it_progress_allowed($a,$t))throw new RuntimeException('Only the assignee or manager may update progress.',403);it_version($in,$t);
   $status=(string)($in['status']??'');$percent=filter_var($in['percent']??null,FILTER_VALIDATE_INT);$resolution=it_text($in,'resolution',10000,false);
   if($percent===false||!it_transition($t['status'],$status,it_manager($a)))throw new RuntimeException('Invalid progress or status transition.',422);
   $error=it_validate_progress($percent,$status,$resolution);if($error)throw new RuntimeException($error,422);
   it_exec($pdo,"UPDATE it_tickets SET percent=?,status=?,resolution=?,closed_at=CASE WHEN ?='closed' THEN now() ELSE NULL END,version=version+1,updated_at=now() WHERE id=?",[$percent,$status,$resolution,$status,$id]);it_event($pdo,$a,$id,'progress',['from'=>$t['status'],'status'=>$status,'percent'=>$percent,'resolution'=>$resolution]);
  }elseif($op==='message'){
   if(empty($t['assignee_id']))throw new RuntimeException('Save your draft; a manager must assign the ticket before you send it.',422);
   if((int)($in['recipient_id']??0)!==(int)$t['assignee_id'])throw new RuntimeException('The assignee changed. Review your draft and send it to the current assignee.',409);
   $body=it_text($in,'body',20000);it_exec($pdo,'INSERT INTO it_messages(ticket_id,author_id,recipient_id,body) VALUES (?,?,?,?)',[$id,$a['id'],$t['assignee_id'],$body]);it_event($pdo,$a,$id,'message_sent');
  }elseif($op==='attach'){
   if($t['status']==='closed')throw new RuntimeException('Reopen the ticket before attaching files.',422);
   $count=it_one($pdo,'SELECT count(*) AS total FROM it_attachments WHERE ticket_id=?',[$id]);if((int)$count['total']>=20)throw new RuntimeException('Maximum 20 attachments per ticket.',422);
   $storage=bin2hex(random_bytes(32));$written=it_root().DIRECTORY_SEPARATOR.$storage;
   if(!move_uploaded_file($f['tmp_name'],$written))throw new RuntimeException('Unable to save attachment.',503);chmod($written,0600);
   $mime=(new finfo(FILEINFO_MIME_TYPE))->file($written)?:'application/octet-stream';
   it_exec($pdo,'INSERT INTO it_attachments(ticket_id,uploader_id,filename,mime,size_bytes,sha256,storage_key) VALUES (?,?,?,?,?,?,?)',[$id,$a['id'],$name,$mime,$size,$sha,$storage]);it_event($pdo,$a,$id,'attachment_added',['filename'=>$name,'size_bytes'=>$size]);
  }else{throw new RuntimeException('Unknown operation.',404);}
  $latest=it_one($pdo,'SELECT * FROM it_tickets WHERE id=?',[$id]);it_notify($pdo,$a,$latest,'Ticket #'.$id.': '.str_replace('_',' ',$op));
 }
 it_exec($pdo,'INSERT INTO it_receipts(user_id,client_key,request_hash,result) VALUES (?,?,?,?::jsonb)',[$a['id'],$key,$hash,json_encode($result,JSON_THROW_ON_ERROR)]);
 $pdo->commit();$committed=true;respond($result);
}catch(Throwable $e){
 if(isset($pdo)&&$pdo->inTransaction())$pdo->rollBack();if($written&&!$committed&&is_file($written))@unlink($written);
 $code=$e instanceof JsonException?400:(int)$e->getCode();if(!in_array($code,[400,401,403,404,405,409,413,422,503],true)){$code=500;error_log('IT support: '.$e->getMessage());}
 respond(['detail'=>$code===500?'Support service unavailable. Try again later.':$e->getMessage()],$code);
}
