<?php

declare(strict_types=1);
require_once dirname(__DIR__) . '/bootstrap.php';
require DENTAL_ROOT . '/app/bootstrap.php';
header('Content-Type: application/json; charset=utf-8');
if(!current_user()){http_response_code(401);echo json_encode(['ok'=>false,'message'=>'Sign in again.']);exit;}
enforce_task_context_page();
if(!active_role_is('dentist')){http_response_code(403);echo json_encode(['ok'=>false,'message'=>'Only the assigned dentist can autosave this encounter.']);exit;}
try{
    verify_csrf();require_doctor_workflow_schema();$id=(int)($_POST['encounter_id']??0);
    $stmt=db()->prepare('SELECT dentist_user_id,status FROM `' . table('clinical_encounters') . '` WHERE id=?');$stmt->execute([$id]);$row=$stmt->fetch();
    if(!$row||(int)$row['dentist_user_id']!==(int)current_user()['id']||$row['status']==='finalized')throw new RuntimeException('This encounter cannot be autosaved.');
    $fields=['chief_complaint','examination','diagnosis','treatment_plan','procedure_done','soap_note','prescription'];$values=[];foreach($fields as $field)$values[$field]=trim((string)($_POST[$field]??''));$follow=trim((string)($_POST['follow_up_date']??''))?:null;
    db()->prepare('UPDATE `' . table('clinical_encounters') . '` SET chief_complaint=?,examination=?,diagnosis=?,treatment_plan=?,procedure_done=?,soap_note=?,prescription=?,follow_up_date=?,updated_at=NOW(),autosaved_at=NOW() WHERE id=?')->execute([$values['chief_complaint'],$values['examination'],$values['diagnosis'],$values['treatment_plan'],$values['procedure_done'],$values['soap_note'],$values['prescription'],$follow,$id]);
    echo json_encode(['ok'=>true,'saved_at'=>date('g:i A')]);
}catch(Throwable $e){http_response_code(422);echo json_encode(['ok'=>false,'message'=>$e->getMessage()]);}
