<?php
$u=current_user();$uid=(int)$u['id'];$role=(string)$u['role'];$companyId=0;
if(is_admin())$companyId=(int)request('clinic_company',(int)($_SESSION['clinic_queue_company']??0));
else{$linked=resolve_company_id_for_user($u);if(in_array($role,['company','employee'],true)&&$linked>0&&company_is_clinic($linked))$companyId=$linked;}
if($companyId<1||(!is_admin()&&clinic_company_owner_user_id($companyId)!==$uid)){http_response_code(403);exit('Sem permissão para gerenciar clientes desta fila.');}
$q=db()->prepare('SELECT name FROM companies WHERE id=?');$q->execute([$companyId]);$companyName=(string)$q->fetchColumn();if($companyName==='')exit('Clínica não encontrada.');
$q=db()->prepare("SELECT cp.id,cp.platform_user_id,cp.name,cp.phone,cp.email,COALESCE(b.blocked,0) queue_blocked,b.reason,(SELECT COUNT(*) FROM clinic_virtual_queue v WHERE v.company_id=cp.company_id AND v.patient_id=cp.id AND v.status='completed') completed_count,(SELECT COUNT(*) FROM clinic_virtual_queue v WHERE v.company_id=cp.company_id AND v.patient_id=cp.id AND v.status IN ('cancelled','skipped','no_show')) missed_count FROM clinic_patients cp LEFT JOIN clinic_queue_client_blocks b ON b.company_id=cp.company_id AND b.platform_user_id=cp.platform_user_id WHERE cp.company_id=? ORDER BY cp.name LIMIT 500");$q->execute([$companyId]);$clients=$q->fetchAll();
$selected=(int)request('queue_client',0);$history=[];if($selected>0){$q=db()->prepare("SELECT q.*,s.name service_name,p.name professional_name FROM clinic_virtual_queue q LEFT JOIN clinic_specialties s ON s.id=q.specialty_id LEFT JOIN clinic_professionals p ON p.id=q.professional_id WHERE q.company_id=? AND q.platform_user_id=? ORDER BY q.queue_date DESC,q.id DESC LIMIT 150");$q->execute([$companyId,$selected]);$history=$q->fetchAll();}
?>
<section class="page-intro"><div><span class="mini-label">FILA VIRTUAL</span><h2>Clientes e histórico</h2><p><?=e($companyName)?> • vínculos, bloqueios, atendimentos, faltas e cancelamentos.</p></div><a class="btn btn-secondary" href="dashboard.php?page=clinic_queue&clinic_company=<?=$companyId?>">← Voltar para a fila</a></section>
<section class="panel"><div class="table-wrap"><table><thead><tr><th>Cliente</th><th>Contato</th><th>Atendimentos</th><th>Faltas/cancelamentos</th><th>Situação</th><th>Ações</th></tr></thead><tbody><?php if(!$clients):?><tr><td colspan="6">Nenhum paciente vinculado.</td></tr><?php endif;?><?php foreach($clients as $c):?><tr><td><strong><?=e($c['name'])?></strong></td><td><?=e(format_phone($c['phone']))?><small style="display:block"><?=e($c['email'])?></small></td><td><?=(int)$c['completed_count']?></td><td><?=(int)$c['missed_count']?></td><td><?=!empty($c['queue_blocked'])?'<span class="status status-blocked">Bloqueado</span>':'<span class="status status-active">Liberado</span>'?><?=!empty($c['reason'])?'<small style="display:block">'.e($c['reason']).'</small>':''?></td><td><?php if(!empty($c['platform_user_id'])):?><div class="actions"><a class="btn btn-secondary btn-sm" href="dashboard.php?page=clinic_queue_clients&clinic_company=<?=$companyId?>&queue_client=<?=(int)$c['platform_user_id']?>#clientHistory">Histórico</a><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_client_block"><input type="hidden" name="return_page" value="clinic_queue_clients"><input type="hidden" name="company_id" value="<?=$companyId?>"><input type="hidden" name="platform_user_id" value="<?=(int)$c['platform_user_id']?>"><input type="hidden" name="blocked" value="<?=!empty($c['queue_blocked'])?'0':'1'?>"><?php if(empty($c['queue_blocked'])):?><input class="input" name="reason" placeholder="Motivo (opcional)"><?php endif;?><button class="btn <?=!empty($c['queue_blocked'])?'btn-accent':'btn-danger'?> btn-sm"><?=!empty($c['queue_blocked'])?'Liberar':'Bloquear'?></button></form></div><?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section>
<?php if($selected>0):?><section class="panel" id="clientHistory"><div class="panel-header"><div><h3>Histórico do cliente</h3><p>Atendimentos, cancelamentos e senhas puladas.</p></div></div><div class="table-wrap"><table><thead><tr><th>Data</th><th>Senha</th><th>Serviço</th><th>Profissional</th><th>Status</th></tr></thead><tbody><?php if(!$history):?><tr><td colspan="5">Sem histórico.</td></tr><?php endif;?><?php foreach($history as $h):?><tr><td><?=e(date('d/m/Y',strtotime($h['queue_date'])))?><?=!empty($h['queue_time'])?' '.e(substr($h['queue_time'],0,5)):''?></td><td>Nº <?=str_pad((string)(int)$h['queue_number'],2,'0',STR_PAD_LEFT)?></td><td><?=e($h['service_name']?:'Atendimento')?></td><td><?=e($h['professional_name']?:'—')?></td><td><?=status_badge($h['status'])?></td></tr><?php endforeach;?></tbody></table></div></section><?php endif;?>
