<?php
declare(strict_types=1);
require_once __DIR__.'/../../authentication/api/connect.php';
function guideline_scope(array $user): array {
 $role=(string)$user['role'];$department=null;
 if($role==='hod'){$q=db()->prepare('SELECT department_id FROM hod_assignments WHERE user_id=?');$q->execute([(int)$user['id']]);$department=$q->fetchColumn();}
 elseif($role==='student'){$q=db()->prepare('SELECT department_id FROM students WHERE user_id=?');$q->execute([(int)$user['id']]);$department=$q->fetchColumn();}
 elseif(!in_array($role,['admin','staff'],true))reply(403,['status'=>'error','message'=>'This workspace is unavailable for your account.']);
 if(!in_array($role,['admin','staff'],true)&&!$department)reply(403,['status'=>'error','message'=>'Your account needs an assigned department to open guidelines.']);
 return ['department_id'=>$department?(int)$department:null,'can_edit'=>in_array($role,['admin','staff','hod'],true)];
}
function guideline_course(array $scope,int $id): array {
 $q=db()->prepare('SELECT c.*,d.department_name FROM courses c JOIN departments d ON d.id=c.department_id WHERE c.id=? AND c.is_active=1 AND d.is_active=1');$q->execute([$id]);$course=$q->fetch();
 if(!$course||($scope['department_id']!==null&&(int)$course['department_id']!==$scope['department_id']))reply(404,['status'=>'error','message'=>'Course not found in your department.']);
 return $course;
}
function guideline_asset_url(int $id): string {return app_path().'/shared/api/guideline_asset.php?id='.$id;}
function guideline_assets(int $course,array $ids): array {
 if(!$ids)return [];
 $q=db()->prepare('SELECT id,file_name,media_type,file_size_bytes,asset_kind FROM guideline_assets WHERE course_id=? AND id IN ('.implode(',',array_fill(0,count($ids),'?')).')');$q->execute(array_merge([$course],$ids));
 $rows=$q->fetchAll();foreach($rows as &$row)$row['url']=guideline_asset_url((int)$row['id']);return $rows;
}
function guideline_ids(mixed $ids): array {
 if(!is_array($ids)||count($ids)>100)throw new InvalidArgumentException('Choose at most 100 attachments.');
 $out=[];foreach($ids as $id){if(!is_numeric($id)||(int)$id<1)throw new InvalidArgumentException('Invalid attachment.');$out[]=(int)$id;}return array_values(array_unique($out));
}
// Store typed editor data, never executable HTML. Only these formats can reach the renderer.
function guideline_delta(mixed $delta,int $course): array {
 if(!is_array($delta)||!isset($delta['ops'])||!is_array($delta['ops'])||count($delta['ops'])>20000)throw new InvalidArgumentException('The editor document is invalid or too large.');
 $ops=[];$images=[];
 foreach($delta['ops'] as $op){
  if(!is_array($op)||!array_key_exists('insert',$op)||isset($op['retain'])||isset($op['delete']))throw new InvalidArgumentException('Invalid editor operation.');
  $insert=$op['insert'];
  if(is_array($insert)){
   if(count($insert)!==1||!isset($insert['image'])||!is_string($insert['image']))throw new InvalidArgumentException('Only uploaded images can be embedded.');
   $prefix=app_path().'/shared/api/guideline_asset.php?id=';
   if(!str_starts_with($insert['image'],$prefix)||!ctype_digit(substr($insert['image'],strlen($prefix))))throw new InvalidArgumentException('Upload images through the image tool.');
   $images[]=(int)substr($insert['image'],strlen($prefix));
  }elseif(!is_string($insert))throw new InvalidArgumentException('Invalid document text.');
  $clean=['insert'=>$insert];$attrs=[];
  if(isset($op['attributes'])&&!is_array($op['attributes']))throw new InvalidArgumentException('Invalid text format.');
  foreach(($op['attributes']??[]) as $key=>$value){
   $valid=match($key){
    'bold','italic','underline','strike','blockquote'=>is_bool($value),
    'header'=>is_int($value)&&$value>=1&&$value<=6,
    'indent'=>is_int($value)&&$value>=1&&$value<=8,
    'font'=>in_array($value,['serif','monospace'],true),
    'size'=>in_array($value,['small','large','huge'],true),
    'script'=>in_array($value,['sub','super'],true),
    'list'=>in_array($value,['ordered','bullet','checked','unchecked'],true),
    'align'=>in_array($value,['center','right','justify'],true),
    'direction'=>$value==='rtl',
    'color','background'=>is_string($value)&&preg_match('/^#[0-9a-fA-F]{3}(?:[0-9a-fA-F]{3})?$/',$value),
    'link'=>is_string($value)&&strlen($value)<=2000&&preg_match('~^(https?://|mailto:)[^\x00-\x20<>]+$~i',$value),
    'code-block'=>is_bool($value)||(is_string($value)&&preg_match('/^[a-zA-Z0-9_-]{1,40}$/',$value)),
    'table'=>is_string($value)&&preg_match('/^[a-zA-Z0-9_-]{1,80}$/',$value),
    default=>false
   };
   if(!$valid)throw new InvalidArgumentException('Unsupported document format: '.$key);
   $attrs[$key]=$value;
  }
  if($attrs)$clean['attributes']=$attrs;$ops[]=$clean;
 }
 $images=array_values(array_unique($images));
 if($images){$found=guideline_assets($course,$images);if(count($found)!==count($images))throw new InvalidArgumentException('An image is outside this course.');foreach($found as $asset)if($asset['asset_kind']!=='image')throw new InvalidArgumentException('Invalid image attachment.');}
 if(!$ops)$ops=[['insert'=>"\n"]];
 $last=$ops[count($ops)-1]['insert'];if(!is_string($last)||!str_ends_with($last,"\n"))$ops[]=['insert'=>"\n"];
 return ['delta'=>['ops'=>$ops],'image_ids'=>$images];
}
