<?php
require DENTAL_ROOT . '/app/bootstrap.php';
require_login();
require_documentation_schema();
require_permission('clinical.view', ['super_admin','clinic_admin','dentist','dental_assistant']);
require DENTAL_ROOT . '/app/layout.php';
require DENTAL_ROOT . '/app/module_helpers.php';
require_once DENTAL_ROOT . '/app/tooth_model.php';

$pdo = db();
$canEdit = clinical_record_edit_allowed(['dentist']);
$currentUserId = (int) (current_user()['id'] ?? 0);
$actualRole = active_role();
$taskRole = $actualRole;
$patients = patient_options();
$dentists = dentist_options();
$patientId = (int) ($_GET['patient_id'] ?? $_POST['patient_id'] ?? 0);
$planId = (int) ($_GET['plan_id'] ?? $_POST['plan_id'] ?? 0);
$findingId = (int) ($_GET['finding_id'] ?? $_POST['odontogram_entry_id'] ?? 0);
$treatmentLinkReady = schema_table_exists(table('odontogram_entries'))
    && schema_table_exists(table('dental_condition_catalog'))
    && schema_column_exists(table('treatment_plan_items'), 'odontogram_entry_id')
    && schema_column_exists(table('odontogram_entries'), 'treatment_plan_item_id');

if ($patientId) {
    require_patient($patientId);
}

function treatment_finding(PDO $pdo, int $findingId, int $patientId = 0): ?array
{
    if ($findingId < 1) return null;
    $sql = 'SELECT o.*,COALESCE(c.name,d.diagnosis_name) condition_name,COALESCE(c.category,IF(d.id IS NOT NULL,"diagnosis",o.finding_type)) category,c.recommended_procedure,c.description condition_description,'
        . 'd.diagnosis_name,d.diagnosis_status '
        . 'FROM `' . table('odontogram_entries') . '` o '
        . 'LEFT JOIN `' . table('dental_condition_catalog') . '` c ON c.code=o.condition_code '
        . 'LEFT JOIN `' . table('diagnoses') . '` d ON d.id=o.diagnosis_id '
        . 'WHERE o.id=?' . ($patientId > 0 ? ' AND o.patient_id=?' : '') . ' LIMIT 1';
    $stmt = $pdo->prepare($sql);
    $stmt->execute($patientId > 0 ? [$findingId, $patientId] : [$findingId]);
    $row = $stmt->fetch();
    return $row ?: null;
}

function treatment_priority_from_severity(?string $severity): string
{
    return match ((string) $severity) {
        'critical' => 'emergency',
        'severe' => 'urgent',
        'moderate' => 'important',
        default => 'routine',
    };
}

function treatment_plan_handoff_schema_ready(): bool
{
    return schema_table_exists(table('treatment_plan_reassignments'));
}

function treatment_plan_handoff_locked(PDO $pdo, int $planId): bool
{
    $stmt=$pdo->prepare('SELECT COUNT(*) FROM `' . table('treatment_plan_items') . '` WHERE treatment_plan_id=? AND status="completed"');
    $stmt->execute([$planId]);
    if((int)$stmt->fetchColumn()>0)return true;
    if(schema_table_exists(table('consent_forms'))){
        $stmt=$pdo->prepare('SELECT COUNT(*) FROM `' . table('consent_forms') . '` c LEFT JOIN `' . table('treatment_plan_items') . '` i ON i.id=c.treatment_plan_item_id WHERE (c.treatment_plan_id=? OR i.treatment_plan_id=?) AND c.status="signed"');
        $stmt->execute([$planId,$planId]);
        if((int)$stmt->fetchColumn()>0)return true;
    }
    return false;
}

function treatment_required_privileges(PDO $pdo, int $planId, string $requestType): array
{
    $codes=['consultation','diagnosis'];
    if($requestType==='transfer')$codes[]='clinical_note_finalization';
    $stmt=$pdo->prepare('SELECT procedure_code,procedure_name FROM `' . table('treatment_plan_items') . '` WHERE treatment_plan_id=? AND status NOT IN ("declined","cancelled")');
    $stmt->execute([$planId]);
    foreach($stmt->fetchAll() as $item){
        $text=strtolower(trim((string)($item['procedure_code']??'').' '.(string)($item['procedure_name']??'')));
        $map=[
            'surgical_extraction'=>['surgical extraction','impacted','odontectomy'],
            'simple_extraction'=>['extraction','extract'],
            'root_canal'=>['root canal','endodont'],
            'orthodontics'=>['orthodont','braces','archwire'],
            'implant_placement'=>['implant'],
            'prosthodontics'=>['crown','bridge','denture','prosthodont'],
            'periodontal_surgery'=>['periodontal surgery','flap surgery','gingivectomy'],
            'oral_prophylaxis'=>['prophylaxis','oral cleaning','scaling'],
            'restoration'=>['restoration','filling','composite','glass ionomer'],
            'pediatric_treatment'=>['pediatric','pulpotomy'],
            'sedation'=>['sedation'],
        ];
        foreach($map as $code=>$needles){foreach($needles as $needle){if(str_contains($text,$needle)){$codes[]=$code;break 2;}}}
    }
    return array_values(array_unique($codes));
}

function treatment_assert_eligible_dentist(PDO $pdo, int $dentistId, int $branchId, int $planId, string $requestType): array
{
    if($dentistId<1)throw new RuntimeException('Select the receiving Dentist.');
    $eligible=null;
    foreach(dentist_options($branchId>0?$branchId:null) as $doctor){if((int)$doctor['id']===$dentistId){$eligible=$doctor;break;}}
    if(!$eligible)throw new RuntimeException('The receiving Dentist is not active or authorized for this clinic branch.');
    require_dentist_credentials_verified($dentistId);
    foreach(treatment_required_privileges($pdo,$planId,$requestType) as $code){
        $reason=null;
        if(!dentist_has_clinical_privilege($dentistId,$code,$reason))throw new RuntimeException('The receiving Dentist is not qualified for this plan: '.($reason?:$code.'.'));
    }
    return $eligible;
}

function treatment_recalculate_total(PDO $pdo, int $planId): void
{
    $pdo->prepare(
        'UPDATE `' . table('treatment_plans') . '` '
        . 'SET estimate_total=(SELECT COALESCE(SUM(estimated_fee),0) FROM `' . table('treatment_plan_items') . '` WHERE treatment_plan_id=?),updated_at=NOW() '
        . 'WHERE id=?'
    )->execute([$planId, $planId]);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $action = (string) ($_POST['action'] ?? '');

    if (in_array($action,['request_handoff','decide_handoff','cancel_handoff'],true)) {
        if(!treatment_plan_handoff_schema_ready())throw new RuntimeException('Apply Version 0.5.9.8.2 before using treatment-plan consultation or transfer.');
        if($actualRole!==$taskRole)throw new RuntimeException('Return to your own task workspace before processing a clinical handoff.');

        if($action==='request_handoff'){
            if(!in_array($actualRole,['dentist','clinic_admin','super_admin'],true))throw new RuntimeException('Only the responsible Dentist or an Administrator may request a treatment-plan handoff.');
            $planId=(int)($_POST['plan_id']??0);$targetId=(int)($_POST['to_dentist_user_id']??0);$requestType=(string)($_POST['request_type']??'consultation');$reason=trim((string)($_POST['reason']??''));
            if(!in_array($requestType,['consultation','transfer'],true))throw new RuntimeException('Choose consultation or transfer.');
            if($reason==='')throw new RuntimeException('Enter the clinical or operational reason for this handoff.');
            $pdo->beginTransaction();
            try{
                $stmt=$pdo->prepare('SELECT p.*,pt.branch_id patient_branch_id FROM `' . table('treatment_plans') . '` p JOIN `' . table('patients') . '` pt ON pt.id=p.patient_id WHERE p.id=? LIMIT 1 FOR UPDATE');$stmt->execute([$planId]);$handoffPlan=$stmt->fetch();
                if(!$handoffPlan)throw new RuntimeException('Treatment plan not found.');
                require_patient((int)$handoffPlan['patient_id']);
                $ownerId=(int)($handoffPlan['dentist_user_id']??0);
                if($actualRole==='dentist'&&$ownerId!==$currentUserId)throw new RuntimeException('Only the responsible Dentist may request a consultation or transfer for this plan.');
                if($targetId===$ownerId)throw new RuntimeException('Select a different receiving Dentist.');
                if(in_array((string)$handoffPlan['status'],['completed','cancelled','expired'],true))throw new RuntimeException('This treatment plan can no longer be reassigned.');
                if($requestType==='transfer'&&treatment_plan_handoff_locked($pdo,$planId))throw new RuntimeException('A plan with signed consent or completed treatment items cannot be transferred. Create a new plan or signed clinical addendum instead.');
                $branchId=(int)($handoffPlan['branch_id']??$handoffPlan['patient_branch_id']??0);
                treatment_assert_eligible_dentist($pdo,$targetId,$branchId,$planId,$requestType);
                $pending=$pdo->prepare('SELECT id FROM `' . table('treatment_plan_reassignments') . '` WHERE treatment_plan_id=? AND status="pending" LIMIT 1 FOR UPDATE');$pending->execute([$planId]);if($pending->fetchColumn())throw new RuntimeException('This treatment plan already has a pending consultation or transfer request.');
                $stmt=$pdo->prepare('INSERT INTO `' . table('treatment_plan_reassignments') . '` (treatment_plan_id,patient_id,branch_id,request_type,from_dentist_user_id,to_dentist_user_id,reason,status,requested_by,requested_at,created_at) VALUES (?,?,?,?,?,?,?,"pending",?,NOW(),NOW())');
                $stmt->execute([$planId,(int)$handoffPlan['patient_id'],$branchId?:null,$requestType,$ownerId,$targetId,$reason,$currentUserId]);$handoffId=(int)$pdo->lastInsertId();
                audit('treatment_plan_handoff_requested','treatment_plan_handoff',$handoffId,['plan_id'=>$planId,'type'=>$requestType,'from_dentist'=>$ownerId,'to_dentist'=>$targetId,'reason'=>$reason]);
                workflow_event((int)$handoffPlan['patient_id'],'treatment_plan_handoff_requested',ucfirst($requestType).' requested',['treatment_plan_id'=>$planId,'handoff_id'=>$handoffId],$reason);
                $pdo->commit();
            }catch(Throwable $exception){if($pdo->inTransaction())$pdo->rollBack();throw $exception;}
            module_return('treatment.php?patient_id='.(int)$handoffPlan['patient_id'].'&plan_id='.$planId,'success',ucfirst($requestType).' request sent to the receiving Dentist. Responsibility has not changed until acceptance.');
        }

        if($action==='decide_handoff'){
            if($actualRole!=='dentist')throw new RuntimeException('Only the receiving Dentist may accept or decline this handoff.');
            $handoffId=(int)($_POST['handoff_id']??0);$decision=(string)($_POST['decision']??'');$note=trim((string)($_POST['decision_note']??''));
            if(!in_array($decision,['accepted','declined'],true))throw new RuntimeException('Choose accept or decline.');
            $pdo->beginTransaction();
            try{
                $stmt=$pdo->prepare('SELECT h.*,p.status plan_status,p.dentist_user_id current_owner,pt.branch_id patient_branch_id FROM `' . table('treatment_plan_reassignments') . '` h JOIN `' . table('treatment_plans') . '` p ON p.id=h.treatment_plan_id JOIN `' . table('patients') . '` pt ON pt.id=h.patient_id WHERE h.id=? LIMIT 1 FOR UPDATE');$stmt->execute([$handoffId]);$handoff=$stmt->fetch();
                if(!$handoff||$handoff['status']!=='pending')throw new RuntimeException('This handoff request is no longer pending.');
                if((int)$handoff['to_dentist_user_id']!==$currentUserId)throw new RuntimeException('This handoff is assigned to another Dentist.');
                require_patient((int)$handoff['patient_id']);
                if($decision==='accepted'){
                    $branchId=(int)($handoff['branch_id']??$handoff['patient_branch_id']??0);
                    treatment_assert_eligible_dentist($pdo,$currentUserId,$branchId,(int)$handoff['treatment_plan_id'],(string)$handoff['request_type']);
                    if($handoff['request_type']==='transfer'){
                        if(in_array((string)$handoff['plan_status'],['completed','cancelled','expired'],true)||treatment_plan_handoff_locked($pdo,(int)$handoff['treatment_plan_id']))throw new RuntimeException('The treatment plan changed and can no longer be transferred.');
                        $update=$pdo->prepare('UPDATE `' . table('treatment_plans') . '` SET dentist_user_id=?,updated_at=NOW() WHERE id=? AND dentist_user_id=?');$update->execute([$currentUserId,(int)$handoff['treatment_plan_id'],(int)$handoff['from_dentist_user_id']]);if($update->rowCount()!==1)throw new RuntimeException('The responsible Dentist changed before this transfer was accepted.');
                    }
                }
                $update=$pdo->prepare('UPDATE `' . table('treatment_plan_reassignments') . '` SET status=?,decided_by=?,decided_at=NOW(),decision_note=?,updated_at=NOW() WHERE id=? AND status="pending"');$update->execute([$decision,$currentUserId,$note?:null,$handoffId]);if($update->rowCount()!==1)throw new RuntimeException('The handoff was resolved in another session.');
                audit('treatment_plan_handoff_'.$decision,'treatment_plan_handoff',$handoffId,['plan_id'=>(int)$handoff['treatment_plan_id'],'type'=>$handoff['request_type'],'decision_note'=>$note]);
                workflow_event((int)$handoff['patient_id'],'treatment_plan_handoff_'.$decision,ucfirst((string)$handoff['request_type']).' '.$decision,['treatment_plan_id'=>(int)$handoff['treatment_plan_id'],'handoff_id'=>$handoffId],$note);
                $pdo->commit();
            }catch(Throwable $exception){if($pdo->inTransaction())$pdo->rollBack();throw $exception;}
            module_return('treatment.php?patient_id='.(int)$handoff['patient_id'].'&plan_id='.(int)$handoff['treatment_plan_id'],'success','Handoff request '.$decision.'.'.($decision==='accepted'&&$handoff['request_type']==='transfer'?' You are now the responsible Dentist.':''));
        }

        if($action==='cancel_handoff'){
            $handoffId=(int)($_POST['handoff_id']??0);$stmt=$pdo->prepare('SELECT * FROM `' . table('treatment_plan_reassignments') . '` WHERE id=? LIMIT 1');$stmt->execute([$handoffId]);$handoff=$stmt->fetch();if(!$handoff||$handoff['status']!=='pending')throw new RuntimeException('This handoff request is no longer pending.');
            $allowed=in_array($actualRole,['super_admin','clinic_admin'],true)||(int)$handoff['requested_by']===$currentUserId||(int)$handoff['from_dentist_user_id']===$currentUserId;if(!$allowed)throw new RuntimeException('You cannot cancel this handoff request.');
            $update=$pdo->prepare('UPDATE `' . table('treatment_plan_reassignments') . '` SET status="cancelled",decided_by=?,decided_at=NOW(),decision_note=?,updated_at=NOW() WHERE id=? AND status="pending"');$update->execute([$currentUserId,trim((string)($_POST['decision_note']??''))?:'Cancelled before acceptance',$handoffId]);if($update->rowCount()!==1)throw new RuntimeException('The handoff was resolved in another session.');
            audit('treatment_plan_handoff_cancelled','treatment_plan_handoff',$handoffId,['plan_id'=>(int)$handoff['treatment_plan_id']]);
            module_return('treatment.php?patient_id='.(int)$handoff['patient_id'].'&plan_id='.(int)$handoff['treatment_plan_id'],'success','Handoff request cancelled.');
        }
    }

    require_clinical_record_editor(['dentist']);

    if ($action === 'create_plan') {
        $patientId = (int) ($_POST['patient_id'] ?? 0);
        $patientRecord=require_patient($patientId);
        $dentist = $currentUserId;
        require_dentist_credentials_verified($dentist);
        $stmt = $pdo->prepare(
            'INSERT INTO `' . table('treatment_plans') . '` '
            . '(patient_id,branch_id,encounter_id,dentist_user_id,title,phase,status,version_no,estimate_total,expires_at,notes,created_at) '
            . 'VALUES (?,?,?,?,?,?,"draft",1,0,?,?,NOW())'
        );
        $stmt->execute([
            $patientId,
            (int)($patientRecord['branch_id']??0)?:null,
            (int) ($_POST['encounter_id'] ?? 0) ?: null,
            $dentist,
            trim((string) ($_POST['title'] ?? '')),
            trim((string) ($_POST['phase'] ?? '')) ?: null,
            trim((string) ($_POST['expires_at'] ?? '')) ?: null,
            trim((string) ($_POST['notes'] ?? '')) ?: null,
        ]);
        $planId = (int) $pdo->lastInsertId();
        audit('treatment_plan_created', 'treatment_plan', $planId, ['patient_id'=>$patientId]);
        $return = 'treatment.php?patient_id=' . $patientId . '&plan_id=' . $planId;
        $postedFinding = (int) ($_POST['finding_id'] ?? 0);
        if ($postedFinding > 0) $return .= '&finding_id=' . $postedFinding;
        module_return($return, 'success', 'Treatment plan created. Add the recommended procedure and sequencing.');
    }

    if ($action === 'add_item') {
        if (!$treatmentLinkReady) throw new RuntimeException('Apply Version 0.5.8.6 before linking tooth findings to treatment plans.');
        $planId = (int) ($_POST['plan_id'] ?? 0);
        $planScope = module_require_record_scope($pdo, 'treatment_plans', $planId, 'patient_id', 'dentist_user_id', true);
        $patientId = (int) $planScope['patient_id'];
        $findingId = (int) ($_POST['odontogram_entry_id'] ?? 0);
        $finding = $findingId ? treatment_finding($pdo, $findingId, $patientId) : null;
        if ($findingId && !$finding) throw new RuntimeException('The linked tooth finding does not belong to this patient.');
        if ($finding && ($finding['status'] ?? '') !== 'active') throw new RuntimeException('Only an active tooth finding can be added to a new treatment item.');

        $toothNumber = trim((string) ($_POST['tooth_number'] ?? '')) ?: ($finding['tooth_number'] ?? null);
        $surfaces = trim((string) ($_POST['surfaces'] ?? '')) ?: ($finding['surface'] ?? null);
        $toothRegion = trim((string) ($_POST['tooth_region'] ?? '')) ?: trim((string) (($toothNumber ?: '') . ($surfaces ? ' · ' . $surfaces : '')));
        $diagnosisId = (int) ($_POST['diagnosis_id'] ?? 0) ?: (($finding && !empty($finding['diagnosis_id'])) ? (int) $finding['diagnosis_id'] : null);
        $diagnosis = trim((string) ($_POST['diagnosis'] ?? '')) ?: ($finding['diagnosis_name'] ?? $finding['condition_name'] ?? null);
        if (!schema_column_exists(table('treatment_plan_items'), 'service_id') || !schema_column_exists(table('service_catalog'), 'fee_status')) {
            throw new RuntimeException('Apply Version 0.5.9.8.15 before adding treatment-plan procedures.');
        }
        $serviceId = (int) ($_POST['service_id'] ?? 0);
        if ($serviceId < 1) throw new RuntimeException('Select the proposed procedure from the approved service catalogue.');
        $branchId = (int)($planScope['branch_id'] ?? 0);
        $serviceStmt = $pdo->prepare('SELECT * FROM `' . table('service_catalog') . '` WHERE id=? AND is_active=1 AND (branch_id=? OR branch_id IS NULL) LIMIT 1');
        $serviceStmt->execute([$serviceId,$branchId]);
        $service = $serviceStmt->fetch();
        if (!$service) throw new RuntimeException('The selected service is inactive or unavailable for this clinic branch.');
        $feeStatus = (string)($service['fee_status'] ?? 'unconfigured');
        $estimatedFee = $feeStatus === 'billable' ? round((float)($service['standard_fee'] ?? 0),2) : 0.0;
        if ($feeStatus === 'billable' && $estimatedFee <= 0) throw new RuntimeException('The selected service has no positive approved fee. Ask an Administrator to correct the service catalogue.');
        if ($feeStatus === 'no_charge' && (mb_strlen(trim((string)($service['no_charge_reason'] ?? ''))) < 5 || empty($service['fee_authorized_by']) || empty($service['fee_authorized_at']))) {
            throw new RuntimeException('The selected service has an incomplete no-charge authorization. Ask an Administrator to correct it.');
        }
        if (!in_array($feeStatus,['billable','no_charge'],true)) throw new RuntimeException('The selected service fee is not configured. Set a positive fee or authorize it as no-charge before adding it to a treatment plan.');
        $procedureName = trim((string)$service['name']);

        $stmt = $pdo->prepare(
            'INSERT INTO `' . table('treatment_plan_items') . '` '
            . '(treatment_plan_id,service_id,diagnosis,diagnosis_id,odontogram_entry_id,tooth_region,tooth_number,surfaces,procedure_code,procedure_name,priority,sequence_no,sessions,duration_minutes,estimated_fee,fee_status,no_charge_reason,fee_authorized_by,fee_authorized_at,status,clinical_rationale,prognosis,consent_status,notes,created_at) '
            . 'VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,"proposed",?,?,?,?,NOW())'
        );
        $stmt->execute([
            $planId,
            $serviceId,
            $diagnosis ?: null,
            $diagnosisId,
            $findingId ?: null,
            $toothRegion ?: null,
            $toothNumber ?: null,
            $surfaces ?: null,
            trim((string) ($_POST['procedure_code'] ?? '')) ?: null,
            $procedureName,
            in_array((string) ($_POST['priority'] ?? ''), ['routine','important','urgent','emergency'], true) ? (string) $_POST['priority'] : 'routine',
            max(1, (int) ($_POST['sequence_no'] ?? 1)),
            max(1, (int) ($_POST['sessions'] ?? 1)),
            max(5, (int) ($_POST['duration_minutes'] ?? (int)($service['duration_minutes'] ?? 30))),
            $estimatedFee,
            $feeStatus,
            $feeStatus === 'no_charge' ? trim((string)$service['no_charge_reason']) : null,
            (int)($service['fee_authorized_by'] ?? 0) ?: null,
            $service['fee_authorized_at'] ?? null,
            trim((string) ($_POST['clinical_rationale'] ?? '')) ?: null,
            trim((string) ($_POST['prognosis'] ?? '')) ?: null,
            'not_requested',
            trim((string) ($_POST['notes'] ?? '')) ?: null,
        ]);
        $itemId = (int) $pdo->lastInsertId();
        if ($findingId) {
            $pdo->prepare('UPDATE `' . table('odontogram_entries') . '` SET treatment_plan_item_id=? WHERE id=? AND patient_id=?')
                ->execute([$itemId, $findingId, $patientId]);
        }
        treatment_recalculate_total($pdo, $planId);
        audit('treatment_plan_item_added', 'treatment_plan_item', $itemId, ['plan_id'=>$planId,'finding_id'=>$findingId ?: null]);
        module_return('treatment.php?patient_id=' . $patientId . '&plan_id=' . $planId, 'success', $findingId ? 'Tooth finding added to the treatment plan.' : 'Treatment item added.');
    }

    if ($action === 'update_status') {
        $planId = (int) ($_POST['plan_id'] ?? 0);
        $planScope = module_require_record_scope($pdo, 'treatment_plans', $planId, 'patient_id', 'dentist_user_id', true);
        $status = (string) ($_POST['status'] ?? 'draft');
        $allowed = ['draft','presented','partially_accepted','accepted','scheduled','in_progress','deferred','declined','cancelled','expired','revised'];
        if ($status === 'completed') throw new RuntimeException('A treatment plan becomes completed only after every active item is completed through a finalized clinical encounter.');
        if (!in_array($status, $allowed, true)) throw new RuntimeException('Invalid treatment-plan status.');
        $accepted = in_array($status, ['accepted','partially_accepted'], true) ? date('Y-m-d H:i:s') : null;
        $pdo->prepare('UPDATE `' . table('treatment_plans') . '` SET status=?,accepted_at=COALESCE(?,accepted_at),updated_at=NOW() WHERE id=?')
            ->execute([$status, $accepted, $planId]);
        audit('treatment_plan_status_updated', 'treatment_plan', $planId, ['status'=>$status]);
        module_return('treatment.php?patient_id=' . (int) $planScope['patient_id'] . '&plan_id=' . $planId, 'success', 'Treatment plan status updated.');
    }

    if ($action === 'update_item') {
        $itemId = (int) ($_POST['item_id'] ?? 0);
        $stmt = $pdo->prepare(
            'SELECT i.*,p.id plan_id,p.patient_id,p.encounter_id plan_encounter_id '
            . 'FROM `' . table('treatment_plan_items') . '` i '
            . 'JOIN `' . table('treatment_plans') . '` p ON p.id=i.treatment_plan_id WHERE i.id=? LIMIT 1'
        );
        $stmt->execute([$itemId]);
        $item = $stmt->fetch();
        if (!$item) throw new RuntimeException('Treatment item not found.');
        module_require_record_scope($pdo, 'treatment_plans', (int) $item['plan_id'], 'patient_id', 'dentist_user_id', true);
        $status = (string) ($_POST['status'] ?? 'proposed');
        if ($status === 'completed') {
            throw new RuntimeException('A treatment item can be completed only by finalizing the linked procedure in the assigned Dentist clinical workspace.');
        }
        if ((string)$item['status'] === 'completed') {
            throw new RuntimeException('A completed treatment item is part of a finalized clinical record and cannot be changed from treatment planning. Use a signed clinical addendum when correction is required.');
        }
        $allowed = ['proposed','accepted','scheduled','in_progress','deferred','declined','cancelled'];
        if (!in_array($status, $allowed, true)) throw new RuntimeException('Invalid treatment-item status.');
        $oldStatus = (string) $item['status'];

        $pdo->beginTransaction();
        try {
            $pdo->prepare('UPDATE `' . table('treatment_plan_items') . '` SET status=?,updated_at=NOW() WHERE id=? AND status<>"completed"')
                ->execute([$status,$itemId]);
            if ($treatmentLinkReady && !empty($item['odontogram_entry_id'])) {
                $finding = treatment_finding($pdo, (int) $item['odontogram_entry_id'], (int) $item['patient_id']);
                if ($finding) {
                    if ($status === 'in_progress') {
                        $pdo->prepare('UPDATE `' . table('odontogram_entries') . '` SET chart_layer="in_progress",treatment_plan_item_id=? WHERE id=? AND status="active"')
                            ->execute([$itemId, (int) $finding['id']]);
                    } elseif (in_array($status, ['declined','cancelled'], true)) {
                        $pdo->prepare('UPDATE `' . table('odontogram_entries') . '` SET chart_layer="existing" WHERE id=? AND status="active"')
                            ->execute([(int) $finding['id']]);
                    }
                }
            }
            treatment_recalculate_total($pdo, (int) $item['plan_id']);
            $pdo->commit();
        } catch (Throwable $exception) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            throw $exception;
        }
        audit('treatment_item_status_updated', 'treatment_plan_item', $itemId, ['from'=>$oldStatus,'to'=>$status,'completion_source'=>'clinical_encounter_only']);
        module_return('treatment.php?patient_id=' . (int) $item['patient_id'] . '&plan_id=' . (int) $item['plan_id'], 'success', 'Treatment item updated. Completion remains controlled by the finalized clinical encounter.');
    }

}

$linkedFinding = null;
if ($findingId > 0) {
    if (!$treatmentLinkReady) throw new RuntimeException('Apply Version 0.5.8.6 before opening a chart finding in treatment planning.');
    $linkedFinding = treatment_finding($pdo, $findingId, $patientId);
    if (!$linkedFinding) throw new RuntimeException('The selected tooth finding was not found for this patient.');
    $patientId = (int) $linkedFinding['patient_id'];
}

$plans = [];
$plan = null;
$items = [];
$itemTasks = [];
$handoffs = [];
$handoffDentists = [];
$canEditPlan = false;
if ($patientId) {
    $stmt = $pdo->prepare(
        'SELECT p.*,u.name dentist FROM `' . table('treatment_plans') . '` p '
        . 'LEFT JOIN `' . table('users') . '` u ON u.id=p.dentist_user_id '
        . 'WHERE p.patient_id=? ORDER BY p.created_at DESC'
    );
    $stmt->execute([$patientId]);
    $plans = $stmt->fetchAll();
    if (!$planId && $plans) $planId = (int) $plans[0]['id'];
}
if ($planId) {
    $stmt = $pdo->prepare(
        'SELECT p.*,pt.branch_id patient_branch_id,CONCAT(pt.first_name," ",pt.last_name) patient,u.name dentist '
        . 'FROM `' . table('treatment_plans') . '` p JOIN `' . table('patients') . '` pt ON pt.id=p.patient_id '
        . 'LEFT JOIN `' . table('users') . '` u ON u.id=p.dentist_user_id WHERE p.id=? LIMIT 1'
    );
    $stmt->execute([$planId]);
    $plan = $stmt->fetch();
    if ($plan) {
        require_patient((int)$plan['patient_id']);
        $patientId = (int) $plan['patient_id'];
        $itemSql = $treatmentLinkReady
            ? 'SELECT i.*,o.condition_code,o.severity finding_severity,c.name finding_name '
                . 'FROM `' . table('treatment_plan_items') . '` i '
                . 'LEFT JOIN `' . table('odontogram_entries') . '` o ON o.id=i.odontogram_entry_id '
                . 'LEFT JOIN `' . table('dental_condition_catalog') . '` c ON c.code=o.condition_code '
                . 'WHERE i.treatment_plan_id=? ORDER BY i.sequence_no,i.id'
            : 'SELECT i.*,NULL condition_code,NULL finding_severity,NULL finding_name FROM `' . table('treatment_plan_items') . '` i WHERE i.treatment_plan_id=? ORDER BY i.sequence_no,i.id';
        $stmt = $pdo->prepare($itemSql);
        $stmt->execute([$planId]);
        $items = $stmt->fetchAll();
        if(clinical_task_assignment_schema_ready()){
            $taskStmt=$pdo->prepare('SELECT t.*,u.name assigned_dentist FROM `' . table('clinical_task_assignments') . '` t LEFT JOIN `' . table('users') . '` u ON u.id=t.assigned_dentist_user_id WHERE t.treatment_plan_id=? ORDER BY t.requested_at DESC,t.id DESC');
            $taskStmt->execute([$planId]);foreach($taskStmt->fetchAll() as $taskRow){$iid=(int)($taskRow['treatment_plan_item_id']??0);if($iid>0&&!isset($itemTasks[$iid]))$itemTasks[$iid]=$taskRow;}
        }
        $canEditPlan=$canEdit&&(int)($plan['dentist_user_id']??0)===$currentUserId;
        $handoffBranchId=(int)($plan['branch_id']??$plan['patient_branch_id']??0);
        $handoffDentists=dentist_options($handoffBranchId>0?$handoffBranchId:null);
        if(treatment_plan_handoff_schema_ready()){
            $stmt=$pdo->prepare('SELECT h.*,fu.name from_dentist,tu.name to_dentist,ru.name requester,du.name decider FROM `' . table('treatment_plan_reassignments') . '` h LEFT JOIN `' . table('users') . '` fu ON fu.id=h.from_dentist_user_id LEFT JOIN `' . table('users') . '` tu ON tu.id=h.to_dentist_user_id LEFT JOIN `' . table('users') . '` ru ON ru.id=h.requested_by LEFT JOIN `' . table('users') . '` du ON du.id=h.decided_by WHERE h.treatment_plan_id=? ORDER BY h.requested_at DESC,h.id DESC');
            $stmt->execute([$planId]);$handoffs=$stmt->fetchAll();
        }
    }
}

$prefillProcedure = trim((string) ($linkedFinding['recommended_procedure'] ?? ''));
$prefillDiagnosis = trim((string) ($linkedFinding['diagnosis_name'] ?? $linkedFinding['condition_name'] ?? ''));
$prefillTooth = trim((string) ($linkedFinding['tooth_number'] ?? ''));
$prefillSurfaces = trim((string) ($linkedFinding['surface'] ?? ''));
$prefillRationale = trim((string) ($linkedFinding['notes'] ?? $linkedFinding['condition_description'] ?? ''));
$prefillPriority = treatment_priority_from_severity($linkedFinding['severity'] ?? null);
$serviceCatalog = [];
if ($plan && schema_column_exists(table('service_catalog'), 'fee_status')) {
    $catalogStmt = $pdo->prepare(
        'SELECT id,name,duration_minutes,standard_fee,fee_status,no_charge_reason FROM `' . table('service_catalog') . '` '
        . 'WHERE is_active=1 AND fee_status IN ("billable","no_charge") AND (branch_id=? OR branch_id IS NULL) ORDER BY name'
    );
    $catalogStmt->execute([(int)($plan['branch_id'] ?? $plan['patient_branch_id'] ?? 0)]);
    $serviceCatalog = $catalogStmt->fetchAll();
}

render_header('Treatment Plans');
render_module_intro(
    'Phased treatment planning',
    'Convert documented dental findings into sequenced procedures, estimates, consent decisions, and completed chart outcomes.',
    $canEdit ? 'New treatment plan' : null,
    $canEdit ? 'plan-form' : null
);
render_patient_filter($patients, 'treatment.php', $patientId);
?>
<?php if ($linkedFinding): ?>
<section class="card dental-linked-finding">
    <div class="card-head"><div><h2>Source dental finding</h2><p>This clinical finding will remain linked to the treatment item and its final outcome.</p></div><a class="btn ghost" href="odontogram.php?patient_id=<?=$patientId?>&dentition=<?=e((string)$linkedFinding['dentition'])?>&tooth=<?=urlencode((string)$linkedFinding['tooth_number'])?>">Open dental chart</a></div>
    <dl class="summary"><div>Tooth / surface</div><div><strong><?=e((string)$linkedFinding['tooth_number'])?></strong><?=!empty($linkedFinding['surface'])?' · '.e(dental_surface_display((string)$linkedFinding['surface'],(string)$linkedFinding['tooth_number'])):''?></div><div>Finding</div><div><?=e((string)($linkedFinding['condition_name'] ?? module_status((string)$linkedFinding['condition_code'])))?></div><div>Severity</div><div><?=e(module_status((string)($linkedFinding['severity'] ?? 'not recorded')))?></div><div>Status</div><div><span class="badge"><?=e(module_status((string)$linkedFinding['status']))?></span></div></dl>
    <?php if (!$plan && !$plans): ?><p class="notice warning">Create a treatment plan first. The finding will remain selected so it can be added immediately afterward.</p><?php elseif ($canEditPlan): ?><p class="notice success">Choose the appropriate plan, then use <strong>Add linked treatment item</strong>.</p><?php endif; ?>
</section>
<?php endif; ?>

<?php if (!$treatmentLinkReady): ?><div class="alert warning"><strong>Version 0.5.8.6 database update required.</strong> Existing plans remain viewable, but finding-linked treatment planning is disabled until the update is applied in System Setup.</div><?php endif; ?>

<?php if ($patientId): ?><div class="tabs"><?php foreach ($plans as $row): ?><a class="<?=$planId===(int)$row['id']?'active':''?>" href="treatment.php?patient_id=<?=$patientId?>&plan_id=<?=(int)$row['id']?><?=$findingId?'&finding_id='.$findingId:''?>"><?=e((string)$row['title'])?> · <?=e(module_status((string)$row['status']))?></a><?php endforeach; ?></div><?php endif; ?>

<?php if ($plan): ?>
<section class="card">
    <div class="card-head"><div><h2><?=e((string)$plan['title'])?></h2><p><?=e((string)$plan['patient'])?> · <?=e((string)($plan['phase'] ?: 'Unspecified phase'))?> · Version <?=e((string)$plan['version_no'])?></p></div><div><strong>₱<?=number_format((float)$plan['estimate_total'],2)?></strong> <span class="badge"><?=e(module_status((string)$plan['status']))?></span></div></div>
    <div class="status-actions"><a href="odontogram.php?patient_id=<?=$patientId?>" class="btn ghost">Dental chart</a><?php if ($canEditPlan): ?><form method="post"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="update_status"><input type="hidden" name="plan_id" value="<?=$planId?>"><select name="status"><?php foreach (['draft','presented','partially_accepted','accepted','scheduled','in_progress','deferred','declined','cancelled','expired','revised'] as $status): ?><option value="<?=e($status)?>" <?=$plan['status']===$status?'selected':''?>><?=e(module_status($status))?></option><?php endforeach; ?></select><button class="btn ghost">Update plan status</button></form><?php if ($treatmentLinkReady): ?><button type="button" class="btn primary" data-open="plan-item-form"><?=$linkedFinding?'Add linked treatment item':'Add treatment item'?></button><?php endif; ?><?php endif; ?></div>
    <?php if (!empty($plan['notes'])): ?><p><?=nl2br(e((string)$plan['notes']))?></p><?php endif; ?>
</section>

<?php if(treatment_plan_handoff_schema_ready()): ?>
<section class="card">
    <div class="card-head"><div><h2>Responsible Dentist and clinical handoff</h2><p>The plan remains owned by <?=e((string)($plan['dentist']?:'the assigned Dentist'))?>. Selecting another Dentist requires a recorded request and acceptance.</p></div><span class="badge"><?=e((string)($plan['dentist']?:'Unassigned'))?></span></div>
    <?php $canRequestHandoff=($actualRole===$taskRole)&&((($actualRole==='dentist')&&(int)($plan['dentist_user_id']??0)===$currentUserId)||in_array($actualRole,['clinic_admin','super_admin'],true)); $hasPending=false; foreach($handoffs as $h){if($h['status']==='pending'){$hasPending=true;break;}} ?>
    <?php if($canRequestHandoff&&!$hasPending&&!in_array((string)$plan['status'],['completed','cancelled','expired'],true)): ?>
    <form method="post" class="form-grid"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="request_handoff"><input type="hidden" name="plan_id" value="<?=$planId?>">
        <label>Handoff type<select name="request_type"><option value="consultation">Consultation — read-only second opinion</option><option value="transfer">Transfer — change responsible Dentist after acceptance</option></select></label>
        <label>Receiving Dentist<select name="to_dentist_user_id" required><option value="">Select credentialed Dentist</option><?php foreach($handoffDentists as $doctor):if((int)$doctor['id']===(int)($plan['dentist_user_id']??0))continue;?><option value="<?=(int)$doctor['id']?>"><?=e((string)($doctor['display_name']??$doctor['name']))?></option><?php endforeach;?></select></label>
        <label class="wide">Reason<textarea name="reason" required placeholder="Specialty consultation, patient request, approved continuity transfer, leave coverage, or other documented reason"></textarea></label>
        <div class="wide"><button class="btn ghost">Send handoff request</button></div>
    </form>
    <?php endif; ?>
    <div class="treatment-handoff-grid">
    <?php foreach($handoffs as $handoff): ?>
        <article class="treatment-handoff"><div class="card-head"><strong><?=e(module_status((string)$handoff['request_type']))?></strong><span class="badge"><?=e(module_status((string)$handoff['status']))?></span></div><p><?=e((string)$handoff['from_dentist'])?> → <?=e((string)$handoff['to_dentist'])?></p><p><?=e((string)$handoff['reason'])?></p><small>Requested by <?=e((string)($handoff['requester']?:'System'))?> · <?=e(date('M j, Y g:i A',strtotime((string)$handoff['requested_at'])))?></small>
        <?php if($handoff['status']==='pending'&&$actualRole==='dentist'&&$taskRole==='dentist'&&(int)$handoff['to_dentist_user_id']===$currentUserId): ?><form method="post" class="form-grid"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="decide_handoff"><input type="hidden" name="handoff_id" value="<?=(int)$handoff['id']?>"><label class="wide">Decision note<textarea name="decision_note" placeholder="Clinical acceptance note or reason for declining"></textarea></label><div class="status-actions wide"><button class="btn primary" name="decision" value="accepted">Accept</button><button class="btn ghost" name="decision" value="declined">Decline</button></div></form><?php endif; ?>
        <?php $canCancel=$handoff['status']==='pending'&&($actualRole===$taskRole)&&(in_array($actualRole,['clinic_admin','super_admin'],true)||(int)$handoff['requested_by']===$currentUserId||(int)$handoff['from_dentist_user_id']===$currentUserId); if($canCancel): ?><form method="post" class="inline-form"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="cancel_handoff"><input type="hidden" name="handoff_id" value="<?=(int)$handoff['id']?>"><button class="link-btn">Cancel pending request</button></form><?php endif; ?>
        <?php if(!empty($handoff['decision_note'])):?><p><strong>Decision:</strong> <?=e((string)$handoff['decision_note'])?></p><?php endif;?>
        </article>
    <?php endforeach; ?>
    <?php if(!$handoffs): ?><p class="muted">No consultation or transfer has been requested for this plan.</p><?php endif; ?>
    </div>
</section>
<?php else: ?><div class="alert warning">Apply Version 0.5.9.8.2 to enable governed Dentist consultation and treatment-plan transfer.</div><?php endif; ?>

<div class="module-card-grid">
<?php foreach ($items as $item): ?>
<article class="module-card treatment-item-card">
    <div class="card-head"><span class="badge"><?=e(module_status((string)$item['priority']))?></span><span class="badge"><?=e(module_status((string)$item['status']))?></span></div>
    <h3><?=e((string)$item['procedure_name'])?></h3>
    <p><?=e((string)($item['tooth_region'] ?: 'General'))?><?=!empty($item['diagnosis'])?' · '.e((string)$item['diagnosis']):''?></p>
    <?php if (!empty($item['finding_name'])): ?><p class="notice"><strong>Linked finding:</strong> <?=e((string)$item['finding_name'])?><?=!empty($item['finding_severity'])?' · '.e(module_status((string)$item['finding_severity'])):''?></p><?php endif; ?>
    <dl><dt>Sessions</dt><dd><?=e((string)$item['sessions'])?></dd><dt>Duration</dt><dd><?=e((string)$item['duration_minutes'])?> minutes</dd><dt>Approved fee</dt><dd><?php if(($item['fee_status']??'unconfigured')==='no_charge'):?>Authorized no-charge<?php elseif(($item['fee_status']??'unconfigured')==='billable'):?>₱<?=number_format((float)$item['estimated_fee'],2)?><?php else:?><span class="badge danger">Not configured</span><?php endif;?></dd><dt>Consent</dt><dd><?=e(module_status((string)($item['consent_status'] ?? 'not_requested')))?></dd><?php if (!empty($item['prognosis'])): ?><dt>Prognosis</dt><dd><?=e((string)$item['prognosis'])?></dd><?php endif; ?></dl>
    <?php $requiredPrivilege=clinical_privilege_code_for_text(trim((string)($item['procedure_code']??'').' '.(string)$item['procedure_name']));$ownerPrivilegeReason=null;$ownerReady=dentist_has_clinical_privilege((int)($plan['dentist_user_id']??0),(string)($requiredPrivilege?:'consultation'),$ownerPrivilegeReason);$itemTask=$itemTasks[(int)$item['id']]??null; ?>
    <div class="treatment-responsibility <?=!$ownerReady&&!$itemTask?'warning':''?>"><strong>Clinical responsibility</strong><span>Required privilege: <?=e(module_status((string)($requiredPrivilege?:'consultation')))?></span><?php if($itemTask):?><span>Assigned Dentist: <?=e((string)($itemTask['assigned_dentist']?:'Pending assignment'))?> · <?=e(module_status((string)$itemTask['status']))?></span><?php elseif(!$ownerReady):?><span><?=e((string)$ownerPrivilegeReason)?></span><?php else:?><span><?=e((string)($plan['dentist']?:'Responsible Dentist'))?> is qualified for this item.</span><?php endif;?></div>
    <?php if(clinical_task_assignment_schema_ready()&&$item['status']!=='completed'&&($canEditPlan||in_array($actualRole,['clinic_admin','super_admin'],true))):?><a class="btn <?=!$ownerReady&&!$itemTask?'primary':'ghost'?>" href="clinical_tasks.php?item_id=<?=(int)$item['id']?>"><?=!$ownerReady&&!$itemTask?'Assign qualified Dentist':'Manage specific Dentist task'?></a><?php endif;?>
    <?php if (!empty($item['clinical_rationale'])): ?><p><strong>Clinical rationale:</strong> <?=nl2br(e((string)$item['clinical_rationale']))?></p><?php endif; ?>
    <?php if (!empty($item['notes'])): ?><p><?=nl2br(e((string)$item['notes']))?></p><?php endif; ?>
    <?php if ($canEditPlan): ?><div class="status-actions"><a class="btn ghost" href="consents.php?patient_id=<?=$patientId?>&item_id=<?=(int)$item['id']?>"><?=($item['consent_status']??'not_requested')==='accepted'?'View consent':'Create consent'?></a><?php if ($item['status']!=='completed'): ?><form method="post" class="status-actions"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="update_item"><input type="hidden" name="item_id" value="<?=(int)$item['id']?>"><select name="status"><?php foreach (['proposed','accepted','scheduled','in_progress','deferred','declined','cancelled'] as $status): ?><option value="<?=e($status)?>" <?=$item['status']===$status?'selected':''?>><?=e(module_status($status))?></option><?php endforeach; ?></select><button class="btn ghost">Save workflow status</button></form><?php else: ?><span class="notice success">Completed through finalized encounter</span><?php endif; ?></div><?php endif; ?>
</article>
<?php endforeach; ?>
<?php if (!$items): ?><div class="card queue-empty">No treatment items yet. Add procedures from the dental chart or enter a general treatment item.</div><?php endif; ?>
</div>
<?php elseif ($patientId): ?><div class="card queue-empty">No treatment plan for this patient yet. Create one to sequence findings and procedures.</div><?php else: ?><div class="card queue-empty">Select a patient to review treatment plans.</div><?php endif; ?>

<?php if ($canEdit): ?>
<dialog id="plan-form" class="wide-dialog"><form method="post" class="form-grid"><button type="button" class="dialog-close" data-close>×</button><h2 class="wide">Create treatment plan</h2><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="create_plan"><input type="hidden" name="finding_id" value="<?=$findingId?>"><label>Patient<?php module_patient_select($patients,'patient_id',$patientId); ?></label><div class="treatment-owner-card"><div><strong><?=e((string)(current_user()['name']??'Dentist'))?></strong><span>Responsible Dentist · locked to the signed-in clinical identity</span></div><input type="hidden" name="dentist_user_id" value="<?=$currentUserId?>"></div><label class="wide">Plan title<input name="title" required value="<?=e($linkedFinding?'Treatment plan for tooth '.$prefillTooth:'')?>" placeholder="Comprehensive restorative plan"></label><label>Phase<select name="phase"><option>Emergency Care</option><option>Disease Control</option><option>Definitive Treatment</option><option>Maintenance</option></select></label><label>Estimate expiration<input type="date" name="expires_at"></label><label>Encounter ID<input type="number" name="encounter_id" value="<?=e((string)($linkedFinding['encounter_id']??''))?>"></label><label class="wide">Notes<textarea name="notes"><?=e($linkedFinding?'Created from dental chart finding: '.$prefillDiagnosis:'')?></textarea></label><button class="btn primary wide">Create plan</button></form></dialog>
<?php if ($canEditPlan && $treatmentLinkReady): ?>
<dialog id="plan-item-form" class="wide-dialog"><form method="post" class="form-grid"><button type="button" class="dialog-close" data-close>×</button><h2 class="wide"><?=$linkedFinding?'Add linked tooth treatment':'Add treatment item'?></h2><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="add_item"><input type="hidden" name="plan_id" value="<?=$planId?>"><input type="hidden" name="odontogram_entry_id" value="<?=$findingId?>"><input type="hidden" name="diagnosis_id" value="<?=e((string)($linkedFinding['diagnosis_id']??''))?>"><label class="wide">Approved service<select name="service_id" required><option value="">Select service</option><?php foreach($serviceCatalog as $service):$match=$prefillProcedure!==''&&str_contains(strtolower((string)$service['name']),strtolower($prefillProcedure));?><option value="<?=(int)$service['id']?>" <?=$match?'selected':''?>><?=e((string)$service['name'])?> · <?=($service['fee_status']==='no_charge'?'Authorized no-charge':'₱'.number_format((float)$service['standard_fee'],2))?> · <?=(int)$service['duration_minutes']?> min</option><?php endforeach;?></select><small>The service name and approved fee are copied into the treatment item. Free-text clinical procedures are not billable.</small></label><label>Procedure code<input name="procedure_code" placeholder="Clinic or CDT code"></label><label>Tooth number<input name="tooth_number" value="<?=e($prefillTooth)?>"></label><label>Surface(s)<input name="surfaces" value="<?=e($prefillSurfaces)?>" placeholder="M,O,D"></label><label class="wide">Tooth or region label<input name="tooth_region" value="<?=e(trim($prefillTooth.($prefillSurfaces?' · '.$prefillSurfaces:'')))?>"></label><label class="wide">Diagnosis<input name="diagnosis" value="<?=e($prefillDiagnosis)?>"></label><label>Priority<select name="priority"><?php foreach (['routine','important','urgent','emergency'] as $priority): ?><option value="<?=$priority?>" <?=$prefillPriority===$priority?'selected':''?>><?=e(module_status($priority))?></option><?php endforeach; ?></select></label><label>Sequence<input type="number" min="1" name="sequence_no" value="<?=count($items)+1?>"></label><label>Sessions<input type="number" min="1" name="sessions" value="1"></label><label>Duration minutes<input type="number" min="5" name="duration_minutes" value="30"><small>Clinical duration only; fee always comes from the service policy.</small></label><label>Prognosis<select name="prognosis"><option value="">Not recorded</option><option>Excellent</option><option>Good</option><option>Fair</option><option>Guarded</option><option>Poor</option><option>Hopeless</option></select></label><div class="notice wide"><strong>Consent is not edited here.</strong> Add the proposed treatment first, then create a procedure-specific consent record for that item.</div><label class="wide">Clinical rationale<textarea name="clinical_rationale" placeholder="Why this procedure is recommended, supporting tests or imaging, and expected outcome"><?=e($prefillRationale)?></textarea></label><label class="wide">Notes<textarea name="notes"></textarea></label><button class="btn primary wide">Add treatment item</button></form></dialog>
<?php endif; endif; ?>
<?php if ($linkedFinding && (($plan && $canEditPlan) || (!$plan && $canEdit))): ?><script>document.addEventListener('DOMContentLoaded',()=>{const id=<?=json_encode($plan ? 'plan-item-form' : 'plan-form')?>;const dialog=document.getElementById(id);if(dialog&&typeof dialog.showModal==='function')dialog.showModal();});</script><?php endif; ?>
<?php render_footer(); ?>
