<?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';

$pdo = db();
$user = current_user() ?? [];
$actualRole = actual_role();
$isRealDentist = active_role_is('dentist');
$isAdministrativeAccount = in_array($actualRole, ['super_admin','clinic_admin'], true);
$dentistId = $isRealDentist ? (int) $user['id'] : (int) ($_GET['dentist_id'] ?? 0);
if (!$isRealDentist && !$isAdministrativeAccount) {
    http_response_code(403);
    render_header('Clinical day access');
    ?><section class="card setup-empty-state"><h2>Clinical day workspace unavailable</h2><p>This page 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;
}
if ($dentistId <= 0) {
    $dentistId = (int) (dentist_options()[0]['id'] ?? 0);
}
$profile = dentist_profile($dentistId);
if (!$profile) {
    http_response_code(200);
    $availableDentists = dentist_options();
    render_header($isRealDentist ? 'My Clinical Day' : 'Dentist Clinical Day');
    ?>
    <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 clinical day view now shows this setup guide instead of a blank white screen.</p>
        <div class="notice warning"><strong>Clinical day is paused:</strong> create or complete a Dentist profile before assigning and treating patients.</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 clinical day<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 clinical_day_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 clinical_day_start_action(array $row, string $buttonLabel = 'Start Encounter', string $buttonClass = 'btn primary'): void
{
    $queueId = (int)($row['id'] ?? 0);
    $status = (string)($row['status'] ?? '');
    if ($queueId < 1) 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="<?= e($buttonClass) ?>" type="submit">Open Encounter</button>
        </form>
        <?php
        return;
    }
    if ($status === 'in_treatment') $buttonLabel = 'Confirm team & open';
    $dialogId = 'clinical-day-start-assistant-' . $queueId;
    $assistantOptions = clinical_day_assistant_options((int)($row['branch_id'] ?? 0));
    ?>
    <button class="<?= e($buttonClass) ?>" type="button" data-open="<?= e($dialogId) ?>"><?= e($buttonLabel) ?></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 clinical encounter</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> Confirm whether a Dental Assistant is working with the Dentist before treatment starts.</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>
            <label class="wide">Dental Assistant<select name="assistant_user_id" data-dialog-initial-focus><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>
            <p class="muted wide"><?= $assistantOptions ? 'Choose the assistant now, or continue with no Dental Assistant for this visit.' : 'No active Dental Assistant account is configured for this branch. The Dentist can continue alone and assign one later if needed.' ?></p>
            <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
}

$today = date('Y-m-d');
$stmt = $pdo->prepare(
    'SELECT q.*,p.patient_no,p.first_name,p.middle_name,p.last_name,p.birth_date,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.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,'
    . (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 ')
    . '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 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->execute([$dentistId]);
$queueRows = $stmt->fetchAll();
$currentPatient = null;
foreach ($queueRows as $row) {
    if ($row['status'] === 'in_treatment') { $currentPatient = $row; break; }
}
if (!$currentPatient) $currentPatient = $queueRows[0] ?? null;

$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)=? AND a.dentist_user_id=? ORDER BY a.start_at'
);
$stmt->execute([$today,$dentistId]);
$appointments = $stmt->fetchAll();

$stmt = $pdo->prepare(
    'SELECT c.id,c.patient_id,c.created_at,c.updated_at,c.autosaved_at,c.status,c.diagnosis,CONCAT(p.first_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 12'
);
$stmt->execute([$dentistId]);
$drafts = $stmt->fetchAll();

$stmt = $pdo->prepare('SELECT COUNT(*) FROM `' . table('follow_ups') . '` WHERE dentist_user_id=? AND status IN ("pending","scheduled") AND recommended_date<=CURDATE()');
$stmt->execute([$dentistId]);
$followupsDue = (int) $stmt->fetchColumn();

$profileMissing = [];
foreach (['license_number'=>'license number','specialty_id'=>'specialty','primary_branch_id'=>'primary branch'] as $key=>$label) {
    if (empty($profile[$key])) $profileMissing[]=$label;
}
$licenseWarning = null;
if (!empty($profile['license_expiry'])) {
    $daysToExpiry = (int) floor((strtotime((string) $profile['license_expiry']) - strtotime(date('Y-m-d'))) / 86400);
    if ($daysToExpiry < 0) $licenseWarning = 'Professional license expired on ' . date('M j, Y', strtotime((string) $profile['license_expiry'])) . '. Clinical finalization is blocked.';
    elseif ($daysToExpiry <= 60) $licenseWarning = 'Professional license expires in ' . $daysToExpiry . ' day(s), on ' . date('M j, Y', strtotime((string) $profile['license_expiry'])) . '.';
}
$dentists = !$isRealDentist ? dentist_options() : [];
render_header($isRealDentist ? 'My Clinical Day' : 'Dentist Clinical Day');
?>
<?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(!$isRealDentist):?><div class="task-view-notice"><strong>Read-only clinical view.</strong> You are reviewing the doctor workflow as <?=e(role_profile($actualRole)['name'])?>. Only the authenticated dentist can create, finalize, or sign clinical records.</div><?php endif;?>
<?php if($licenseWarning):?><div class="flash warning"><strong>License notice:</strong> <?=e($licenseWarning)?></div><?php endif;?>
<?php if($profileMissing):?><div class="flash error"><strong>Professional setup incomplete:</strong> <?=e(implode(', ',$profileMissing))?>. <a href="doctor_profile.php?user_id=<?=$dentistId?>">Complete profile</a>.</div><?php endif;?>
<section class="clinical-day-heading card"><div><span class="eyebrow"><?= $isRealDentist ? 'My Clinical Day' : 'Dentist Review' ?></span><h2><?=e(dentist_display_name($profile))?></h2><p><?=e($profile['specialty_name']?:'Dentist')?> · <?=e(date('l, F j, Y'))?></p></div><div class="status-actions"><a class="btn ghost" href="doctor_profile.php?user_id=<?=$dentistId?>"><?= $isRealDentist ? 'Professional credentials' : 'Professional credentials' ?></a><a class="btn ghost" href="doctor_schedule.php<?=!$isRealDentist?'?doctor_id='.$dentistId:''?>">My Schedule</a></div></section>

<div data-live-queue-region="clinical-day-flow">
<section class="stats role-stats">
<?php stat_card('Waiting patients',count($queueRows),'Assigned today');stat_card("Today's appointments",count($appointments),'Scheduled');stat_card('Draft notes',count($drafts),'Need completion');stat_card('Follow-ups due',$followupsDue,'Assigned to doctor'); ?>
</section>

<?php if($currentPatient):?>
<section class="now-serving card">
<div><span class="eyebrow"><?=$currentPatient['status']==='in_treatment'?'Now treating':'Next patient'?></span><h2><?=e(patient_full_name($currentPatient))?></h2><p><?=e($currentPatient['patient_no'])?> · Queue <?=e($currentPatient['queue_no'])?> · <?=e($currentPatient['service_name']?:'Dental visit')?></p><p><span class="badge"><?=!empty($currentPatient['intake_completed_at'])?'Intake complete':'Intake pending'?></span> <a href="visit_workflow.php?patient_id=<?=(int)$currentPatient['patient_id']?>">View patient journey</a></p><?php if($currentPatient['medical_alerts']):?><div class="alert error"><strong>Dental safety alert</strong> <?=e($currentPatient['medical_alerts'])?></div><?php endif;?></div>
<div class="now-serving-meta"><span><?=e(ucwords(str_replace('_',' ',$currentPatient['status'])))?></span><small>Waiting <?=e((string)max(0,(int)floor((time()-strtotime($currentPatient['checked_in_at']))/60)))?> min</small></div>
<div class="status-actions"><?php if($isRealDentist):?><?php clinical_day_start_action($currentPatient, $currentPatient['status']==='in_treatment'?'Open Encounter':'Start Encounter'); ?><?php endif;?><a class="btn ghost" href="patients.php?id=<?=(int)$currentPatient['patient_id']?>">Open Patient</a></div>
</section>
<?php else:?><section class="card empty-state"><h2>No patient is currently assigned</h2><p>Patients will appear here after Reception checks them in and assigns them to this doctor.</p><a class="btn ghost" href="appointments.php">View schedule</a></section><?php endif;?>

<div class="grid-2 clinical-day-grid">
<section class="card table-wrap"><div class="card-head"><h2>Assigned queue</h2><a href="queue.php">Open full queue</a></div><table><thead><tr><th>Patient</th><th>Queue</th><th>Service</th><th>Intake</th><th>Status</th><th></th></tr></thead><tbody><?php foreach($queueRows as $row):?><tr><td><strong><?=e(patient_full_name($row))?></strong><br><small><?=e($row['patient_no'])?></small></td><td><?=e($row['queue_no'])?></td><td><?=e($row['service_name']?:'Dental visit')?></td><td><span class="badge"><?=!empty($row['intake_completed_at'])?'Complete':'Pending'?></span></td><td><span class="badge"><?=e(ucwords(str_replace('_',' ',$row['status'])))?></span></td><td><?php if($isRealDentist):?><?php clinical_day_start_action($row, (string)$row['status']==='seated'?'Start':'Open', 'btn link'); ?><?php else:?><span class="muted">View only</span><?php endif;?></td></tr><?php endforeach;if(!$queueRows):?><tr><td colspan="6" class="muted">No assigned queue entries.</td></tr><?php endif;?></tbody></table></section>
<section class="card table-wrap"><div class="card-head"><h2>Draft 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($draft['patient'])?></strong><br><small><?=e($draft['patient_no'])?></small></td><td><?=e(date('M j, g:i A',strtotime($draft['autosaved_at']?:$draft['updated_at']?:$draft['created_at'])))?></td><td><span class="badge"><?=e(ucwords(str_replace('_',' ',$draft['status'])))?></span></td><td><a href="clinical_workspace.php?encounter_id=<?=(int)$draft['id']?>">Continue</a></td></tr><?php endforeach;if(!$drafts):?><tr><td colspan="4" class="muted">No unfinished clinical notes.</td></tr><?php endif;?></tbody></table></section>
</div>
<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($appointment['start_at'])))?></td><td><strong><?=e(patient_full_name($appointment))?></strong><br><small><?=e($appointment['patient_no'])?></small></td><td><?=e($appointment['service_name'])?></td><td><?=e($appointment['chair_name']?:'—')?></td><td><span class="badge"><?=e(ucwords(str_replace('_',' ',$appointment['status'])))?></span></td></tr><?php endforeach;if(!$appointments):?><tr><td colspan="5" class="muted">No appointments scheduled.</td></tr><?php endif;?></tbody></table></section>
</div>
<?php render_footer();
