<?php
class TeamTask extends BaseModel
{
    public function all(?int$userId=null):array{$sql='SELECT team_tasks.*,assignee.name assignee_name,creator.name creator_name FROM team_tasks LEFT JOIN users assignee ON assignee.id=team_tasks.assigned_to LEFT JOIN users creator ON creator.id=team_tasks.created_by';$p=[];if($userId){$sql.=' WHERE team_tasks.assigned_to=? OR team_tasks.created_by=?';$p=[$userId,$userId];}$sql.=' ORDER BY FIELD(team_tasks.status,\'open\',\'in_progress\',\'blocked\',\'completed\'),FIELD(team_tasks.priority,\'urgent\',\'high\',\'normal\',\'low\'),team_tasks.due_at';$s=$this->db->prepare($sql);$s->execute($p);return$s->fetchAll();}
    public function create(array$d):int{$s=$this->db->prepare('INSERT INTO team_tasks (title,description,assigned_to,related_type,related_id,priority,status,due_at,created_by) VALUES (?,?,?,?,?,?,?,?,?)');$s->execute([trim($d['title']),trim((string)($d['description']??''))?:null,$d['assigned_to']?:null,trim((string)($d['related_type']??''))?:null,$d['related_id']?:null,$d['priority']??'normal',$d['status']??'open',$d['due_at']?:null,$_SESSION['user_id']??null]);return(int)$this->db->lastInsertId();}
    public function status(int$id,string$status):void{if(!in_array($status,['open','in_progress','blocked','completed'],true))return;$sql='UPDATE team_tasks SET status=?';if($status==='completed')$sql.=', completed_at=NOW()';$sql.=' WHERE id=?';$this->db->prepare($sql)->execute([$status,$id]);}
}
