<?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\AssignmentService;
use App\Services\TreatmentPlanService;
use InvalidArgumentException;
use RuntimeException;
final class TreatmentPlanController extends Controller
{
    public function __construct(private ?TreatmentPlanService $service=null,private ?AssignmentService $assignments=null){$this->service??=new TreatmentPlanService();$this->assignments??=new AssignmentService();}
    public function index():Response{$tid=$this->therapistId();$filters=['search'=>(string)($_GET['search']??''),'status'=>(string)($_GET['status']??''),'page'=>(int)($_GET['page']??1)];return $this->view('treatment-plans/index',['pageTitle'=>'Treatment Plans','pageDescription'=>'Treatment goals, interventions and review plans.','plans'=>$this->service->list($filters,$tid),'filters'=>$filters]);}
    public function createForm():Response{$tid=$this->therapistId();return $this->view('treatment-plans/form',['pageTitle'=>'New Treatment Plan','pageDescription'=>'Create a treatment plan for a currently assigned patient.','plan'=>null,'csrf'=>Csrf::token(),'form'=>Session::pull('treatment_form')??[],'error'=>Session::pull('treatment_error'),'message'=>Session::pull('treatment_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('treatment_message','Treatment plan created successfully.');return Response::redirect('/crm/public/treatment-plans/'.$id.'/edit');}catch(InvalidArgumentException|RuntimeException $e){Session::put('treatment_error',$e->getMessage());Session::put('treatment_form',$_POST);return Response::redirect('/crm/public/treatment-plans/create');}}
    public function editForm(int $id):Response{$tid=$this->therapistId();$p=$this->service->find($id);$this->authorize($p,$tid);return $this->view('treatment-plans/form',['pageTitle'=>'Treatment Plan #'.$id,'pageDescription'=>'Treatment plan record.','plan'=>$p,'csrf'=>Csrf::token(),'form'=>Session::pull('treatment_form')??[],'error'=>Session::pull('treatment_error'),'message'=>Session::pull('treatment_message'),...$this->service->formData($tid),'therapistLocked'=>$tid!==null]);}
    public function update(int $id):Response{Csrf::verify((string)($_POST['_csrf']??''));$tid=$this->therapistId();try{$p=$this->service->find($id);$this->authorize($p,$tid);$this->service->update($id,$_POST,Auth::id()??0,$tid);Session::put('treatment_message','Treatment plan updated successfully.');}catch(InvalidArgumentException|RuntimeException $e){Session::put('treatment_error',$e->getMessage());Session::put('treatment_form',$_POST);}return Response::redirect('/crm/public/treatment-plans/'.$id.'/edit');}
    public function status(int $id):Response{Csrf::verify((string)($_POST['_csrf']??''));$tid=$this->therapistId();try{$this->service->setStatus($id,(string)($_POST['status']??''),Auth::id()??0,$tid);Session::put('treatment_message','Treatment plan status updated.');}catch(InvalidArgumentException|RuntimeException $e){Session::put('treatment_error',$e->getMessage());}return Response::redirect('/crm/public/treatment-plans/'.$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 $p,?int $tid):void{if($tid!==null&&!$this->service->canTherapistAccess($p,$tid))throw new RuntimeException('You do not have permission to access this treatment plan.',403);}
}
