<?php
declare(strict_types=1);
// Integration point: reuse the existing authenticated PDO/session adapter.
require_once __DIR__.'/leave_common.php';
require_once __DIR__.'/it_policy.php';
function it_actor(PDO $pdo): array {
 $u=leave_current_user($pdo); // MUST validate the session/bearer token; never trust a posted user ID.
 if(empty($u['id']))throw new RuntimeException('Authentication required.',401);
 if(isset($u['account_status'])&&strtolower((string)$u['account_status'])==='suspended')throw new RuntimeException('Account suspended.',403);
 $profile=leave_official_profile($pdo,$u);
 $q=$pdo->prepare('SELECT role FROM it_members WHERE user_id=?');$q->execute([$u['id']]);
 $role=$q->fetchColumn()?:'member';
 return ['id'=>(int)$u['id'],'name'=>(string)($u['full_name']??''),'email'=>(string)($u['email']??''),'campus'=>(string)($profile['campus']??$u['campus']??''),'role'=>$role];
}
function it_root(): string {
 $configured=getenv('IT_SUPPORT_STORAGE');
 if(!$configured||!is_dir($configured)||!is_writable($configured))throw new RuntimeException('Private attachment storage is not configured.',503);
 $root=realpath($configured);$web=realpath($_SERVER['DOCUMENT_ROOT']??'');
 if(!$root||($web&&($root===$web||str_starts_with($root,$web.DIRECTORY_SEPARATOR))))throw new RuntimeException('Attachment storage must be outside the web root.',503);
 return $root;
}
function it_rows(PDO $pdo,string $sql,array $args=[]): array {$q=$pdo->prepare($sql);$q->execute($args);return $q->fetchAll(PDO::FETCH_ASSOC);}
function it_one(PDO $pdo,string $sql,array $args=[]): ?array {return it_rows($pdo,$sql,$args)[0]??null;}
function it_exec(PDO $pdo,string $sql,array $args=[]): void {$pdo->prepare($sql)->execute($args);}
function it_text(array $in,string $key,int $max,bool $required=true): string {
 $v=trim((string)($in[$key]??''));if(($required&&$v==='')||strlen($v)>$max)throw new RuntimeException("Invalid $key (maximum $max bytes).",422);return $v;
}
function it_ticket(PDO $pdo,array $a,int $id,bool $lock=false): array {
 $t=it_one($pdo,'SELECT * FROM it_tickets WHERE id=?'.($lock?' FOR UPDATE':''),[$id]);
 $watch=it_one($pdo,'SELECT user_id FROM it_watchers WHERE ticket_id=? AND user_id=?',[$id,$a['id']])!==null;
 if(!$t||!it_readable($a,$t,$watch))throw new RuntimeException('Ticket unavailable.',404);return $t;
}
function it_version(array $in,array $t): void {if((int)($in['version']??0)!==(int)$t['version'])throw new RuntimeException('Ticket changed. Refresh, review it and try again.',409);}
function it_event(PDO $pdo,array $a,int $id,string $action,array $details=[]): void {it_exec($pdo,'INSERT INTO it_events(ticket_id,actor_id,action,details) VALUES (?,?,?,?::jsonb)',[$id,$a['id'],$action,json_encode($details,JSON_THROW_ON_ERROR)]);}
function it_notify(PDO $pdo,array $a,array $t,string $message): void {
 $recipients=[(int)$t['reporter_id'],(int)($t['assignee_id']??0)];
 foreach(it_rows($pdo,'SELECT user_id FROM it_watchers WHERE ticket_id=?',[$t['id']]) as $w)$recipients[]=(int)$w['user_id'];
 foreach(it_rows($pdo,"SELECT user_id FROM it_members WHERE role='manager'") as $m)$recipients[]=(int)$m['user_id'];
 foreach(array_unique($recipients) as $id)if($id>0&&$id!==(int)$a['id'])it_exec($pdo,'INSERT INTO it_notifications(user_id,ticket_id,message) VALUES (?,?,?)',[$id,$t['id'],$message]);
}
function it_person(PDO $pdo,int $id): array {
 $u=it_one($pdo,'SELECT id,full_name,email FROM users WHERE id=?',[$id]);
 if(!$u)throw new RuntimeException('Choose an existing university user.',422);return $u;
}
function it_watchers(PDO $pdo,array $a,int $ticket,array $ids): void {
 if(count($ids)>30)throw new RuntimeException('Maximum 30 watchers.',422);
 $ids=array_values(array_unique(array_map('intval',$ids)));
 foreach($ids as $id)it_person($pdo,$id);
 it_exec($pdo,'DELETE FROM it_watchers WHERE ticket_id=?',[$ticket]);
 foreach($ids as $id)it_exec($pdo,'INSERT INTO it_watchers(ticket_id,user_id,added_by) VALUES (?,?,?)',[$ticket,$id,$a['id']]);
}

function it_require_csrf(): void {
 // Use the shared reader so Apache/XAMPP getallheaders() fallback is included.
 // it_actor() has already validated this token with leave_current_user().
 $bearer=function_exists('rvu_bearer_token')?rvu_bearer_token():'';
 if($bearer!=='')return;
 $expected=(string)($_SESSION['csrf_token']??'');$received=(string)($_SERVER['HTTP_X_CSRF_TOKEN']??'');
 if($expected===''||!hash_equals($expected,$received))throw new RuntimeException('A valid CSRF token is required for cookie-authenticated requests.',403);
}
