<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Response;
use App\Core\Session;
use App\Services\AssessmentService;
use App\Services\AssignmentService;
use InvalidArgumentException;
use RuntimeException;

final class AssessmentController extends Controller
{
    public function __construct(private ?AssessmentService $service=null,private ?AssignmentService $assignments=null){$this->service??=new AssessmentService();$this->assignments??=new AssignmentService();}
    public function index():Response{$tid=$this->therapistId();return $this->view('assessments/index',['pageTitle'=>'Assessments','pageDescription'=>'Clinical assessments and documentation.','assessments'=>$this->service->list(['search'=>(string)($_GET['search']??''),'status'=>(string)($_GET['status']??''),'date'=>(string)($_GET['date']??''),'page'=>(int)($_GET['page']??1)],$tid),'filters'=>['search'=>(string)($_GET['search']??''),'status'=>(string)($_GET['status']??''),'date'=>(string)($_GET['date']??'')]]);}
    public function createForm():Response{$tid=$this->therapistId();return $this->view('assessments/form',['pageTitle'=>'New Assessment','pageDescription'=>'Create a clinical assessment for a currently assigned patient.','assessment'=>null,'csrf'=>Csrf::token(),'form'=>Session::pull('assessment_form')??[],'error'=>Session::pull('assessment_error'),'message'=>Session::pull('assessment_message'),...$this->service->formData($tid),'therapistLocked'=>$tid!==null]);}
    public function create():Response{Csrf::verify((string)($_POST['_csrf']??''));$tid=$this->therapistId();try{$id=$this->service->create($_POST,Auth::id()??0,$tid);Session::put('assessment_message','Assessment created successfully.');return Response::redirect('/crm/public/assessments/'.$id.'/edit');}catch(InvalidArgumentException $e){Session::put('assessment_error',$e->getMessage());Session::put('assessment_form',$_POST);return Response::redirect('/crm/public/assessments/create');}}
    public function editForm(int $id):Response{$tid=$this->therapistId();$a=$this->service->find($id);$this->authorize($a,$tid);return $this->view('assessments/form',['pageTitle'=>'Assessment '.$a['assessment_reference'],'pageDescription'=>'Clinical assessment record.','assessment'=>$a,'csrf'=>Csrf::token(),'form'=>Session::pull('assessment_form')??[],'error'=>Session::pull('assessment_error'),'message'=>Session::pull('assessment_message'),...$this->service->formData($tid),'therapistLocked'=>$tid!==null]);}
    public function update(int $id):Response{Csrf::verify((string)($_POST['_csrf']??''));$tid=$this->therapistId();try{$a=$this->service->find($id);$this->authorize($a,$tid);$this->service->update($id,$_POST,Auth::id()??0,$tid);Session::put('assessment_message','Assessment updated successfully.');}catch(InvalidArgumentException|RuntimeException $e){Session::put('assessment_error',$e->getMessage());Session::put('assessment_form',$_POST);}return Response::redirect('/crm/public/assessments/'.$id.'/edit');}
    public function submit(int $id):Response{Csrf::verify((string)($_POST['_csrf']??''));$tid=$this->therapistId();try{$this->service->submit($id,Auth::id()??0,$tid);Session::put('assessment_message','Assessment submitted for review.');}catch(InvalidArgumentException|RuntimeException $e){Session::put('assessment_error',$e->getMessage());}return Response::redirect('/crm/public/assessments/'.$id.'/edit');}
    public function review(int $id):Response{Csrf::verify((string)($_POST['_csrf']??''));try{$this->service->review($id,Auth::id()??0);Session::put('assessment_message','Assessment marked as reviewed.');}catch(InvalidArgumentException|RuntimeException $e){Session::put('assessment_error',$e->getMessage());}return Response::redirect('/crm/public/assessments/'.$id.'/edit');}
    public function approve(int $id):Response{Csrf::verify((string)($_POST['_csrf']??''));try{$this->service->approve($id,Auth::id()??0);Session::put('assessment_message','Assessment approved.');}catch(InvalidArgumentException|RuntimeException $e){Session::put('assessment_error',$e->getMessage());}return Response::redirect('/crm/public/assessments/'.$id.'/edit');}
    private function therapistId():?int{if(!Auth::hasRole('THERAPIST'))return null;$id=$this->assignments->therapistIdForUser(Auth::id()??0);if($id===null)throw new RuntimeException('Your therapist profile is not active.',403);return $id;}
    private function authorize(array $a,?int $tid):void{if($tid!==null&&!$this->service->canTherapistAccess($a,$tid))throw new RuntimeException('You do not have permission to access this assessment.',403);}
}
