<?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\PatientService;
use App\Services\AssignmentService;
use RuntimeException;
use InvalidArgumentException;

final class PatientController extends Controller
{
    public function __construct(private ?PatientService $service=null, private ?AssignmentService $assignments=null){$this->service??=new PatientService(); $this->assignments??=new AssignmentService();}

    private function denyTherapistManagement(): void
    {
        if (Auth::hasRole('THERAPIST')) {
            throw new RuntimeException('Therapists cannot manage patient records. Open patients from your assigned sessions.', 403);
        }
    }

    public function index(): Response
    {
        $this->denyTherapistManagement();
        $therapistId = null;
        if (Auth::hasRole('THERAPIST')) {
            $therapistId = $this->assignments->therapistIdForUser(Auth::id() ?? 0);
            if ($therapistId === null) { throw new RuntimeException('Your therapist profile is not active.', 403); }
        }
        $result=$this->service->list($_GET, $therapistId);
        return $this->view('patients/index',['pageTitle'=>'Patients','pageDescription'=>'Manage patient records and demographics.','patients'=>$result['items'],'pagination'=>$result,'filters'=>['search'=>(string)($_GET['search']??''),'status'=>(string)($_GET['status']??'')],'message'=>Session::pull('patient_message'),'error'=>Session::pull('patient_error')]);
    }

    public function createForm(): Response
    {
        $this->denyTherapistManagement();
        return $this->view('patients/form',['pageTitle'=>'Create Patient','patient'=>null,'csrf'=>Csrf::token(),'error'=>Session::pull('patient_error'),'form'=>Session::pull('patient_form')]);
    }

    public function create(): Response
    {
        $this->denyTherapistManagement();
        Csrf::verify((string)($_POST['_csrf']??''));
        try { $id=$this->service->create($_POST,Auth::id()??0); Session::put('patient_message','Patient created successfully.'); return Response::redirect('/crm/public/patients/'.$id.'/edit'); }
        catch(InvalidArgumentException $e){Session::put('patient_error',$e->getMessage());Session::put('patient_form',$_POST);return Response::redirect('/crm/public/patients/create');}
    }

    public function editForm(int $id): Response
    {
        $this->denyTherapistManagement();
        return $this->view('patients/form',['pageTitle'=>'Edit Patient','patient'=>$this->service->find($id),'csrf'=>Csrf::token(),'error'=>Session::pull('patient_error'),'message'=>Session::pull('patient_message'),'form'=>Session::pull('patient_form')]);
    }

    public function delete(int $id): Response
    {
        $this->denyTherapistManagement();
        Csrf::verify((string)($_POST['_csrf']??''));
        try {
            $this->service->delete($id, Auth::id()??0);
            Session::put('patient_message','Patient record archived successfully.');
        } catch (InvalidArgumentException $e) {
            Session::put('patient_error',$e->getMessage());
        }
        return Response::redirect('/crm/public/patients');
    }

    public function update(int $id): Response
    {
        $this->denyTherapistManagement();
        Csrf::verify((string)($_POST['_csrf']??''));
        try {$this->service->update($id,$_POST,Auth::id()??0);Session::put('patient_message','Patient updated successfully.');}
        catch(InvalidArgumentException $e){Session::put('patient_error',$e->getMessage());Session::put('patient_form',$_POST);}
        return Response::redirect('/crm/public/patients/'.$id.'/edit');
    }
}
