<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require_login();
require_roles(['super_admin','clinic_admin','receptionist','staff','dental_assistant']);
require DENTAL_ROOT . '/app/layout.php';
require_once DENTAL_ROOT . '/app/transaction_integrity.php';
require_once DENTAL_ROOT . '/app/clinical_billing.php';
require_once DENTAL_ROOT . '/app/workflow_governance.php';
require_once DENTAL_ROOT . '/app/appointment_planning.php';

$pdo = db();
$user = current_user() ?? [];
$userId = (int)($user['id'] ?? 0);
$role = active_role();
$branchId = (int)($user['branch_id'] ?? 0);
if ($branchId < 1) {
    $branchId = (int)($pdo->query('SELECT id FROM `' . table('branches') . '` WHERE is_active=1 ORDER BY id LIMIT 1')->fetchColumn() ?: 0);
}
$error = '';
$schemaReady = workflow_governance_schema_ready();

function inhouse_checkup_can_record(array $queue, int $userId, string $role): bool
{
    return in_array($role, ['dental_assistant','staff','clinic_admin'], true)
        && (int)($queue['inhouse_provider_user_id'] ?? 0) === $userId;
}

function inhouse_checkup_history(PDO $pdo, int $queueId, string $from, string $to, string $note, int $userId): void
{
    $pdo->prepare(
        'INSERT INTO `' . table('queue_status_history') . '` '
        . '(queue_entry_id,previous_status,new_status,notes,changed_by,created_at) VALUES (?,?,?,?,?,NOW())'
    )->execute([$queueId,$from,$to,$note,$userId ?: null]);
}

function inhouse_checkup_appointment_history(PDO $pdo, int $appointmentId, string $from, string $to, string $reason, int $userId): void
{
    if (!schema_table_exists(table('appointment_status_history'))) return;
    $pdo->prepare(
        'INSERT INTO `' . table('appointment_status_history') . '` '
        . '(appointment_id,previous_status,new_status,reason,changed_by,created_at) VALUES (?,?,?,?,?,NOW())'
    )->execute([$appointmentId,$from,$to,$reason,$userId ?: null]);
}

function inhouse_checkup_verified_dentist(PDO $pdo, int $dentistId, int $branchId): array
{
    if ($dentistId < 1) throw new RuntimeException('Select the Dentist who will receive the referral.');
    $stmt = $pdo->prepare(
        'SELECT u.id,u.name FROM `' . table('users') . '` u '
        . 'JOIN `' . table('roles') . '` r ON r.id=u.role_id AND r.code="dentist" '
        . 'WHERE u.id=? AND u.status="active" AND ('
        . 'u.branch_id=? OR u.branch_id IS NULL OR EXISTS('
        . 'SELECT 1 FROM `' . table('dentist_branch_assignments') . '` dba '
        . 'WHERE dba.dentist_user_id=u.id AND dba.branch_id=? AND dba.status="active")) LIMIT 1'
    );
    $stmt->execute([$dentistId,$branchId,$branchId]);
    $dentist = $stmt->fetch();
    if (!$dentist) throw new RuntimeException('The selected Dentist is not active or authorized at this branch.');
    require_dentist_credentials_verified($dentistId);
    return $dentist;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        verify_csrf();
        if (!$schemaReady) throw new RuntimeException('Apply Version 0.5.9.8.16 in System Setup before recording or billing dental-support services.');
        $action = (string)($_POST['action'] ?? '');
        $queueId = (int)($_POST['queue_id'] ?? 0);
        if ($queueId < 1) throw new RuntimeException('Select a valid in-house queue visit.');

        $pdo->beginTransaction();
        $stmt = $pdo->prepare(
            'SELECT q.*,s.requires_chair,COALESCE(s.standard_fee,0) standard_fee,s.fee_status,s.no_charge_reason,s.fee_authorized_by,s.fee_authorized_at,p.first_name,p.last_name,p.patient_no '
            . 'FROM `' . table('queue_entries') . '` q '
            . 'JOIN `' . table('patients') . '` p ON p.id=q.patient_id '
            . 'LEFT JOIN `' . table('service_catalog') . '` s ON s.id=q.service_id '
            . 'WHERE q.id=? AND q.branch_id=? FOR UPDATE'
        );
        $stmt->execute([$queueId,$branchId]);
        $queue = $stmt->fetch();
        if (!$queue || (string)($queue['provider_type'] ?? '') !== 'inhouse') throw new RuntimeException('The selected visit is not an assigned dental-support service at this branch.');
        if (!inhouse_checkup_can_record($queue,$userId,$role)) {
            throw new RuntimeException('Only the assigned dental-support staff member can record or complete this service. Administrators and reception may review it without impersonating the provider.');
        }

        $oldStatus = (string)$queue['status'];
        $patientName = trim((string)$queue['first_name'] . ' ' . (string)$queue['last_name']);
        $appointmentId = (int)($queue['appointment_id'] ?? 0);

        if ($action === 'call') {
            if ($oldStatus !== 'waiting') throw new RuntimeException('Only a waiting patient can be called from the in-house list.');
            $update = $pdo->prepare('UPDATE `' . table('queue_entries') . '` SET status="called",called_at=COALESCE(called_at,NOW()),updated_at=NOW() WHERE id=? AND status="waiting"');
            $update->execute([$queueId]);
            if ($update->rowCount() !== 1) throw new RuntimeException('The queue changed while the patient was being called. Reload and try again.');
            inhouse_checkup_history($pdo,$queueId,'waiting','called','Called by assigned in-house provider',$userId);
            workflow_event((int)$queue['patient_id'],'queue_called','Called for dental-support service',['appointment_id'=>$appointmentId,'queue_entry_id'=>$queueId],(string)$queue['service_name']);
            audit('inhouse_checkup_patient_called','queue_entry',$queueId,['service_name'=>$queue['service_name']]);
            $pdo->commit();
            flash('success',$patientName . ' has been called for ' . (string)$queue['service_name'] . '.');
        } elseif ($action === 'start') {
            $requiresChair = (int)($queue['requires_chair'] ?? 0) === 1;
            $allowed = $requiresChair ? ['seated'] : ['called','seated'];
            if (!in_array($oldStatus,$allowed,true)) {
                throw new RuntimeException($requiresChair
                    ? 'Seat the patient in the assigned shared chair before starting this dental-support service.'
                    : 'Call the patient before starting this dental-support service.');
            }
            $update = $pdo->prepare('UPDATE `' . table('queue_entries') . '` SET status="in_treatment",treatment_started_at=COALESCE(treatment_started_at,NOW()),updated_at=NOW() WHERE id=? AND status=?');
            $update->execute([$queueId,$oldStatus]);
            if ($update->rowCount() !== 1) throw new RuntimeException('The queue changed while the dental-support service was starting. Reload and try again.');
            inhouse_checkup_history($pdo,$queueId,$oldStatus,'in_treatment','Dental-support service started by assigned provider',$userId);
            $pdo->prepare(
                'INSERT INTO `' . table('inhouse_checkup_results') . '` '
                . '(branch_id,patient_id,appointment_id,queue_entry_id,service_id,service_name,provider_user_id,status,recorded_by,started_at,created_at,updated_at) '
                . 'VALUES (?,?,?,?,?,?,?,"in_progress",?,NOW(),NOW(),NOW()) '
                . 'ON DUPLICATE KEY UPDATE provider_user_id=VALUES(provider_user_id),service_id=VALUES(service_id),service_name=VALUES(service_name),status="in_progress",recorded_by=VALUES(recorded_by),updated_at=NOW()'
            )->execute([$branchId,(int)$queue['patient_id'],$appointmentId ?: null,$queueId,(int)($queue['service_id'] ?? 0) ?: null,(string)($queue['service_name'] ?: 'Dental support service'),$userId,$userId]);
            if ($appointmentId > 0) {
                $a = $pdo->prepare('SELECT status,start_at FROM `' . table('appointments') . '` WHERE id=? FOR UPDATE');
                $a->execute([$appointmentId]);
                $appointment = $a->fetch();
                if ($appointment && (string)$appointment['status'] !== 'in_treatment') {
                    integrity_assert_appointment_transition((string)$appointment['status'],'in_treatment',(string)$appointment['start_at']);
                    $u = $pdo->prepare('UPDATE `' . table('appointments') . '` SET status="in_treatment",updated_at=NOW() WHERE id=? AND status=?');
                    $u->execute([$appointmentId,(string)$appointment['status']]);
                    if ($u->rowCount() !== 1) throw new RuntimeException('The linked appointment changed while the dental-support service was starting.');
                    inhouse_checkup_appointment_history($pdo,$appointmentId,(string)$appointment['status'],'in_treatment','Dental-support service started',$userId);
                }
            }
            workflow_event((int)$queue['patient_id'],'inhouse_checkup_started','Dental-support service started',['appointment_id'=>$appointmentId,'queue_entry_id'=>$queueId],(string)$queue['service_name']);
            audit('inhouse_checkup_started','queue_entry',$queueId,['service_name'=>$queue['service_name'],'provider_user_id'=>$userId]);
            $pdo->commit();
            flash('success',$patientName . ' dental-support service is now in progress.');
        } elseif ($action === 'complete') {
            if ($oldStatus !== 'in_treatment') throw new RuntimeException('Start the dental-support service before recording completion.');
            $findings = trim((string)($_POST['findings'] ?? ''));
            $notes = trim((string)($_POST['notes'] ?? ''));
            if ($findings === '' && $notes === '') {
                throw new RuntimeException('Record the completed dental-support work or an operational note.');
            }
            $abnormal = isset($_POST['abnormal_flag']);
            $refer = isset($_POST['refer_to_dentist']);
            $dentist = null;
            $referralReason = trim((string)($_POST['referral_reason'] ?? ''));
            if ($refer) {
                if ($referralReason === '') throw new RuntimeException('Document why this dental-support service requires Dentist assessment.');
                $dentist = inhouse_checkup_verified_dentist($pdo,(int)($_POST['referral_dentist_user_id'] ?? 0),$branchId);
            }
            $feeSource = null;
            if (!$refer) {
                if (!workflow_governance_schema_ready()) throw new RuntimeException('Apply Version 0.5.9.8.16 before completing a dental-support service.');
                $feeSource = governance_inhouse_fee_source($pdo,(int)($queue['service_id'] ?? 0),$branchId);
            }
            $resultStatus = $refer ? 'referred' : 'completed';
            $pdo->prepare(
                'INSERT INTO `' . table('inhouse_checkup_results') . '` '
                . '(branch_id,patient_id,appointment_id,queue_entry_id,service_id,service_name,provider_user_id,status,blood_pressure_systolic,blood_pressure_diastolic,pulse_rate,respiratory_rate,temperature_c,oxygen_saturation,weight_kg,height_cm,bmi,blood_glucose_mg_dl,clearance_status,findings,notes,abnormal_flag,referral_dentist_user_id,referral_reason,recorded_by,started_at,completed_at,created_at,updated_at) '
                . 'VALUES (?,?,?,?,?,?,?,?,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,"not_applicable",?,?,?,?,?,?,COALESCE((SELECT treatment_started_at FROM `' . table('queue_entries') . '` WHERE id=?),NOW()),NOW(),NOW(),NOW()) '
                . 'ON DUPLICATE KEY UPDATE provider_user_id=VALUES(provider_user_id),status=VALUES(status),blood_pressure_systolic=NULL,blood_pressure_diastolic=NULL,pulse_rate=NULL,respiratory_rate=NULL,temperature_c=NULL,oxygen_saturation=NULL,weight_kg=NULL,height_cm=NULL,bmi=NULL,blood_glucose_mg_dl=NULL,clearance_status="not_applicable",findings=VALUES(findings),notes=VALUES(notes),abnormal_flag=VALUES(abnormal_flag),referral_dentist_user_id=VALUES(referral_dentist_user_id),referral_reason=VALUES(referral_reason),recorded_by=VALUES(recorded_by),completed_at=NOW(),updated_at=NOW()'
            )->execute([
                $branchId,(int)$queue['patient_id'],$appointmentId ?: null,$queueId,(int)($queue['service_id'] ?? 0) ?: null,(string)($queue['service_name'] ?: 'Dental support service'),$userId,$resultStatus,
                $findings ?: null,$notes ?: null,$abnormal ? 1 : 0,$dentist['id'] ?? null,$referralReason ?: null,$userId,$queueId,
            ]);
            $resultIdStmt=$pdo->prepare('SELECT id FROM `' . table('inhouse_checkup_results') . '` WHERE queue_entry_id=? LIMIT 1 FOR UPDATE');
            $resultIdStmt->execute([$queueId]);
            $resultId=(int)($resultIdStmt->fetchColumn()?:0);
            if($resultId<1)throw new RuntimeException('The in-house result could not be verified after saving.');

            if ($refer && $dentist) {
                $binding = doctor_chair_binding((int)$dentist['id'],$branchId);
                if (empty($binding['valid'])) throw new RuntimeException((string)($binding['issue'] ?? 'The receiving Dentist needs a valid branch chair assignment.'));
                $update = $pdo->prepare(
                    'UPDATE `' . table('queue_entries') . '` SET provider_type="dentist",dentist_user_id=?,dentist_name=?,chair_id=?,chair_name=?,status="waiting",seated_at=NULL,treatment_started_at=NULL,notes=CONCAT_WS("\n",NULLIF(notes,""),?),updated_at=NOW() WHERE id=? AND status="in_treatment"'
                );
                $handoffNote = 'In-house referral: ' . $referralReason;
                $update->execute([(int)$dentist['id'],(string)$dentist['name'],(int)($binding['chair_id'] ?? 0) ?: null,(string)($binding['chair_name'] ?? '') ?: null,$handoffNote,$queueId]);
                if ($update->rowCount() !== 1) throw new RuntimeException('The queue changed while the Dentist referral was being recorded.');
                inhouse_checkup_history($pdo,$queueId,'in_treatment','waiting',$handoffNote,$userId);
                if ($appointmentId > 0) {
                    $a = $pdo->prepare('SELECT status FROM `' . table('appointments') . '` WHERE id=? FOR UPDATE');
                    $a->execute([$appointmentId]);
                    $oldAppointment = (string)($a->fetchColumn() ?: 'in_treatment');
                    $u = $pdo->prepare('UPDATE `' . table('appointments') . '` SET provider_type="dentist",dentist_user_id=?,dentist_name=?,inhouse_provider_user_id=NULL,inhouse_provider_name=NULL,chair_id=?,chair_name=?,status="checked_in",notes=CONCAT_WS("\n",NULLIF(notes,""),?),updated_at=NOW() WHERE id=? AND status=?');
                    $u->execute([(int)$dentist['id'],(string)$dentist['name'],(int)($binding['chair_id'] ?? 0) ?: null,(string)($binding['chair_name'] ?? '') ?: null,$handoffNote,$appointmentId,$oldAppointment]);
                    if ($u->rowCount() !== 1) throw new RuntimeException('The appointment changed while the Dentist referral was being recorded.');
                    inhouse_checkup_appointment_history($pdo,$appointmentId,$oldAppointment,'checked_in',$handoffNote,$userId);
                }
                workflow_event((int)$queue['patient_id'],'inhouse_checkup_referred','Dental-support service referred to Dentist',['appointment_id'=>$appointmentId,'queue_entry_id'=>$queueId,'dentist_user_id'=>(int)$dentist['id']],$referralReason);
                audit('inhouse_checkup_referred','queue_entry',$queueId,['dentist_user_id'=>(int)$dentist['id'],'reason'=>$referralReason,'abnormal_flag'=>$abnormal]);
                $message = $patientName . ' was returned to the waiting queue for ' . (string)$dentist['name'] . '.';
            } else {
                if (!$feeSource) throw new RuntimeException('The approved in-house fee policy could not be resolved.');
                $invoiceId=governance_sync_inhouse_invoice($pdo,$queue,$resultId,$feeSource,$userId);
                $feeStatus=(string)$feeSource['fee_status'];
                $approvedFee=$feeStatus==='no_charge'?0.0:round((float)$feeSource['approved_fee'],2);
                $update = $pdo->prepare('UPDATE `' . table('queue_entries') . '` SET status="waiting_billing",billing_at=COALESCE(billing_at,NOW()),updated_at=NOW() WHERE id=? AND status="in_treatment"');
                $update->execute([$queueId]);
                if ($update->rowCount() !== 1) throw new RuntimeException('The queue changed while the dental-support service was being completed.');
                inhouse_checkup_history($pdo,$queueId,'in_treatment','waiting_billing',$feeStatus==='no_charge'?'Authorized no-charge in-house service sent for audited checkout':'In-house service completed and sent to cashier',$userId);
                if ($appointmentId > 0) {
                    $a = $pdo->prepare('SELECT status,start_at FROM `' . table('appointments') . '` WHERE id=? FOR UPDATE');
                    $a->execute([$appointmentId]);
                    $appointment = $a->fetch();
                    if ($appointment && (string)$appointment['status'] !== 'awaiting_billing') {
                        integrity_assert_appointment_transition((string)$appointment['status'],'awaiting_billing',(string)$appointment['start_at']);
                        $u = $pdo->prepare('UPDATE `' . table('appointments') . '` SET status="awaiting_billing",updated_at=NOW() WHERE id=? AND status=?');
                        $u->execute([$appointmentId,(string)$appointment['status']]);
                        if ($u->rowCount() !== 1) throw new RuntimeException('The linked appointment changed while the dental-support service was being completed.');
                        inhouse_checkup_appointment_history($pdo,$appointmentId,(string)$appointment['status'],'awaiting_billing',$feeStatus==='no_charge'?'Authorized no-charge service requires audited cashier checkout':'In-house service completed and sent to cashier',$userId);
                    }
                }
                workflow_event((int)$queue['patient_id'],'inhouse_checkup_completed','Dental-support service completed',[
                    'appointment_id'=>$appointmentId,'queue_entry_id'=>$queueId,'invoice_id'=>$invoiceId,
                    'approved_fee'=>$approvedFee,'fee_status'=>$feeStatus,'cashier_required'=>true,
                ],(string)$queue['service_name'] . ($abnormal ? ' · Abnormal finding flagged' : ''));
                audit('inhouse_checkup_completed','queue_entry',$queueId,[
                    'service_name'=>$queue['service_name'],'abnormal_flag'=>$abnormal,'invoice_id'=>$invoiceId,
                    'approved_fee'=>$approvedFee,'fee_status'=>$feeStatus,'cashier_required'=>true,
                ]);
                $message = $feeStatus==='no_charge'
                    ? $patientName . ' dental-support service was completed and sent to Cashier for audited zero-balance checkout.'
                    : $patientName . ' dental-support service was completed and billed at ₱' . number_format($approvedFee,2) . '.';
            }
            $pdo->commit();
            flash('success',$message);
        } else {
            throw new RuntimeException('Unsupported dental-support service action.');
        }
        header('Location: inhouse_checkups.php');
        exit;
    } catch (Throwable $exception) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        $error = $exception->getMessage();
    }
}

$dentists = [];
foreach (active_dentists($branchId ?: null) as $dentist) {
    $reason = null;
    if (dentist_credentials_verified((int)$dentist['id'],$reason)) $dentists[] = $dentist;
}

$rows = [];
if ($schemaReady) {
    $sql = 'SELECT q.*,TRIM(CONCAT(p.last_name,", ",p.first_name," ",COALESCE(NULLIF(p.middle_name,""),""))) patient,p.patient_no,p.birth_date,p.medical_alerts,'
        . 's.requires_chair,COALESCE(s.standard_fee,0) standard_fee,s.fee_status service_fee_status,s.no_charge_reason service_no_charge_reason,s.fee_authorized_by service_fee_authorized_by,s.fee_authorized_at service_fee_authorized_at,u.name inhouse_provider_name,r.id result_id,r.status result_status,r.fee_status result_fee_status,r.approved_fee_snapshot,r.billing_status,r.invoice_id,r.abnormal_flag,r.completed_at,r.findings,r.referral_reason,rd.name referral_dentist_name,'
        . '(SELECT aps.id FROM `' . table('appointment_services') . '` aps WHERE aps.appointment_id=q.appointment_id AND aps.provider_type="inhouse" AND aps.status="planned" AND (q.inhouse_provider_user_id IS NULL OR aps.inhouse_provider_user_id=q.inhouse_provider_user_id) ORDER BY CASE WHEN aps.service_id=q.service_id THEN 0 ELSE 1 END,aps.sequence_no,aps.id LIMIT 1) appointment_service_id '
        . 'FROM `' . table('queue_entries') . '` q '
        . 'JOIN `' . table('patients') . '` p ON p.id=q.patient_id '
        . 'LEFT JOIN `' . table('service_catalog') . '` s ON s.id=q.service_id '
        . 'LEFT JOIN `' . table('users') . '` u ON u.id=q.inhouse_provider_user_id '
        . 'LEFT JOIN `' . table('inhouse_checkup_results') . '` r ON r.queue_entry_id=q.id '
        . 'LEFT JOIN `' . table('users') . '` rd ON rd.id=r.referral_dentist_user_id '
        . 'WHERE q.branch_id=? AND q.provider_type="inhouse" AND (DATE(q.checked_in_at)=CURDATE() OR q.status IN ("waiting","called","seated","in_treatment")) '
        . 'ORDER BY FIELD(q.status,"in_treatment","seated","called","waiting","waiting_billing","cashier_called","completed","cancelled"),q.checked_in_at';
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$branchId]);
    $rows = $stmt->fetchAll();
}

$counts = ['waiting'=>0,'active'=>0,'completed'=>0,'referred'=>0];
foreach ($rows as $row) {
    $status = (string)$row['status'];
    if (in_array($status,['waiting','called'],true)) $counts['waiting']++;
    if (in_array($status,['seated','in_treatment'],true)) $counts['active']++;
    if ((string)($row['result_status'] ?? '') === 'completed') $counts['completed']++;
    if ((string)($row['result_status'] ?? '') === 'referred') $counts['referred']++;
}

render_header('Dental Support Services');
?>
<?php if ($error): ?><div class="flash error" data-auto-dismiss="10000"><?= e($error) ?></div><?php endif; ?>
<?php if (!$schemaReady): ?><div class="alert error"><strong>Database update required.</strong> Apply Version 0.5.9.8.16 from Super → System Setup → Updates before using this workspace.</div><?php endif; ?>
<div class="toolbar">
    <div><strong>Today’s assigned dental-support services</strong><span class="muted">Assigned staff complete approved dental-support services. Health-history review and indicated measurements remain in the separate first-seating workflow before Dentist treatment.</span></div>
    <div class="button-row"><a class="btn ghost" href="queue.php">Open live queue</a><?php if (has_role(['super_admin','clinic_admin'])): ?><a class="btn ghost" href="services.php">Manage service list</a><a class="btn ghost" href="inhouse_team.php">Assign care team</a><?php endif; ?></div>
</div>
<div class="stats-grid compact-stats" data-live-queue-region="inhouse-checkup-stats">
    <article><span>Waiting / called</span><strong><?= (int)$counts['waiting'] ?></strong></article>
    <article><span>In progress</span><strong><?= (int)$counts['active'] ?></strong></article>
    <article><span>Completed today</span><strong><?= (int)$counts['completed'] ?></strong></article>
    <article><span>Referred today</span><strong><?= (int)$counts['referred'] ?></strong></article>
</div>
<div class="module-card-grid inhouse-checkup-grid" data-live-queue-region="inhouse-checkup-flow">
<?php foreach ($rows as $row):
    $canRecord = inhouse_checkup_can_record($row,$userId,$role);
    $rowAge = 0; if (!empty($row['birth_date'])) { try { $rowAge=(new DateTime((string)$row['birth_date']))->diff(new DateTime('today'))->y; } catch (Throwable) { $rowAge=0; } }
    $status = (string)$row['status'];
    $requiresChair = (int)($row['requires_chair'] ?? 0) === 1;
?>
<article id="checkup-<?= (int)$row['id'] ?>" class="module-card inhouse-checkup-card <?= !empty($row['abnormal_flag']) ? 'has-alert' : '' ?>">
    <div class="card-head"><div><span class="badge"><?= e(module_status($status)) ?></span><?php if (!empty($row['abnormal_flag'])): ?><span class="urgency urgent">Abnormal finding</span><?php endif; ?></div><strong><?= e((string)$row['queue_no']) ?></strong></div>
    <h3><?= e((string)$row['patient']) ?></h3>
    <p><?= e((string)$row['patient_no']) ?> · <?= e((string)($row['service_name'] ?: 'Dental support service')) ?></p>
    <dl><dt>Assigned provider</dt><dd><?= e((string)($row['inhouse_provider_name'] ?: 'Unassigned')) ?></dd><dt>Checked in</dt><dd><?= e(date('g:i A',strtotime((string)$row['checked_in_at']))) ?></dd><?php if ($requiresChair): ?><dt>Chair</dt><dd><?= e((string)($row['chair_name'] ?: 'Not assigned')) ?></dd><?php endif; ?></dl>
    <?php if (!empty($row['medical_alerts'])): ?><div class="alert warning"><strong>Dental safety alert:</strong> <?= e((string)$row['medical_alerts']) ?></div><?php endif; ?>
    <?php $serviceFeeStatus=(string)($row['service_fee_status']??'unconfigured');$serviceFeeAmount=(float)($row['standard_fee']??0); ?>
    <p><strong>Fee policy:</strong> <?php if($serviceFeeStatus==='billable'&&$serviceFeeAmount>0):?><span class="badge">Billable · ₱<?=number_format($serviceFeeAmount,2)?></span><?php elseif($serviceFeeStatus==='no_charge'&&trim((string)($row['service_no_charge_reason']??''))!==''):?><span class="badge">Authorized no-charge</span><small><?=e((string)$row['service_no_charge_reason'])?></small><?php else:?><span class="badge danger">Fee setup incomplete</span><?php endif;?></p>
    <?php if (!empty($row['result_status'])): ?><p><strong>Result:</strong> <?= e(module_status((string)$row['result_status'])) ?><?php if ($row['completed_at']): ?> · <?= e(date('g:i A',strtotime((string)$row['completed_at']))) ?><?php endif; ?><?php if(!empty($row['invoice_id'])):?> · Invoice prepared<?php endif;?></p><?php endif; ?>
    <?php if (!empty($row['findings'])): ?><p><?= nl2br(e((string)$row['findings'])) ?></p><?php endif; ?>
    <?php if ((string)($row['result_status'] ?? '') === 'referred'): ?><div class="alert"><strong>Referred to:</strong> <?= e((string)($row['referral_dentist_name'] ?: 'Dentist')) ?><br><?= nl2br(e((string)$row['referral_reason'])) ?></div><?php endif; ?>
    <div class="button-row">
        <a class="btn ghost" href="patients.php?action=view&amp;id=<?= (int)$row['patient_id'] ?>">Patient profile</a>
        <?php if ($canRecord && $status === 'waiting'): ?><form method="post" class="inline-form"><input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>"><input type="hidden" name="action" value="call"><input type="hidden" name="queue_id" value="<?= (int)$row['id'] ?>"><button class="btn primary" type="submit">Call patient</button></form><?php endif; ?>
        <?php if ($canRecord && (($status === 'called' && !$requiresChair) || $status === 'seated')): ?><form method="post" class="inline-form"><input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>"><input type="hidden" name="action" value="start"><input type="hidden" name="queue_id" value="<?= (int)$row['id'] ?>"><button class="btn primary" type="submit">Start service</button></form><?php endif; ?>
    </div>
    <?php if ($canRecord && $requiresChair && $status === 'called'): ?><p class="muted">This dental-support service requires a shared chair. Seat the patient from the <a href="queue.php#queue-entry-<?= (int)$row['id'] ?>">live queue</a> first.</p><?php endif; ?>
    <?php if ($canRecord && $status === 'in_treatment' && !empty($row['appointment_service_id']) && appointment_service_disposition_schema_ready()): $futureInhouseStmt=$pdo->prepare('SELECT id,start_at,service_name,dentist_name,inhouse_provider_name FROM `' . table('appointments') . '` WHERE patient_id=? AND branch_id=? AND id<>? AND start_at>NOW() AND status IN ("requested","pending_confirmation","confirmed") ORDER BY start_at,id LIMIT 30');$futureInhouseStmt->execute([(int)$row['patient_id'],$branchId,(int)($row['appointment_id']??0)]);$futureInhouse=$futureInhouseStmt->fetchAll(); ?>
    <details class="planned-service-disposition"><summary>Could not complete this in-house 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)$row['appointment_service_id']?>"><input type="hidden" name="return" value="inhouse_checkups.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($futureInhouse as $future):?><option value="<?=(int)$future['id']?>"><?=e(date('M j, Y g:i A',strtotime((string)$future['start_at'])).' · '.(string)$future['service_name'])?></option><?php endforeach;?></select></label><label>Required reason<textarea name="reason" required minlength="5" placeholder="Why it could not be completed and the patient discussion"></textarea></label><button class="btn ghost" type="submit">Save disposition</button></form></details>
    <?php endif; ?>
    <?php if ($canRecord && $status === 'in_treatment'): ?>
    <?php if(!($serviceFeeStatus==='billable'&&$serviceFeeAmount>0)&&!($serviceFeeStatus==='no_charge'&&trim((string)($row['service_no_charge_reason']??''))!=='')):?><div class="alert error"><strong>Completion blocked:</strong> this service has no approved billable fee or authorized no-charge policy. An Administrator must correct Dental Services before the result can be completed.</div><?php endif;?>
    <details class="checkup-entry" open><summary>Record dental-support result</summary>
        <form method="post" class="form-grid compact-form">
            <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>"><input type="hidden" name="action" value="complete"><input type="hidden" name="queue_id" value="<?= (int)$row['id'] ?>">
            <div class="notice info wide"><strong>Dental-support scope only.</strong> Record the assigned dental service, equipment/document work, patient assistance, or another approved dental-support action. Health history and indicated measurements are recorded at first seating before Dentist treatment—not here.</div>
            <label class="wide"><span>Completed work / result</span><textarea name="findings" required minlength="3" placeholder="Describe the dental-support service completed for this visit."></textarea></label>
            <label class="wide"><span>Operational note</span><textarea name="notes" placeholder="Materials, image/document reference, patient cooperation, handoff, or another dental-service note."></textarea></label>
            <label class="wide check-label"><input type="checkbox" name="abnormal_flag" value="1"><span>Flag an observation or service issue for Dentist attention.</span></label>
            <label class="wide check-label"><input type="checkbox" name="refer_to_dentist" value="1" data-checkup-referral-toggle><span>Return this patient to a Dentist instead of sending the service directly to Cashier.</span></label>
            <div class="wide form-grid checkup-referral-fields" data-checkup-referral-fields hidden>
                <label>Receiving Dentist<select name="referral_dentist_user_id"><option value="">Select verified Dentist</option><?php foreach ($dentists as $dentist): ?><option value="<?= (int)$dentist['id'] ?>"><?= e((string)$dentist['name']) ?></option><?php endforeach; ?></select></label>
                <label class="wide">Referral reason<textarea name="referral_reason" placeholder="Describe the dental concern or service issue requiring Dentist assessment."></textarea></label>
            </div>
            <div class="button-row wide"><button class="btn primary" type="submit" <?=(!($serviceFeeStatus==='billable'&&$serviceFeeAmount>0)&&!($serviceFeeStatus==='no_charge'&&trim((string)($row['service_no_charge_reason']??''))!==''))?'disabled':''?>>Complete dental-support service</button></div>
        </form>
    </details>
    <?php elseif (!$canRecord && in_array($status,['waiting','called','seated','in_treatment'],true)): ?><p class="muted">This transaction is assigned to <?= e((string)($row['inhouse_provider_name'] ?: 'another provider')) ?>. You may review it but cannot record results under that person’s name.</p><?php endif; ?>
</article>
<?php endforeach; ?>
<?php if (!$rows): ?><div class="card queue-empty">No dental-support services are active or scheduled for today.</div><?php endif; ?>
</div>
<script>
(function(){
  const initialize=function(root=document){
    root.querySelectorAll('[data-checkup-referral-toggle]:not([data-referral-ready])').forEach(function(toggle){
      toggle.dataset.referralReady='1';
      const fields=toggle.closest('form')?.querySelector('[data-checkup-referral-fields]');
      const sync=function(){if(fields)fields.hidden=!toggle.checked;fields?.querySelectorAll('select,textarea').forEach(function(field){field.required=toggle.checked;});};
      toggle.addEventListener('change',sync);sync();
    });
  };
  initialize();
  document.addEventListener('dental:live-queue-updated',function(event){initialize(event.detail?.region||document);});
})();
</script>
<?php render_footer();
