<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require_login();
require_doctor_workflow_schema();
require_clinical_sequence_schema();
require_encounter_assistant_schema();
require DENTAL_ROOT . '/app/layout.php';
require_once DENTAL_ROOT . '/app/queue_flow.php';
require_once DENTAL_ROOT . '/app/treatment_flow.php';
require_once DENTAL_ROOT . '/app/module_helpers.php';
require_once DENTAL_ROOT . '/app/tooth_model.php';
require_once DENTAL_ROOT . '/app/adaptive_encounter.php';
require_once DENTAL_ROOT . '/app/clinical_media.php';
require_once DENTAL_ROOT . '/app/appointment_planning.php';
require_once DENTAL_ROOT . '/app/workflow_governance.php';

$pdo = db();
$user = current_user() ?? [];
$userId = (int) ($user['id'] ?? 0);
$actualRole = actual_role();
$isDentist = active_role_is('dentist');
$isAdministrativeAccount = in_array($actualRole, ['super_admin','clinic_admin'], true);
if (!$isDentist && !$isAdministrativeAccount) {
    http_response_code(403);
    render_header('Treatment access');
    ?><section class="card setup-empty-state"><h2>Treatment dashboard unavailable</h2><p>This workspace is reserved for an authenticated Dentist or authorized clinical administrator.</p><div class="status-actions"><a class="btn primary" href="dashboard.php">Return to dashboard</a><a class="btn ghost" href="queue.php">Open clinic queue</a></div></section><?php
    render_footer();
    return;
}

$dentistId = $isDentist ? $userId : (int) ($_GET['dentist_id'] ?? 0);
if (!$isDentist && $dentistId <= 0) $dentistId = (int) (dentist_options()[0]['id'] ?? 0);
$profile = dentist_profile($dentistId);
if (!$profile) {
    http_response_code(200);
    $availableDentists = dentist_options();
    render_header($isDentist ? 'My Treatment Dashboard' : 'Dentist Treatment Dashboard');
    ?>
    <section class="card setup-empty-state">
        <span class="eyebrow">Clinical setup required</span>
        <h2>No active Dentist profile is ready yet</h2>
        <p>This usually happens after a fresh reset, when no Dentist account/profile has been created or activated yet. The system should show this setup guide instead of a blank white screen.</p>
        <div class="notice warning"><strong>Treatment is paused:</strong> create or complete a Dentist profile before seating patients for clinical treatment.</div>
        <div class="button-row">
            <?php if ($isAdministrativeAccount): ?>
                <?php if(task_link_allowed('staff.php')):?><a class="btn primary" href="staff.php">Create / manage staff</a><?php endif;?>
                <a class="btn ghost" href="doctor_profile.php">Open professional setup</a>
                <?php if(task_link_allowed('chairs.php')):?><a class="btn ghost" href="chairs.php">Review chairs/resources</a><?php endif;?>
            <?php else: ?>
                <a class="btn primary" href="doctor_profile.php">Complete professional setup</a>
            <?php endif; ?>
            <a class="btn ghost" href="dashboard.php">Back to dashboard</a>
        </div>
        <?php if ($availableDentists): ?>
            <hr>
            <form class="compact-filter" method="get">
                <label>Open another Dentist dashboard<select name="dentist_id" onchange="this.form.submit()"><option value="">Choose Dentist</option><?php foreach ($availableDentists as $doctor): ?><option value="<?= (int)$doctor['id'] ?>"><?= e((string)($doctor['display_name'] ?: $doctor['name'])) ?></option><?php endforeach; ?></select></label>
                <noscript><button class="btn ghost">Open</button></noscript>
            </form>
        <?php endif; ?>
    </section>
    <?php
    render_footer();
    return;
}

function treatment_elapsed(?string $startedAt): string
{
    if (!$startedAt) return 'Not started';
    $seconds = max(0, time() - strtotime($startedAt));
    $minutes = (int) floor($seconds / 60);
    if ($minutes < 60) return $minutes . ' min';
    return intdiv($minutes, 60) . ' hr ' . ($minutes % 60) . ' min';
}

function treatment_start_assistant_options(int $branchId): array
{
    if (!function_exists('encounter_assistant_schema_ready') || !encounter_assistant_schema_ready()) return [];
    $stmt = db()->prepare(
        'SELECT u.id,u.name FROM `' . table('users') . '` u '
        . 'JOIN `' . table('roles') . '` r ON r.id=u.role_id '
        . 'WHERE r.code="dental_assistant" AND u.status="active" AND (u.branch_id=? OR u.branch_id IS NULL OR ?=0) '
        . 'ORDER BY u.name'
    );
    $stmt->execute([$branchId, $branchId]);
    return $stmt->fetchAll();
}

function treatment_start_form(array $row, string $label = 'Start treatment'): void
{
    $queueId = (int) $row['id'];
    $status = (string)($row['status'] ?? '');
    $dialogId = 'start-treatment-assistant-' . $queueId;
    $assistantOptions = treatment_start_assistant_options((int)($row['branch_id'] ?? 0));
    $safetyGate = dental_safety_treatment_gate($row, dental_encounter_default_care_path($row));
    if ($status !== 'in_treatment' && empty($safetyGate['ready'])) {
        $assessmentUrl = dental_safety_assessment_url($queueId);
        ?>
        <div class="dental-safety-start-gate">
            <span class="badge warning"><?= e((string)($safetyGate['label'] ?? 'First seating required')) ?></span>
            <p><?= e((string)($safetyGate['message'] ?? 'Complete first-seating dental safety assessment before treatment starts.')) ?></p>
            <a class="btn primary" href="<?= e($assessmentUrl) ?>">Complete first seating</a>
        </div>
        <?php
        return;
    }
    if ($status === 'in_treatment' && clinical_assistant_decision_complete($row)) {
        ?>
        <form method="post" action="clinical_workspace.php" class="inline-form" data-preserve-scroll-form>
            <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
            <input type="hidden" name="action" value="start">
            <input type="hidden" name="queue_id" value="<?= $queueId ?>">
            <button class="btn primary" type="submit">Open encounter</button>
        </form>
        <?php
        return;
    }
    if ($status === 'in_treatment') $label = 'Confirm team & open';
    ?>
    <button class="btn primary" type="button" data-open="<?= e($dialogId) ?>"><?= e($label) ?></button>
    <dialog id="<?= e($dialogId) ?>" class="wide-dialog" data-dialog-start-top>
        <form method="post" action="clinical_workspace.php" class="form-grid">
            <button type="button" class="dialog-close" data-close>×</button>
            <h2 class="wide">Start treatment</h2>
            <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
            <input type="hidden" name="action" value="start">
            <input type="hidden" name="queue_id" value="<?= $queueId ?>">
            <input type="hidden" name="start_assistant_prompted" value="1">
            <div class="notice wide">
                <strong>Chairside team check.</strong> Before the clinical encounter starts, confirm whether a Dental Assistant is working with the Dentist for this patient.
            </div>
            <div class="wide clinical-start-patient-summary">
                <span class="eyebrow"><?= e((string)($row['queue_no'] ?? 'Queue')) ?> · <?= e((string)($row['chair_name'] ?: 'Chair not recorded')) ?></span>
                <strong><?= e(patient_full_name($row)) ?></strong>
                <small><?= e((string)($row['service_name'] ?: 'Dental visit')) ?></small>
            </div>
            <?php $selectedCarePath=dental_encounter_default_care_path($row); ?>
            <label class="wide">Encounter path
                <select name="care_path" data-dialog-initial-focus required>
                    <?php foreach(dental_encounter_care_paths() as $carePathCode=>$carePath): ?>
                        <option value="<?=e($carePathCode)?>" <?=$selectedCarePath===$carePathCode?'selected':''?>><?=e((string)$carePath['label'])?> — <?=e((string)$carePath['summary'])?></option>
                    <?php endforeach; ?>
                </select>
                <small>Choose the clinical pattern for this visit. Focused and follow-up paths skip nonessential intake and full-examination steps, but safety, diagnosis, consent, treatment, and billing controls remain active.</small>
            </label>
            <label class="wide">Dental Assistant
                <select name="assistant_user_id">
                    <option value="" <?=clinical_assistant_decision($row)==='none'?'selected':''?>>No Dental Assistant for this visit</option>
                    <?php foreach ($assistantOptions as $assistant): ?>
                        <option value="<?= (int)$assistant['id'] ?>" <?=(int)($row['assistant_user_id']??0)===(int)$assistant['id']?'selected':''?>><?= e((string)$assistant['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </label>
            <?php if (!$assistantOptions): ?>
                <p class="muted wide">No active Dental Assistant account is configured for this branch. The Dentist can continue alone and assign one later if needed.</p>
            <?php else: ?>
                <p class="muted wide">Choose the assistant now, or keep <strong>No Dental Assistant</strong>. This controls the assistant’s treatment access for this encounter.</p>
            <?php endif; ?>
            <div class="button-row wide">
                <button class="btn primary" type="submit">Start clinical encounter</button>
                <button class="btn ghost" type="button" data-close>Cancel</button>
            </div>
        </form>
    </dialog>
    <?php
}

function treatment_render_planned_services(array $segments, bool $compact = false): void
{
    if (!$segments || ($compact && count($segments) < 2)) return;
    $canDisposition=!$compact&&appointment_service_disposition_schema_ready()&&has_role(['super_admin','clinic_admin','dentist','staff','dental_assistant']);
    $futureAppointments=[];
    if($canDisposition){
        $first=$segments[0];
        $stmt=db()->prepare('SELECT a.id,a.start_at,a.service_name,a.dentist_name,a.inhouse_provider_name FROM `' . table('appointments') . '` a JOIN `' . table('appointments') . '` source ON source.id=? WHERE a.patient_id=source.patient_id AND a.branch_id=source.branch_id AND a.id<>source.id AND a.start_at>NOW() AND a.status IN ("requested","pending_confirmation","confirmed") ORDER BY a.start_at,a.id LIMIT 30');
        $stmt->execute([(int)$first['appointment_id']]);
        $futureAppointments=$stmt->fetchAll();
    }
    ?>
    <div class="appointment-service-segments<?= $compact ? ' compact' : '' ?>">
        <strong>Planned services</strong>
        <?php foreach ($segments as $segment): $segmentStatus=(string)($segment['status']??'planned'); ?>
            <small><span><?= e((string)($segment['service_name'] ?? 'Dental service')) ?><?php if($segmentStatus!=='planned'):?> <span class="badge"><?=e(ucwords(str_replace('_',' ',$segmentStatus)))?></span><?php endif;?></span><span><?= e(date('g:i A', strtotime((string)$segment['start_at']))) ?>–<?= e(date('g:i A', strtotime((string)$segment['end_at']))) ?><?php $segmentProvider=trim((string)(($segment['dentist_name'] ?? '') ?: ($segment['inhouse_provider_name'] ?? ''))); ?><?= $segmentProvider!=='' ? ' · ' . e($segmentProvider) : '' ?></span></small>
            <?php if($canDisposition&&$segmentStatus==='planned'):?>
            <details class="planned-service-disposition"><summary>Could not complete this service</summary><form method="post" action="appointment_service_actions.php" class="compact-form"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="appointment_service_id" value="<?=(int)$segment['id']?>"><input type="hidden" name="return" value="doctor_treatment.php"><label>Next action<select name="service_action" data-service-disposition-action required><option value="defer_next">Prioritize on next appointment</option><option value="move_existing">Move to an existing future appointment</option><option value="create_followup">Create a new follow-up</option><option value="not_performed">Mark not performed</option></select></label><label data-service-destination>Future appointment<select name="destination_appointment_id"><option value="">Choose future appointment</option><?php foreach($futureAppointments as $future):?><option value="<?=(int)$future['id']?>"><?=e(date('M j, Y g:i A',strtotime((string)$future['start_at'])).' · '.(string)$future['service_name'].' · '.(string)(($future['dentist_name']??'')?:($future['inhouse_provider_name']??'Clinic team')))?></option><?php endforeach;?></select></label><label>Required reason<textarea name="reason" required minlength="5" placeholder="Why the service was not completed and the patient discussion"></textarea></label><button class="btn ghost" type="submit">Save disposition</button></form></details>
            <?php elseif($segmentStatus!=='planned'&&!empty($segment['disposition_reason'])):?><small class="muted"><?=e((string)$segment['disposition_reason'])?><?php if(!empty($segment['destination_appointment_id'])):?> · Appointment #<?=(int)$segment['destination_appointment_id']?><?php endif;?></small><?php endif;?>
        <?php endforeach; ?>
    </div>
    <?php
}

function treatment_patient_age(?string $birthDate): string
{
    if (!$birthDate) return 'Not recorded';
    try { return (string)(new DateTime($birthDate))->diff(new DateTime('today'))->y . ' years'; }
    catch (Throwable) { return 'Not recorded'; }
}

function treatment_safe_fetch(PDO $pdo, string $sql, array $args = []): ?array
{
    try { $stmt=$pdo->prepare($sql); $stmt->execute($args); $row=$stmt->fetch(); return $row ?: null; }
    catch (Throwable $exception) { error_log('DentalCare treatment snapshot query failed: '.$exception->getMessage()); return null; }
}

function treatment_safe_fetch_all(PDO $pdo, string $sql, array $args = []): array
{
    try { $stmt=$pdo->prepare($sql); $stmt->execute($args); return $stmt->fetchAll(); }
    catch (Throwable $exception) { error_log('DentalCare treatment snapshot query failed: '.$exception->getMessage()); return []; }
}

function treatment_patient_snapshot(PDO $pdo, array $row): array
{
    $patientId=(int)($row['patient_id']??0);
    $queueId=(int)($row['id']??0);
    $appointmentId=(int)($row['appointment_id']??0);
    $encounterId=(int)($row['encounter_id']??0);
    $intake=active_patient_intake($patientId,$queueId?:null,$appointmentId?:null) ?: [];
    $medical=treatment_safe_fetch($pdo,'SELECT allergies,medications,conditions,dental_history,created_at FROM `' . table('medical_histories') . '` WHERE patient_id=? ORDER BY created_at DESC,id DESC LIMIT 1',[$patientId]) ?: [];
    $vitals=treatment_safe_fetch($pdo,'SELECT * FROM `' . table('vital_signs') . '` WHERE patient_id=? ORDER BY recorded_at DESC,id DESC LIMIT 1',[$patientId]) ?: [];
    $lastEncounter=treatment_safe_fetch($pdo,'SELECT id,created_at,diagnosis,procedure_done,status,dentist_name FROM `' . table('clinical_encounters') . '` WHERE patient_id=? ORDER BY created_at DESC,id DESC LIMIT 1',[$patientId]) ?: [];
    $findings=[];
    if(schema_table_exists(table('odontogram_entries'))){
        $findingSql=schema_table_exists(table('dental_condition_catalog'))
            ? 'SELECT o.dentition,o.tooth_number,o.surface,o.condition_code,o.finding_type,o.severity,o.chart_layer,o.status,COALESCE(c.name,d.diagnosis_name) condition_name,COALESCE(c.category,IF(d.id IS NOT NULL,"diagnosis",o.finding_type)) category 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.patient_id=? AND o.status="active" ORDER BY FIELD(o.severity,"critical","severe","moderate","mild","information"),o.recorded_at DESC'
            : 'SELECT o.dentition,o.tooth_number,o.surface,o.condition_code,o.finding_type,o.severity,o.chart_layer,o.status,d.diagnosis_name condition_name,IF(d.id IS NOT NULL,"diagnosis",o.finding_type) category FROM `' . table('odontogram_entries') . '` o LEFT JOIN `' . table('diagnoses') . '` d ON d.id=o.diagnosis_id WHERE o.patient_id=? AND o.status="active" ORDER BY o.recorded_at DESC';
        $findings=treatment_safe_fetch_all($pdo,$findingSql,[$patientId]);
    }
    $plan=[];
    if(schema_table_exists(table('treatment_plans'))){
        $plan=treatment_safe_fetch($pdo,'SELECT tp.*,(SELECT COUNT(*) FROM `' . table('treatment_plan_items') . '` i WHERE i.treatment_plan_id=tp.id AND i.status NOT IN ("cancelled","declined")) item_count,(SELECT COUNT(*) FROM `' . table('treatment_plan_items') . '` i WHERE i.treatment_plan_id=tp.id AND (i.consent_status="accepted" OR i.status IN ("accepted","scheduled","in_progress","completed"))) accepted_count FROM `' . table('treatment_plans') . '` tp WHERE tp.patient_id=? AND tp.status IN ("draft","presented","partially_accepted","accepted","scheduled","in_progress") ORDER BY tp.created_at DESC,tp.id DESC LIMIT 1',[$patientId]) ?: [];
    }
    $followup=schema_table_exists(table('follow_ups')) ? (treatment_safe_fetch($pdo,'SELECT purpose,recommended_date,urgency,status FROM `' . table('follow_ups') . '` WHERE patient_id=? AND status IN ("pending","scheduled") ORDER BY recommended_date ASC,id DESC LIMIT 1',[$patientId]) ?: []) : [];
    $prescription=[];
    if(schema_table_exists(table('prescriptions'))){
        $prescription=treatment_safe_fetch($pdo,'SELECT rx.id,rx.prescription_no,rx.issued_at,rx.status,rx.notes,u.name dentist_name,dp.license_number FROM `' . table('prescriptions') . '` rx LEFT JOIN `' . table('users') . '` u ON u.id=rx.dentist_user_id LEFT JOIN `' . table('dentist_profiles') . '` dp ON dp.user_id=rx.dentist_user_id WHERE rx.patient_id=? AND rx.status="issued" ORDER BY rx.issued_at DESC,rx.id DESC LIMIT 1',[$patientId]) ?: [];
        if(!empty($prescription['id'])&&schema_table_exists(table('prescription_items'))){
            $prescription['items']=treatment_safe_fetch_all($pdo,'SELECT medication_name,generic_name,strength,dosage,frequency,route,duration_days,quantity,instructions FROM `' . table('prescription_items') . '` WHERE prescription_id=? ORDER BY id',[(int)$prescription['id']]);
        }else{$prescription['items']=[];}
    }
    $imaging=[];
    if(schema_table_exists(table('documents'))){
        try{$imaging=clinical_recent_imaging($pdo,$patientId,$encounterId?:null,6);}
        catch(Throwable $exception){error_log('DentalCare treatment imaging snapshot failed: '.$exception->getMessage());}
    }
    return compact('intake','medical','vitals','lastEncounter','findings','plan','followup','prescription','imaging');
}

function treatment_render_snapshot_odontogram(array $row, array $findings, bool $editable = false): void
{
    $ageValue = null;
    if (!empty($row['birth_date'])) {
        try { $ageValue=(new DateTime((string)$row['birth_date']))->diff(new DateTime('today'))->y; }
        catch (Throwable) { $ageValue=null; }
    }
    $dentition=$ageValue!==null && $ageValue<6 ? 'primary' : (($ageValue!==null && $ageValue<=12) ? 'mixed' : 'permanent');
    $permanentUpper=['18','17','16','15','14','13','12','11','21','22','23','24','25','26','27','28'];
    $permanentLower=['48','47','46','45','44','43','42','41','31','32','33','34','35','36','37','38'];
    $primaryUpper=['55','54','53','52','51','61','62','63','64','65'];
    $primaryLower=['85','84','83','82','81','71','72','73','74','75'];
    $upper=$dentition==='primary'?$primaryUpper:($dentition==='mixed'?array_merge($permanentUpper,$primaryUpper):$permanentUpper);
    $lower=$dentition==='primary'?$primaryLower:($dentition==='mixed'?array_merge($permanentLower,$primaryLower):$permanentLower);
    $filtered=[];
    foreach($findings as $finding){
        if($dentition==='mixed' || (string)($finding['dentition']??'permanent')===$dentition)$filtered[]=$finding;
    }
    $byTooth=dental_group_active_entries_by_tooth($filtered);
    $encounterId=(int)($row['encounter_id']??0);
    $base='odontogram.php?patient_id='.(int)$row['patient_id'].'&dentition='.urlencode($dentition).($encounterId>0?'&encounter_id='.$encounterId:'');
    $readOnlyMessage=$encounterId>0?'Read-only chart. Only the assigned dentist can record findings for this treatment encounter.':'Start treatment first to create or link a clinical encounter before charting a tooth.';
    ?>
    <div class="snapshot-odontogram">
        <div class="snapshot-odontogram-head"><strong>Tooth model</strong><a href="<?=e($base)?>">Open full chart</a></div>
        <div class="fdi-orientation-note compact"><strong>FDI patient-facing view</strong><span>Screen left is the patient’s right. Upper: 18–11 | 21–28. Lower: 48–41 | 31–38. Primary teeth use quadrants 5–8.</span></div>
        <div class="tooth-model-row compact-row"><?php foreach($upper as $tooth)echo dental_render_tooth_model($tooth,$byTooth[$tooth]??[],$base.'&tooth='.urlencode($tooth).($editable&&$encounterId>0?'&open_finding=1':''),false,'upper',true,['interactive'=>true,'editable'=>$editable&&$encounterId>0,'dialog_id'=>'finding-form','read_only_message'=>$readOnlyMessage]);?></div>
        <div class="tooth-model-row compact-row lower-row"><?php foreach($lower as $tooth)echo dental_render_tooth_model($tooth,$byTooth[$tooth]??[],$base.'&tooth='.urlencode($tooth).($editable&&$encounterId>0?'&open_finding=1':''),false,'lower',true,['interactive'=>true,'editable'=>$editable&&$encounterId>0,'dialog_id'=>'finding-form','read_only_message'=>$readOnlyMessage]);?></div>
    </div>
    <?php
}

function treatment_render_snapshot(array $row, array $snapshot, bool $open = false, bool $editable = false): void
{
    $intake=$snapshot['intake']??[];$medical=$snapshot['medical']??[];$vitals=$snapshot['vitals']??[];$last=$snapshot['lastEncounter']??[];$findings=$snapshot['findings']??[];$plan=$snapshot['plan']??[];$followup=$snapshot['followup']??[];$prescription=$snapshot['prescription']??[];$imaging=$snapshot['imaging']??[];
    $patientAge=0;if(!empty($row['birth_date'])){try{$patientAge=(new DateTime((string)$row['birth_date']))->diff(new DateTime('today'))->y;}catch(Throwable){$patientAge=0;}}
    [$bpSys,$bpDia,$bpRepeated]=clinical_vitals_effective_bp($vitals);$bp=$bpSys!==null?$bpSys.'/'.$bpDia.' mmHg'.($bpRepeated?' (repeat)':''):'Not recorded';$bpScreening=clinical_vitals_bp_screening($vitals,$patientAge);
    ?>
    <details class="patient-treatment-snapshot" <?= $open?'open':'' ?>>
        <summary>Clinical snapshot and patient information</summary>
        <div class="patient-snapshot-grid">
            <section><h4>Patient</h4><dl><dt>Age / sex</dt><dd><?=e(treatment_patient_age($row['birth_date']??null))?> · <?=e((string)(($row['sex']??'')?:'Not recorded'))?></dd><dt>Mobile</dt><dd><?=e((string)(($row['mobile']??'')?:'Not recorded'))?></dd><dt>Email</dt><dd><?=e((string)(($row['email']??'')?:'Not recorded'))?></dd><dt>Emergency contact</dt><dd><?=e((string)(($row['emergency_contact']??'')?:'Not recorded'))?></dd></dl></section>
            <section><h4>Reason and intake</h4><dl><dt>Chief complaint</dt><dd><?=e((string)($intake['chief_complaint']??$row['reason']??'Not recorded'))?></dd><dt>History</dt><dd><?=e((string)($intake['history_present_condition']??'Not recorded'))?></dd><dt>Pain</dt><dd><?=isset($intake['pain_score'])&&$intake['pain_score']!==null?e((string)$intake['pain_score']).'/10':'Not recorded'?></dd><dt>Intake consent</dt><dd><?=!empty($intake['consent_acknowledged'])?'Acknowledged':'Not yet acknowledged'?></dd></dl></section>
            <section class="snapshot-medical"><h4>Dental treatment safety</h4><dl><dt>Allergies</dt><dd><?=e(function_exists('dentalcare_medical_display') ? dentalcare_medical_display(($medical['allergies']??$intake['allergy_changes']??''), 'None recorded') : (string)($medical['allergies']??$intake['allergy_changes']??'None recorded'))?></dd><dt>Medications</dt><dd><?=e(function_exists('dentalcare_medical_display') ? dentalcare_medical_display(($medical['medications']??$intake['medication_changes']??''), 'None recorded') : (string)($medical['medications']??$intake['medication_changes']??'None recorded'))?></dd><dt>Conditions</dt><dd><?=e(function_exists('dentalcare_medical_display') ? dentalcare_medical_display(($medical['conditions']??$intake['medical_changes']??''), 'None recorded') : (string)($medical['conditions']??$intake['medical_changes']??'None recorded'))?></dd><dt>Pregnancy</dt><dd><?=e((string)($vitals['pregnancy_status']??'Not recorded'))?></dd></dl></section>
            <section><h4>Latest vitals</h4><dl><dt>Blood pressure</dt><dd><?=e($bp)?><?php if($bpSys!==null):?><br><small class="vital-cue <?=e((string)$bpScreening['class'])?>"><?=e((string)$bpScreening['label'])?></small><?php endif;?></dd><dt>Pulse / SpO₂</dt><dd><?=e((string)($vitals['pulse_rate']??'—'))?> bpm · <?=e((string)($vitals['oxygen_saturation']??'—'))?>%</dd><dt>Temperature / respiration</dt><dd><?=e((string)($vitals['temperature_c']??'—'))?> °C · <?=e((string)($vitals['respiratory_rate']??'—'))?>/min</dd><dt>Weight / height / BMI</dt><dd><?=e((string)($vitals['weight_kg']??'—'))?> kg · <?=e((string)($vitals['height_cm']??'—'))?> cm · <?=e((string)($vitals['bmi']??'—'))?></dd><dt>Glucose / pain</dt><dd><?=e((string)($vitals['blood_glucose']??'—'))?> mg/dL · <?=e((string)($vitals['pain_score']??'—'))?>/10</dd><dt>Recorded</dt><dd><?=!empty($vitals['recorded_at'])?e(date('M j, Y g:i A',strtotime((string)$vitals['recorded_at']))):'Not recorded'?></dd></dl></section>
            <section><h4>Dental status</h4><?php if($findings):?><ul class="snapshot-findings"><?php foreach(array_slice($findings,0,8) as $finding):?><li><strong><?=e(dental_tooth_display_label((string)$finding['tooth_number']))?></strong> · <?=e((string)($finding['condition_name']??module_status((string)$finding['condition_code'])))?><?=!empty($finding['surface'])?' · '.e(dental_surface_display((string)$finding['surface'],(string)$finding['tooth_number'])):''?><?=!empty($finding['severity'])?' · '.e(ucfirst((string)$finding['severity'])):''?></li><?php endforeach;?></ul><?php else:?><p>No active tooth findings recorded.</p><?php endif;?></section>
            <section><h4>Plan and continuity</h4><dl><dt>Active plan</dt><dd><?=!empty($plan['id'])?e(module_status((string)$plan['status'])).' · '.(int)($plan['item_count']??0).' item(s)':'None'?></dd><dt>Accepted items</dt><dd><?=!empty($plan['id'])?(int)($plan['accepted_count']??0).' accepted':'None'?></dd><dt>Follow-up</dt><dd><?=!empty($followup['recommended_date'])?e(date('M j, Y',strtotime((string)$followup['recommended_date']))).' · '.e((string)($followup['purpose']??'Follow-up')):'None pending'?></dd><dt>Urgency</dt><dd><?=!empty($followup['urgency'])?e(ucfirst((string)$followup['urgency'])):'Routine / none'?></dd></dl></section>
            <?php if(!empty($snapshot['unresolved_services'])):?><section class="snapshot-unresolved-services"><h4>Carry-forward items</h4><ul><?php foreach(array_slice((array)$snapshot['unresolved_services'],0,5) as $svc):?><li><strong><?=e((string)$svc['service_name'])?></strong><small><?=e(ucwords(str_replace('_',' ',(string)$svc['status'])))?><?=!empty($svc['start_at'])?' · from '.e(date('M j, Y',strtotime((string)$svc['start_at']))):''?><?=!empty($svc['disposition_reason'])?' · '.e((string)$svc['disposition_reason']):''?></small></li><?php endforeach;?></ul></section><?php endif;?>
            <section class="snapshot-last-visit"><h4>Last clinical record</h4><p><?=!empty($last['created_at'])?e(date('M j, Y',strtotime((string)$last['created_at']))).' · '.e((string)(($last['dentist_name']??'')?:'Dentist')):'No previous encounter'?></p><p><strong>Diagnosis:</strong> <?=e((string)(($last['diagnosis']??'')?:'Not recorded'))?><br><strong>Procedure:</strong> <?=e((string)(($last['procedure_done']??'')?:'Not recorded'))?></p></section>
            <section class="snapshot-prescription"><div class="snapshot-section-head"><h4>Latest prescription</h4><?php if(!empty($prescription['id'])):?><a target="_blank" href="print_record.php?type=prescription&amp;id=<?=(int)$prescription['id']?>">View / print</a><?php endif;?></div><?php if(!empty($prescription['id'])):?><p><strong><?=e((string)$prescription['prescription_no'])?></strong> · <?=e(date('M j, Y',strtotime((string)$prescription['issued_at'])))?> · <?=e((string)($prescription['dentist_name']?:'Dentist'))?></p><ul class="snapshot-rx-list"><?php foreach(array_slice((array)($prescription['items']??[]),0,6) as $medicine):?><li><strong><?=e(trim((string)$medicine['medication_name'].' '.(string)($medicine['strength']??'')))?></strong><span><?=e(trim(implode(' · ',array_filter([(string)($medicine['dosage']??''),(string)($medicine['frequency']??''),(string)($medicine['route']??''),!empty($medicine['duration_days'])?((int)$medicine['duration_days'].' days'):null]))))?></span><?php if(!empty($medicine['instructions'])):?><small><?=e((string)$medicine['instructions'])?></small><?php endif;?></li><?php endforeach;?></ul><?php if(!empty($prescription['notes'])):?><p class="muted"><?=e((string)$prescription['notes'])?></p><?php endif;?><?php else:?><p>No issued prescription recorded.</p><?php endif;?></section>
            <section class="snapshot-imaging"><div class="snapshot-section-head"><h4>X-rays and clinical images</h4><a href="documents.php?patient_id=<?=(int)$row['patient_id']?>">View all</a></div><?php if($imaging):?><div class="snapshot-image-grid"><?php foreach(array_slice($imaging,0,4) as $image):$isImage=str_starts_with((string)($image['mime_type']??''),'image/');$region=trim((string)($image['tooth_region']??''));?><a class="snapshot-image-card" href="download_document.php?id=<?=(int)$image['id']?>" target="_blank" rel="noopener"><?php if($isImage):?><img src="download_document.php?id=<?=(int)$image['id']?>&amp;preview=1" alt="<?=e((string)$image['category'])?><?= $region!==''?' · '.e($region):'' ?>" loading="lazy"><?php else:?><span class="clinical-image-icon">PDF</span><?php endif;?><span><strong><?=e((string)$image['category'])?></strong><small><?= $region!==''?e((dental_is_valid_fdi_tooth($region)?dental_tooth_display_label($region):$region)):'General / full arch' ?> · <?=e(date('M j, Y',strtotime((string)$image['created_at'])))?></small></span></a><?php endforeach;?></div><?php else:?><p>No X-ray or clinical image recorded.</p><?php endif;?></section>
        </div>
        <?php treatment_render_snapshot_odontogram($row,$findings,$editable); ?>
    </details>
    <?php
}

$carePathEncounterSelect=dental_adaptive_encounter_schema_ready()
    ? '(SELECT c.care_path FROM `' . table('clinical_encounters') . '` c WHERE c.queue_entry_id=q.id ORDER BY c.id DESC LIMIT 1) care_path,'
    : 'NULL care_path,';
$assistantEncounterSelect=encounter_assistant_schema_ready()
    ? '(SELECT c.assistant_user_id FROM `' . table('clinical_encounters') . '` c WHERE c.queue_entry_id=q.id ORDER BY c.id DESC LIMIT 1) assistant_user_id,(SELECT c.assistant_name FROM `' . table('clinical_encounters') . '` c WHERE c.queue_entry_id=q.id ORDER BY c.id DESC LIMIT 1) assistant_name,'
        . $carePathEncounterSelect
        . (clinical_flow_stability_schema_ready()
            ? '(SELECT c.assistant_decision FROM `' . table('clinical_encounters') . '` c WHERE c.queue_entry_id=q.id ORDER BY c.id DESC LIMIT 1) assistant_decision '
            : 'NULL assistant_decision ')
    : 'NULL assistant_user_id,NULL assistant_name,' . $carePathEncounterSelect . 'NULL assistant_decision ';
$queueSql = 'SELECT q.*,p.patient_no,p.first_name,p.middle_name,p.last_name,p.birth_date,p.sex,p.mobile,p.email,p.address,p.emergency_contact,p.medical_alerts,'
    . 'a.start_at,a.end_at,a.status appointment_status,'
    . '(SELECT c.id FROM `' . table('clinical_encounters') . '` c WHERE c.queue_entry_id=q.id ORDER BY c.id DESC LIMIT 1) encounter_id,'
    . '(SELECT c.status FROM `' . table('clinical_encounters') . '` c WHERE c.queue_entry_id=q.id ORDER BY c.id DESC LIMIT 1) encounter_status,'
    . '(SELECT c.paused_at FROM `' . table('clinical_encounters') . '` c WHERE c.queue_entry_id=q.id ORDER BY c.id DESC LIMIT 1) encounter_paused_at,'
    . '(SELECT c.pause_reason FROM `' . table('clinical_encounters') . '` c WHERE c.queue_entry_id=q.id ORDER BY c.id DESC LIMIT 1) encounter_pause_reason,'
    . $assistantEncounterSelect
    . 'FROM `' . table('queue_entries') . '` q '
    . 'JOIN `' . table('patients') . '` p ON p.id=q.patient_id '
    . 'LEFT JOIN `' . table('appointments') . '` a ON a.id=q.appointment_id '
    . 'WHERE (q.status="in_treatment" OR DATE(q.checked_in_at)=CURDATE()) AND q.dentist_user_id=? '
    . 'AND q.status IN ("waiting","called","seated","in_treatment") '
    . 'ORDER BY CASE q.status WHEN "in_treatment" THEN 0 WHEN "seated" THEN 1 WHEN "called" THEN 2 ELSE 3 END,'
    . 'FIELD(q.priority,"emergency","urgent","regular"),q.checked_in_at';
$stmt = $pdo->prepare($queueSql);
$stmt->execute([$dentistId]);
$queueRows = $stmt->fetchAll();

$inTreatment = [];
$seated = [];
$called = [];
$waiting = [];
foreach ($queueRows as $row) {
    if ($row['status'] === 'in_treatment') $inTreatment[] = $row;
    elseif ($row['status'] === 'seated') $seated[] = $row;
    elseif ($row['status'] === 'called') $called[] = $row;
    else $waiting[] = $row;
}
$current = $inTreatment[0] ?? null;

$chairAssignments = [];
if (schema_table_exists(table('doctor_chair_assignments'))) {
    $stmt = $pdo->prepare(
        'SELECT dca.*,cc.chair_code,cc.room_name,cc.status chair_status,b.name branch_name '
        . 'FROM `' . table('doctor_chair_assignments') . '` dca '
        . 'LEFT JOIN `' . table('clinic_chairs') . '` cc ON cc.id=dca.chair_id '
        . 'LEFT JOIN `' . table('branches') . '` b ON b.id=dca.branch_id '
        . 'WHERE dca.dentist_user_id=? AND dca.is_active=1 ORDER BY b.name,dca.chair_name'
    );
    $stmt->execute([$dentistId]);
    $chairAssignments = $stmt->fetchAll();
}

$stmt = $pdo->prepare(
    'SELECT a.*,p.patient_no,p.first_name,p.middle_name,p.last_name,p.medical_alerts '
    . 'FROM `' . table('appointments') . '` a JOIN `' . table('patients') . '` p ON p.id=a.patient_id '
    . 'WHERE DATE(a.start_at)=CURDATE() AND a.dentist_user_id=? '
    . 'ORDER BY a.start_at'
);
$stmt->execute([$dentistId]);
$appointments = $stmt->fetchAll();

$plannedAppointmentIds = [];
foreach ($queueRows as $row) if (!empty($row['appointment_id'])) $plannedAppointmentIds[] = (int)$row['appointment_id'];
foreach ($appointments as $row) if (!empty($row['id'])) $plannedAppointmentIds[] = (int)$row['id'];
$plannedServicesByAppointment = appointment_services_for_ids($pdo, $plannedAppointmentIds);

$stmt = $pdo->prepare(
    'SELECT c.id,c.patient_id,c.created_at,c.updated_at,c.autosaved_at,c.status,c.diagnosis,'
    . 'TRIM(CONCAT(p.first_name," ",COALESCE(NULLIF(p.middle_name,""),"")," ",p.last_name)) patient,p.patient_no '
    . 'FROM `' . table('clinical_encounters') . '` c JOIN `' . table('patients') . '` p ON p.id=c.patient_id '
    . 'WHERE c.dentist_user_id=? AND c.status IN ("draft","pending_review") '
    . 'ORDER BY COALESCE(c.updated_at,c.created_at) DESC LIMIT 10'
);
$stmt->execute([$dentistId]);
$drafts = $stmt->fetchAll();

$delegatedTasks = [];
if (clinical_task_assignment_schema_ready()) {
    $taskSql = 'SELECT t.id task_id,t.status task_status,t.patient_id,t.branch_id,t.treatment_plan_id,t.treatment_plan_item_id,'
        . 't.task_title,t.required_privilege_code,t.reason,t.requested_at,t.decided_at,'
        . 'p.patient_no,p.first_name,p.middle_name,p.last_name,i.procedure_name,i.status item_status,ru.name responsible_dentist,'
        . 'q.id active_queue_id,q.status active_queue_status,q.dentist_user_id queue_dentist_user_id,q.queue_no,q.chair_name,qu.name queue_dentist_name '
        . 'FROM `' . table('clinical_task_assignments') . '` t '
        . 'JOIN `' . table('patients') . '` p ON p.id=t.patient_id '
        . 'LEFT JOIN `' . table('treatment_plan_items') . '` i ON i.id=t.treatment_plan_item_id '
        . 'LEFT JOIN `' . table('users') . '` ru ON ru.id=t.requesting_dentist_user_id '
        . 'LEFT JOIN `' . table('queue_entries') . '` q ON q.id=(SELECT q2.id FROM `' . table('queue_entries') . '` q2 WHERE q2.patient_id=t.patient_id AND DATE(q2.checked_in_at)=CURDATE() AND q2.status IN ("waiting","called","seated","in_treatment") ORDER BY q2.id DESC LIMIT 1) '
        . 'LEFT JOIN `' . table('users') . '` qu ON qu.id=q.dentist_user_id '
        . 'WHERE t.assigned_dentist_user_id=? AND t.status IN ("pending","accepted","in_progress") '
        . 'ORDER BY FIELD(t.status,"pending","accepted","in_progress"),t.requested_at DESC LIMIT 30';
    $stmt = $pdo->prepare($taskSql);
    $stmt->execute([$dentistId]);
    $delegatedTasks = $stmt->fetchAll();
}

$activePlanCounts = [];
$activeFindingCounts = [];
$patientIds = array_values(array_unique(array_map(static fn(array $row): int => (int) $row['patient_id'], $queueRows)));
if ($patientIds) {
    $placeholders = implode(',', array_fill(0, count($patientIds), '?'));
    if (schema_table_exists(table('treatment_plans'))) {
        $stmt = $pdo->prepare('SELECT patient_id,COUNT(*) total FROM `' . table('treatment_plans') . '` WHERE patient_id IN (' . $placeholders . ') AND status IN ("draft","presented","partially_accepted","accepted","scheduled","in_progress") GROUP BY patient_id');
        $stmt->execute($patientIds);
        foreach ($stmt->fetchAll() as $row) $activePlanCounts[(int) $row['patient_id']] = (int) $row['total'];
    }
    if (schema_table_exists(table('odontogram_entries')) && schema_column_exists(table('odontogram_entries'), 'severity')) {
        $stmt = $pdo->prepare('SELECT patient_id,COUNT(*) total FROM `' . table('odontogram_entries') . '` WHERE patient_id IN (' . $placeholders . ') AND status="active" AND severity IN ("severe","critical") GROUP BY patient_id');
        $stmt->execute($patientIds);
        foreach ($stmt->fetchAll() as $row) $activeFindingCounts[(int) $row['patient_id']] = (int) $row['total'];
    }
}

$patientSnapshots = [];
foreach ($queueRows as $row) {
    $patientSnapshots[(int)$row['id']] = treatment_patient_snapshot($pdo, $row);
}

$chairGroups = [];
$chairConflictIds = [];
foreach (array_merge($inTreatment, $seated) as $row) {
    $identity = queue_chair_identity($row);
    $key = $identity['chair_id'] > 0
        ? 'id:' . $identity['chair_id']
        : 'branch:' . $identity['branch_id'] . ':name:' . mb_strtolower($identity['chair_name']);
    if ($identity['chair_id'] < 1 && $identity['chair_name'] === '') $key = 'missing:' . (int)$row['id'];
    $chairGroups[$key][] = $row;
}
foreach ($chairGroups as $rowsInChair) {
    if (count($rowsInChair) > 1) foreach ($rowsInChair as $row) $chairConflictIds[(int)$row['id']] = true;
}

$billingCorrections=[];
$incomingTransfers=[];
$emergencyCoverage=[];
if(workflow_governance_schema_ready()){
    $correctionStmt=$pdo->prepare(
        'SELECT b.*,pr.procedure_name,pr.tooth_region,q.queue_no,TRIM(CONCAT(p.first_name," ",COALESCE(NULLIF(p.middle_name,""),"")," ",p.last_name)) patient,p.patient_no '
        . 'FROM `' . table('billing_correction_requests') . '` b '
        . 'JOIN `' . table('patients') . '` p ON p.id=b.patient_id '
        . 'LEFT JOIN `' . table('procedures') . '` pr ON pr.id=b.procedure_id '
        . 'LEFT JOIN `' . table('queue_entries') . '` q ON q.id=b.queue_entry_id '
        . 'WHERE b.assigned_dentist_user_id=? AND b.status IN ("open","in_review") ORDER BY b.requested_at ASC,b.id ASC LIMIT 30'
    );
    $correctionStmt->execute([$dentistId]);
    $billingCorrections=$correctionStmt->fetchAll()?:[];

    $transferStmt=$pdo->prepare(
        'SELECT t.*,TRIM(CONCAT(p.first_name," ",COALESCE(NULLIF(p.middle_name,""),"")," ",p.last_name)) patient,p.patient_no,f.name from_dentist_name '
        . 'FROM `' . table('clinical_encounter_transfers') . '` t JOIN `' . table('patients') . '` p ON p.id=t.patient_id '
        . 'LEFT JOIN `' . table('users') . '` f ON f.id=t.from_dentist_user_id '
        . 'WHERE t.to_dentist_user_id=? AND t.status IN ("pending","accepted") ORDER BY FIELD(t.status,"pending","accepted"),t.requested_at ASC LIMIT 30'
    );
    $transferStmt->execute([$dentistId]);
    $incomingTransfers=$transferStmt->fetchAll()?:[];

    if($isDentist){
        $coverageStmt=$pdo->prepare(
            'SELECT c.id encounter_id,c.dentist_user_id,TRIM(CONCAT(p.first_name," ",COALESCE(NULLIF(p.middle_name,""),"")," ",p.last_name)) patient,p.patient_no,u.name responsible_dentist,q.queue_no,q.chair_name '
            . 'FROM `' . table('clinical_encounters') . '` c JOIN `' . table('patients') . '` p ON p.id=c.patient_id '
            . 'JOIN `' . table('queue_entries') . '` q ON q.id=c.queue_entry_id AND q.status="in_treatment" '
            . 'LEFT JOIN `' . table('users') . '` u ON u.id=c.dentist_user_id '
            . 'WHERE c.branch_id=? AND c.dentist_user_id<>? AND c.status IN ("draft","pending_review") ORDER BY q.treatment_started_at ASC LIMIT 12'
        );
        $coverageStmt->execute([(int)($profile['branch_id']??$user['branch_id']??0),$dentistId]);
        $emergencyCoverage=$coverageStmt->fetchAll()?:[];
    }
}


function treatment_render_action_suggestions(array $row, array $snapshot, bool $active): void
{
    $suggestions = [];
    if (!$active && ($row['status'] ?? '') === 'seated') $suggestions[] = ['Start today’s encounter', 'Open the clinical workspace from this seated patient, then finish screening, charting, treatment, and billing handoff in one flow.'];
    if (empty($row['intake_completed_at'])) $suggestions[] = ['Complete intake review', 'Confirm allergies, medicines, health changes relevant to dental care, consent, and pain/vitals before finalizing treatment.'];
    if (!empty($snapshot['unresolved_services'])) $suggestions[] = ['Review carry-forward services', 'Previous deferred or moved services are linked forward. Do not rebill until actually performed today.'];
    if (($snapshot['last_encounter']['status'] ?? '') === 'draft') $suggestions[] = ['Close old draft if needed', 'A previous draft exists. Review it before starting a separate new clinical note.'];
    if (!empty($row['medical_alerts'])) $suggestions[] = ['Acknowledge dental safety alert', 'Review the alert before anesthesia, prescription, extraction, or invasive care.'];
    if (!$suggestions) $suggestions[] = ['Ready for clinical work', 'Proceed in order: screening → assessment/charting → procedures → follow-up/billing handoff → finalize.'];
    ?>
    <div class="treatment-suggestions"><strong>Suggested next step</strong><ul><?php foreach($suggestions as [$title,$text]):?><li><span><?=e($title)?></span><small><?=e($text)?></small></li><?php endforeach;?></ul></div>
    <?php
}

$dentists = !$isDentist ? dentist_options() : [];
render_header($isDentist ? 'My Treatment Dashboard' : 'Doctor Treatment Dashboard');
?>
<?php if (function_exists('dentalcare_render_role_lane_card')) dentalcare_render_role_lane_card($isDentist ? 'dentist' : active_role(), 'doctor-treatment-flow-card'); ?>
<?php if ($dentists): ?>
<form class="card compact-filter" method="get">
    <label>Doctor
        <select name="dentist_id" onchange="this.form.submit()">
            <?php foreach ($dentists as $doctor): ?>
                <option value="<?= (int) $doctor['id'] ?>" <?= $dentistId === (int) $doctor['id'] ? 'selected' : '' ?>><?= e($doctor['display_name'] ?: $doctor['name']) ?></option>
            <?php endforeach; ?>
        </select>
    </label>
    <noscript><button class="btn ghost">Open</button></noscript>
</form>
<?php endif; ?>

<?php if (!$isDentist): ?>
<div class="task-view-notice"><strong>Read-only doctor view.</strong> You can review chair and treatment flow, but only the assigned authenticated dentist can start, write, or finalize treatment.</div>
<?php endif; ?>

<section class="card treatment-dashboard-heading">
    <div class="treatment-doctor-identity">
        <div class="doctor-avatar treatment-doctor-avatar"><?php if(!empty($profile['photo_path'])):?><img src="doctor_asset.php?type=photo&user_id=<?=$dentistId?>" alt="<?=e(dentist_display_name($profile))?>"><?php else:?><span><?=e(strtoupper(substr(dentist_display_name($profile),0,1)))?></span><?php endif;?></div>
        <div><span class="eyebrow">Live doctor workspace</span><h2><?= e(dentist_display_name($profile)) ?></h2><p><?= e($profile['specialty_name'] ?: 'Dentist') ?> · <?= e(date('l, F j, Y')) ?></p></div>
    </div>
    <div class="status-actions">
        <a class="btn ghost" href="doctor_profile.php?user_id=<?=$dentistId?>"><?=!empty($profile['photo_path'])?'Doctor profile':'Add profile photo'?></a>
        <a class="btn ghost" href="doctor_schedule.php<?= !$isDentist ? '?doctor_id=' . $dentistId : '' ?>">Schedule</a>
        <a class="btn ghost" href="queue.php">Clinic queue</a>
        <a class="btn ghost" href="clinical.php">Encounter records</a>
    </div>
</section>

<div class="live-treatment-flow" data-live-queue-region="doctor-treatment-flow">
<section class="stats role-stats treatment-dashboard-stats">
    <?php stat_card('In treatment', count($inTreatment), $current ? (string) ($current['chair_name'] ?: 'Chair not recorded') : 'No active patient'); ?>
    <?php stat_card('Seated and ready', count($seated), 'Ready for doctor'); ?>
    <?php stat_card('Waiting / called', count($waiting) + count($called), 'Assigned today'); ?>
    <?php stat_card('Draft records', count($drafts), 'Need completion'); ?>
</section>

<?php if($billingCorrections): ?>
<section class="card delegated-task-panel">
    <div class="card-head"><div><span class="eyebrow">Cashier exception returned to clinical care</span><h2>Billing corrections requiring your signature</h2><p>The Cashier cannot price or rename a clinical procedure. Open the finalized encounter, select the actual approved service, and sign the correction under your own professional identity.</p></div><span class="badge warning"><?=count($billingCorrections)?></span></div>
    <div class="delegated-task-grid">
        <?php foreach($billingCorrections as $correction): ?>
        <article class="delegated-task-card pending"><div class="delegated-task-title"><div><strong><?=e((string)$correction['patient'])?></strong><small><?=e((string)$correction['patient_no'])?><?=!empty($correction['queue_no'])?' · Queue '.e((string)$correction['queue_no']):''?></small></div><span class="badge warning">Fee correction</span></div><p><strong><?=e((string)($correction['procedure_name']?:'Unidentified completed procedure'))?></strong><?=!empty($correction['tooth_region'])?' · '.e((string)$correction['tooth_region']):''?><br><?=e((string)$correction['reason'])?></p><div class="status-actions"><a class="btn primary" href="clinical_workspace.php?encounter_id=<?=(int)$correction['encounter_id']?>#treatment">Correct billing source</a><a class="btn ghost" href="patients.php?action=view&amp;id=<?=(int)$correction['patient_id']?>&amp;tab=clinical">Patient record</a></div></article>
        <?php endforeach; ?>
    </div>
</section>
<?php endif; ?>

<?php if($incomingTransfers): ?>
<section class="card delegated-task-panel">
    <div class="card-head"><div><span class="eyebrow">Dentist-to-Dentist request</span><h2>Consultations and responsibility transfers</h2><p>Review the patient record before accepting. A transfer changes the responsible Dentist only after your acceptance; a consultation keeps responsibility with the requesting Dentist.</p></div><span class="badge"><?=count($incomingTransfers)?></span></div>
    <div class="delegated-task-grid">
        <?php foreach($incomingTransfers as $transfer): ?>
        <article class="delegated-task-card <?=e((string)$transfer['status'])?>"><div class="delegated-task-title"><div><strong><?=e((string)$transfer['patient'])?></strong><small><?=e((string)$transfer['patient_no'])?> · From <?=e((string)($transfer['from_dentist_name']?:'Dentist'))?></small></div><span class="badge <?=($transfer['status']==='pending'?'warning':'')?>"><?=e(module_status((string)$transfer['request_type']))?> · <?=e(module_status((string)$transfer['status']))?></span></div><p><?=e((string)$transfer['reason'])?></p><div class="status-actions"><a class="btn primary" href="clinical_workspace.php?encounter_id=<?=(int)$transfer['encounter_id']?>">Review encounter</a></div></article>
        <?php endforeach; ?>
    </div>
</section>
<?php endif; ?>

<?php if($isDentist&&$emergencyCoverage): ?>
<details class="card"><summary><strong>Emergency coverage · <?=count($emergencyCoverage)?> active encounter(s) under another Dentist</strong></summary><p class="muted">Use only when immediate clinical continuity is required and the responsible Dentist cannot continue. Opening a record does not transfer responsibility; the emergency takeover still requires your reason and your own verified license.</p><div class="compact-flow-list"><?php foreach($emergencyCoverage as $coverage):?><article class="compact-flow-patient"><div><strong><?=e((string)$coverage['patient'])?></strong><small><?=e((string)$coverage['patient_no'])?> · Queue <?=e((string)$coverage['queue_no'])?> · <?=e((string)($coverage['chair_name']?:'Chair not recorded'))?></small></div><div><span class="badge warning">Responsible: <?=e((string)($coverage['responsible_dentist']?:'Dentist'))?></span><a class="btn ghost compact" href="clinical_workspace.php?encounter_id=<?=(int)$coverage['encounter_id']?>&amp;emergency=1">Emergency review</a></div></article><?php endforeach;?></div></details>
<?php endif; ?>

<?php if ($delegatedTasks): ?>
<section class="card delegated-task-panel">
    <div class="card-head"><div><span class="eyebrow">Specific procedure responsibility</span><h2>Delegated clinical tasks</h2><p>These assignments grant access only to the named patient and treatment item. They do not transfer the complete treatment plan.</p></div><a href="clinical_tasks.php">Manage all tasks</a></div>
    <div class="delegated-task-grid">
        <?php foreach ($delegatedTasks as $task):
            $taskPending = (string)$task['task_status'] === 'pending';
            $queueAssignedHere = !empty($task['active_queue_id']) && (int)$task['queue_dentist_user_id'] === $dentistId;
            $queueAssignedElsewhere = !empty($task['active_queue_id']) && (int)$task['queue_dentist_user_id'] > 0 && !$queueAssignedHere;
        ?>
        <article class="delegated-task-card <?= $taskPending ? 'pending' : 'accepted' ?>">
            <div class="delegated-task-title"><div><strong><?= e(patient_full_name($task)) ?></strong><small><?= e((string)$task['patient_no']) ?> · <?= e((string)($task['procedure_name'] ?: $task['task_title'])) ?></small></div><span class="badge <?= $taskPending ? 'warning' : '' ?>"><?= e(module_status((string)$task['task_status'])) ?></span></div>
            <p><?= e((string)$task['reason']) ?></p>
            <div class="delegated-task-meta"><span><b>Required privilege</b><?= e(module_status((string)($task['required_privilege_code'] ?: 'consultation'))) ?></span><span><b>Responsible Dentist</b><?= e((string)($task['responsible_dentist'] ?: 'Clinic administration')) ?></span></div>
            <?php if ($taskPending): ?>
                <div class="notice warning">Accept or decline this task before performing the procedure.</div>
            <?php elseif ($queueAssignedHere): ?>
                <div class="notice success">The patient is routed to your active queue<?= !empty($task['chair_name']) ? ' · '.e((string)$task['chair_name']) : '' ?>. Use the patient flow above when seated.</div>
            <?php elseif ($queueAssignedElsewhere): ?>
                <div class="notice warning">The task is accepted, but today’s active visit is still routed to <?= e((string)($task['queue_dentist_name'] ?: 'another Dentist')) ?>. Reception must route the active chair/visit before you start this procedure.</div>
            <?php else: ?>
                <div class="notice">Patient profile and treatment-plan access are active. At check-in, Reception must route the active visit/chair to you for this specific procedure.</div>
            <?php endif; ?>
            <div class="status-actions">
                <?php if ($taskPending): ?><a class="btn primary" href="clinical_tasks.php?item_id=<?= (int)$task['treatment_plan_item_id'] ?>">Review task</a><?php endif; ?>
                <a class="btn ghost" href="patients.php?action=view&amp;id=<?= (int)$task['patient_id'] ?>&amp;tab=clinical">Patient profile</a>
                <a class="btn ghost" href="treatment.php?patient_id=<?= (int)$task['patient_id'] ?>&amp;plan_id=<?= (int)$task['treatment_plan_id'] ?>">Treatment plan</a>
            </div>
        </article>
        <?php endforeach; ?>
    </div>
</section>
<?php endif; ?>

<?php if (count($inTreatment) > 1): ?>
<div class="alert error"><strong>Multiple active treatments detected.</strong> Only one patient may be actively treated by this dentist at a time. Finalize the correct encounter and return the other patient to the queue.</div>
<?php endif; ?>
<?php if ($chairConflictIds): ?>
<div class="alert error"><strong>Chair occupancy conflict detected.</strong> More than one patient is marked seated or in treatment in the same chair. Choose the patient who is actually in the chair and select <b>Start treatment</b>; DentalCare will return the other merely seated ticket(s) to waiting. An already active treatment is never moved automatically.</div>
<?php endif; ?>

<section class="chair-command-grid">
    <?php if (!$chairAssignments): ?>
        <article class="card chair-command-card warning-card">
            <span class="eyebrow">Chair assignment</span>
            <h3>No doctor-bound chair assigned</h3>
            <p>The doctor can still see assigned patients, but Reception and assistants need a formal chair assignment to seat them consistently.</p>
            <?php if ($isAdministrativeAccount): ?><a class="btn ghost" href="chairs.php">Assign chair</a><?php endif; ?>
        </article>
    <?php else: ?>
        <?php foreach ($chairAssignments as $chair):
            $occupants = [];
            foreach (array_merge($inTreatment, $seated) as $row) {
                if ((int) ($chair['branch_id'] ?? 0) !== (int) ($row['branch_id'] ?? 0)) continue;
                if ((int) ($chair['chair_id'] ?? 0) > 0 && (int) ($row['chair_id'] ?? 0) === (int) $chair['chair_id']) { $occupants[] = $row; continue; }
                if ((string) ($row['chair_name'] ?? '') !== '' && strcasecmp((string) $row['chair_name'], (string) $chair['chair_name']) === 0) $occupants[] = $row;
            }
            $occupant = $occupants[0] ?? null;
            $chairConflict = count($occupants) > 1;
        ?>
        <article class="card chair-command-card <?= $chairConflict ? 'conflict' : ($occupant ? 'occupied' : 'available') ?>">
            <div class="card-head">
                <div><span class="eyebrow"><?= e((string) ($chair['branch_name'] ?: 'Clinic branch')) ?></span><h3><?= e((string) $chair['chair_name']) ?></h3></div>
                <span class="badge"><?= $chairConflict ? count($occupants).' patients' : ($occupant ? e(ucwords(str_replace('_', ' ', (string) $occupant['status']))) : 'Available') ?></span>
            </div>
            <p><?= e((string) ($chair['room_name'] ?: 'Treatment area')) ?><?= !empty($chair['chair_code']) ? ' · ' . e((string) $chair['chair_code']) : '' ?></p>
            <?php foreach ($occupants as $chairPatient): ?>
                <div class="chair-patient"><strong><?= e(patient_full_name($chairPatient)) ?></strong><span>Queue <?= e((string) $chairPatient['queue_no']) ?> · <?= e(ucwords(str_replace('_',' ',(string)$chairPatient['status']))) ?> · <?= e((string) ($chairPatient['service_name'] ?: 'Dental visit')) ?></span></div>
            <?php endforeach; ?>
            <?php if ($chairConflict): ?><small class="danger-text">Resolve the duplicate seating before continuing treatment.</small><?php elseif ($occupant): ?><small><?= $occupant['status'] === 'in_treatment' ? 'Treatment time ' . e(treatment_elapsed($occupant['treatment_started_at'] ?? null)) : 'Seated ' . e(treatment_elapsed($occupant['seated_at'] ?? null)) ?></small><?php else: ?><small>Ready for the next assigned patient.</small><?php endif; ?>
        </article>
        <?php endforeach; ?>
    <?php endif; ?>
</section>

<?php if ($current): ?>
<section class="card active-treatment-cockpit">
    <div class="active-treatment-primary">
        <span class="eyebrow">Currently treating</span>
        <h2><?= e(patient_full_name($current)) ?></h2>
        <p><?= e((string) $current['patient_no']) ?> · Queue <?= e((string) $current['queue_no']) ?> · <?= e((string) ($current['service_name'] ?: 'Dental visit')) ?></p>
        <?php treatment_render_planned_services($plannedServicesByAppointment[(int)($current['appointment_id'] ?? 0)] ?? []); ?>
        <div class="treatment-meta-strip">
            <span><strong>Chair</strong><?= e((string) ($current['chair_name'] ?: 'Not recorded')) ?></span>
            <span><strong>Started</strong><?= e(treatment_elapsed($current['treatment_started_at'] ?? null)) ?> ago</span>
            <span><strong>Priority</strong><?= e(ucfirst((string) $current['priority'])) ?></span>
            <span><strong>Intake</strong><?= !empty($current['intake_completed_at']) ? 'Complete' : 'Pending' ?></span>
            <span><strong>Encounter path</strong><?=e(dental_encounter_care_path_label((string)($current['care_path']??dental_encounter_default_care_path($current))))?></span>
            <span><strong>Dental Assistant</strong><?=e((string)(($current['assistant_name']??'')?:'Not assigned'))?></span>
        </div>
        <?php treatment_flow_render_mini($current, $pdo); ?>
        <?php if (!empty($current['medical_alerts'])): ?><div class="alert error"><strong>Dental safety alert</strong><?= nl2br(e((string) $current['medical_alerts'])) ?></div><?php endif; ?>
    </div>
    <div class="active-treatment-actions">
        <?php if ($isDentist && isset($chairConflictIds[(int)$current['id']])): ?>
            <?php treatment_start_form($current, 'Resolve conflict & continue'); ?>
        <?php elseif (!empty($current['encounter_id']) && clinical_assistant_decision_complete($current)): ?>
            <a class="btn primary" href="clinical_workspace.php?encounter_id=<?= (int) $current['encounter_id'] ?>">Continue treatment</a><?php if($isDentist):?><a class="btn ghost" href="clinical_workspace.php?encounter_id=<?= (int) $current['encounter_id'] ?>&amp;assign_assistant=1">Assign / change assistant</a><?php endif;?>
        <?php elseif ($isDentist): ?>
            <?php treatment_start_form($current, 'Confirm team & continue'); ?>
        <?php endif; ?>
        <?php if (!empty($current['encounter_id']) && $isDentist): ?>
            <a class="btn ghost" href="clinical_workspace.php?encounter_id=<?= (int) $current['encounter_id'] ?>&amp;open_xray=1#charting">Capture X-ray</a>
        <?php endif; ?>
        <a class="btn ghost" href="odontogram.php?patient_id=<?= (int) $current['patient_id'] ?><?= !empty($current['encounter_id']) ? '&encounter_id=' . (int) $current['encounter_id'] : '' ?>">Open tooth model</a>
        <a class="btn ghost" href="treatment.php?patient_id=<?= (int) $current['patient_id'] ?>">Treatment plan</a>
        <a class="btn ghost" href="patients.php?action=view&id=<?= (int) $current['patient_id'] ?>&tab=clinical">Patient record</a>
    </div>
    <?php treatment_render_action_suggestions($current, $patientSnapshots[(int)$current['id']] ?? [], true); ?>
</section>
<?php treatment_render_snapshot($current, $patientSnapshots[(int)$current['id']] ?? [], true, $isDentist && !empty($current['encounter_id'])); ?>
<?php else: ?>
<section class="card empty-state treatment-empty-state">
    <h2>No patient is currently in treatment</h2>
    <p><?= $seated ? 'A patient is seated and ready. Start the encounter from the ready list below.' : 'Reception or the dental assistant must call and seat an assigned patient before treatment begins.' ?></p>
</section>
<?php endif; ?>

<div class="doctor-treatment-columns">
<section class="card ready-patient-panel">
    <div class="card-head"><div><h2>Seated and ready</h2><p>Patients physically placed in the doctor’s assigned chair.</p></div><span class="badge"><?= count($seated) ?></span></div>
    <div class="treatment-patient-list">
        <?php foreach ($seated as $row): ?>
        <article class="treatment-patient-card <?= isset($chairConflictIds[(int)$row['id']]) ? 'chair-conflict' : '' ?>" id="queue-entry-<?=(int)$row['id']?>">
            <div>
                <span class="eyebrow"><?= e((string) ($row['chair_name'] ?: 'Chair not recorded')) ?> · <?= e((string) $row['queue_no']) ?></span>
                <h3><?= e(patient_full_name($row)) ?></h3>
                <p><?= e((string) ($row['service_name'] ?: 'Dental visit')) ?> · Seated <?= e(treatment_elapsed($row['seated_at'] ?? null)) ?> ago</p>
                <?php treatment_render_planned_services($plannedServicesByAppointment[(int)($row['appointment_id'] ?? 0)] ?? [], true); ?>
                <div class="patient-risk-badges">
                    <?php if (isset($chairConflictIds[(int)$row['id']])): ?><span class="badge danger">Chair conflict</span><?php endif; ?>
                    <?php if (!empty($row['medical_alerts'])): ?><span class="badge danger">Dental safety alert</span><?php endif; ?>
                    <?php if (($activeFindingCounts[(int) $row['patient_id']] ?? 0) > 0): ?><span class="badge danger"><?= (int) $activeFindingCounts[(int) $row['patient_id']] ?> severe tooth finding(s)</span><?php endif; ?>
                    <?php if (($activePlanCounts[(int) $row['patient_id']] ?? 0) > 0): ?><span class="badge"><?= (int) $activePlanCounts[(int) $row['patient_id']] ?> active plan(s)</span><?php endif; ?>
                </div>
                <?php treatment_flow_render_mini($row, $pdo); ?>
            </div>
            <div class="status-actions">
                <?php if ($isDentist): ?><?php treatment_start_form($row, !empty($row['encounter_id']) ? 'Start treatment' : 'Start treatment'); ?>
                <?php elseif (!empty($row['encounter_id'])): ?><a class="btn primary" href="clinical_workspace.php?encounter_id=<?= (int) $row['encounter_id'] ?>">Open encounter</a><?php endif; ?>
                <a class="btn ghost" href="odontogram.php?patient_id=<?= (int) $row['patient_id'] ?><?= !empty($row['encounter_id']) ? '&encounter_id=' . (int)$row['encounter_id'] : '' ?>">Tooth model</a>
                <a class="btn ghost" href="patients.php?action=view&id=<?= (int)$row['patient_id'] ?>&tab=clinical">Full record</a>
            </div>
            <?php treatment_render_action_suggestions($row, $patientSnapshots[(int)$row['id']] ?? [], false); ?>
            <?php treatment_render_snapshot($row, $patientSnapshots[(int)$row['id']] ?? [], false, false); ?>
        </article>
        <?php endforeach; ?>
        <?php if (!$seated): ?><div class="queue-empty">No patient is seated for this doctor.</div><?php endif; ?>
    </div>
</section>

<section class="card doctor-queue-panel">
    <div class="card-head"><div><h2>Assigned patient flow</h2><p>Called and waiting patients assigned to this doctor.</p></div><a href="queue.php">Full queue</a></div>
    <div class="compact-flow-list">
        <?php foreach (array_merge($called, $waiting) as $row): ?>
        <article class="compact-flow-patient">
            <div><strong><?= e(patient_full_name($row)) ?></strong><small>Queue <?= e((string) $row['queue_no']) ?> · <?= e((string) ($row['service_name'] ?: 'Dental visit')) ?></small><?php treatment_render_planned_services($plannedServicesByAppointment[(int)($row['appointment_id'] ?? 0)] ?? [], true); ?><?php if(!empty($row['encounter_paused_at'])):?><span class="badge warning">Treatment paused</span><small><?=e((string)($row['encounter_pause_reason']?:'Resume when ready'))?></small><?php endif;?><?php if(!empty($row['medical_alerts'])):?><span class="badge danger">Dental safety alert</span><?php endif;?></div>
            <div><span class="badge"><?= e(ucwords(str_replace('_', ' ', (string) $row['status']))) ?></span><small><?= e(treatment_elapsed($row['checked_in_at'] ?? null)) ?> in clinic</small></div>
            <?php treatment_flow_render_mini($row, $pdo); ?>
            <?php treatment_render_action_suggestions($row, $patientSnapshots[(int)$row['id']] ?? [], false); ?>
            <?php treatment_render_snapshot($row, $patientSnapshots[(int)$row['id']] ?? [], false, false); ?>
        </article>
        <?php endforeach; ?>
        <?php if (!$called && !$waiting): ?><div class="queue-empty">No additional assigned patients are waiting.</div><?php endif; ?>
    </div>
</section>
</div>

<div class="grid-2 treatment-support-grid">
<section class="card table-wrap">
    <div class="card-head"><h2>Unfinished clinical records</h2><a href="clinical.php">All encounters</a></div>
    <table><thead><tr><th>Patient</th><th>Last saved</th><th>Status</th><th></th></tr></thead><tbody>
    <?php foreach ($drafts as $draft): ?><tr><td><strong><?= e((string) $draft['patient']) ?></strong><br><small><?= e((string) $draft['patient_no']) ?></small></td><td><?= e(date('M j, g:i A', strtotime((string) ($draft['autosaved_at'] ?: $draft['updated_at'] ?: $draft['created_at'])))) ?></td><td><span class="badge"><?= e(ucwords(str_replace('_', ' ', (string) $draft['status']))) ?></span></td><td><a href="clinical_workspace.php?encounter_id=<?= (int) $draft['id'] ?>">Continue</a></td></tr><?php endforeach; ?>
    <?php if (!$drafts): ?><tr><td colspan="4" class="muted">No unfinished clinical records.</td></tr><?php endif; ?>
    </tbody></table>
</section>
<section class="card table-wrap">
    <div class="card-head"><h2>Today's appointments</h2><a href="appointments.php">Full schedule</a></div>
    <table><thead><tr><th>Time</th><th>Patient</th><th>Service</th><th>Chair</th><th>Status</th></tr></thead><tbody>
    <?php foreach ($appointments as $appointment): ?><tr><td><?= e(date('g:i A', strtotime((string) $appointment['start_at']))) ?></td><td><strong><?= e(patient_full_name($appointment)) ?></strong><br><small><?= e((string) $appointment['patient_no']) ?></small></td><td><?= e((string) ($appointment['service_name'] ?: 'Dental visit')) ?><?php treatment_render_planned_services($plannedServicesByAppointment[(int)$appointment['id']] ?? [], true); ?></td><td><?= e((string) ($appointment['chair_name'] ?: '—')) ?></td><td><span class="badge"><?= e(ucwords(str_replace('_', ' ', (string) $appointment['status']))) ?></span></td></tr><?php endforeach; ?>
    <?php if (!$appointments): ?><tr><td colspan="5" class="muted">No appointments scheduled today.</td></tr><?php endif; ?>
    </tbody></table>
</section>
</div>
</div>
<script src="public/assets/js/dental-chart.js?v=<?=e(app_release_version())?>"></script><?php render_footer(); ?>
