<?php
$u=current_user();$uid=(int)($u['id']??0);$role=(string)($u['role']??'');$today=date('Y-m-d');$admin=is_admin();
if($uid<1){http_response_code(403);exit('Faça login para acessar a fila virtual.');}

$linkedCompanyId=resolve_company_id_for_user($u);$managedCompanyId=0;$professionalMemberships=[];$professionalIds=[];
if(in_array($role,['company','employee'],true)&&$linkedCompanyId>0&&company_is_clinic($linkedCompanyId))$managedCompanyId=$linkedCompanyId;
if($role==='clinic_professional'){$professionalMemberships=clinic_professional_memberships($uid,false);foreach($professionalMemberships as $m)if(($m['status']??'')==='active'&&($m['link_state']??'active')==='active')$professionalIds[]=(int)$m['id'];}

$allClinics=[];
try{$allClinics=db()->query("SELECT c.id,c.name,c.city,c.state,c.status,c.owner_user_id,COALESCE(qs.attendance_mode,'day_queue') attendance_mode,COALESCE(qs.agenda_open,1) agenda_open FROM companies c LEFT JOIN clinic_queue_settings qs ON qs.company_id=c.id WHERE lower(COALESCE(c.type,''))='clinic' OR lower(COALESCE(c.sector,'')) LIKE '%clinic%' OR lower(COALESCE(c.sector,'')) LIKE '%clínic%' ORDER BY c.name")->fetchAll();}catch(Throwable $e){}

$manageCompanyForView=$managedCompanyId;
if($admin){$requested=(int)request('clinic_company',(int)($_SESSION['clinic_queue_company']??0));foreach($allClinics as $c)if((int)$c['id']===$requested){$manageCompanyForView=$requested;break;}if(!$manageCompanyForView&&!empty($allClinics))$manageCompanyForView=(int)$allClinics[0]['id'];if($manageCompanyForView>0)$_SESSION['clinic_queue_company']=$manageCompanyForView;}
elseif(!$manageCompanyForView&&$professionalMemberships){$requested=(int)request('clinic_company',0);foreach($professionalMemberships as $m){if($requested>0&&(int)$m['company_id']===$requested){$manageCompanyForView=$requested;break;}}if(!$manageCompanyForView)$manageCompanyForView=(int)$professionalMemberships[0]['company_id'];}
$canManage=$admin||$managedCompanyId>0||count($professionalIds)>0;
$clinicOwnerCanConfigure=$managedCompanyId>0&&$role==='company'&&clinic_company_owner_user_id($managedCompanyId)===$uid;
$canConfigure=$admin||$clinicOwnerCanConfigure;

$clinics=[];$specialties=[];$professionals=[];
if(!$canManage){try{$q=db()->prepare("SELECT c.id,c.name,c.city,c.state,COALESCE(qs.attendance_mode,'day_queue') attendance_mode,COALESCE(qs.agenda_open,1) agenda_open FROM clinic_patients cp JOIN companies c ON c.id=cp.company_id LEFT JOIN clinic_queue_settings qs ON qs.company_id=c.id WHERE cp.platform_user_id=? AND cp.status='active' AND c.status='active' ORDER BY c.name");$q->execute([$uid]);$clinics=$q->fetchAll();$q=db()->prepare("SELECT s.id,s.company_id,s.name,s.duration_minutes FROM clinic_specialties s JOIN clinic_patients cp ON cp.company_id=s.company_id AND cp.platform_user_id=? AND cp.status='active' WHERE s.status='active' AND COALESCE(s.service_kind,'consultation')<>'exam' ORDER BY s.name");$q->execute([$uid]);$specialties=$q->fetchAll();$q=db()->prepare("SELECT p.id,p.company_id,p.specialty_id,p.name,s.name specialty_name FROM clinic_professionals p JOIN clinic_patients cp ON cp.company_id=p.company_id AND cp.platform_user_id=? AND cp.status='active' LEFT JOIN clinic_specialties s ON s.id=p.specialty_id WHERE p.status='active' AND COALESCE(p.link_state,'active')='active' ORDER BY p.name");$q->execute([$uid]);$professionals=$q->fetchAll();}catch(Throwable $e){}}

$myQueue=[];
if(!$admin){try{$q=db()->prepare("SELECT q.*,c.name clinic_name,s.name service_name,s.duration_minutes,p.name professional_name FROM clinic_virtual_queue q JOIN companies c ON c.id=q.company_id LEFT JOIN clinic_specialties s ON s.id=q.specialty_id LEFT JOIN clinic_professionals p ON p.id=q.professional_id WHERE q.platform_user_id=? ORDER BY CASE WHEN q.queue_date>=date('now') AND q.status NOT IN ('completed','cancelled') THEN 0 ELSE 1 END,q.queue_date DESC,q.queue_number");$q->execute([$uid]);$myQueue=$q->fetchAll();}catch(Throwable $e){}}

$selectedDate=trim((string)request('queue_date',$today));if(!preg_match('/^\d{4}-\d{2}-\d{2}$/',$selectedDate))$selectedDate=$today;
$manageRows=[];$manageCompanyName='';$manageSettings=[];$manageServices=[];$manageProfessionals=[];$dayRules=[];$weeklyRules=[];$clientRows=[];$selectedClientUser=(int)request('queue_client',0);$clientHistory=[];
if($canManage&&$manageCompanyForView>0){
  try{$q=db()->prepare('SELECT name FROM companies WHERE id=?');$q->execute([$manageCompanyForView]);$manageCompanyName=(string)$q->fetchColumn();$manageSettings=clinic_queue_settings($manageCompanyForView);
    $q=db()->prepare("SELECT * FROM clinic_specialties WHERE company_id=? AND status='active' AND COALESCE(service_kind,'consultation')<>'exam' ORDER BY name");$q->execute([$manageCompanyForView]);$manageServices=$q->fetchAll();
    $q=db()->prepare("SELECT p.*,s.name specialty_name FROM clinic_professionals p LEFT JOIN clinic_specialties s ON s.id=p.specialty_id WHERE p.company_id=? AND p.status='active' AND COALESCE(p.link_state,'active')='active' ORDER BY p.name");$q->execute([$manageCompanyForView]);$manageProfessionals=$q->fetchAll();
    $sql="SELECT q.*,cp.name patient_name,cp.phone patient_phone,cp.platform_user_id,s.name service_name,s.duration_minutes,p.name professional_name FROM clinic_virtual_queue q JOIN clinic_patients cp ON cp.id=q.patient_id 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.queue_date=?";$params=[$manageCompanyForView,$selectedDate];
    if($role==='clinic_professional'){$myIds=array_values(array_filter($professionalIds,fn($id)=>clinic_professional_can_access_company($uid,$manageCompanyForView)));if(!$myIds)$sql.=' AND 1=0';else{$marks=implode(',',array_fill(0,count($myIds),'?'));$sql.=" AND q.professional_id IN ($marks)";$params=array_merge($params,$myIds);}}
    $sql.=" ORDER BY CASE q.status WHEN 'in_service' THEN 0 WHEN 'waiting' THEN 1 WHEN 'scheduled' THEN 2 WHEN 'skipped' THEN 3 WHEN 'completed' THEN 4 ELSE 5 END,CASE WHEN q.sort_order>0 THEN q.sort_order ELSE q.queue_number END,q.queue_number";$q=db()->prepare($sql);$q->execute($params);$manageRows=$q->fetchAll();
    if($canConfigure){$q=db()->prepare("SELECT d.*,p.name professional_name,s.name service_name FROM clinic_queue_days d LEFT JOIN clinic_professionals p ON p.id=d.professional_id LEFT JOIN clinic_specialties s ON s.id=d.service_id WHERE d.company_id=? AND d.service_date>=date('now','-30 days') ORDER BY d.service_date,d.id DESC LIMIT 120");$q->execute([$manageCompanyForView]);$dayRules=$q->fetchAll();$q=db()->prepare("SELECT w.*,p.name professional_name,s.name service_name FROM clinic_queue_weekly_rules w LEFT JOIN clinic_professionals p ON p.id=w.professional_id LEFT JOIN clinic_specialties s ON s.id=w.service_id WHERE w.company_id=? ORDER BY w.weekday,w.id DESC");$q->execute([$manageCompanyForView]);$weeklyRules=$q->fetchAll();
      $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 300");$q->execute([$manageCompanyForView]);$clientRows=$q->fetchAll();if($selectedClientUser>0){$hq=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 100");$hq->execute([$manageCompanyForView,$selectedClientUser]);$clientHistory=$hq->fetchAll();}}
  }catch(Throwable $e){}
}
$firstWaiting=null;foreach($manageRows as $mr){if($mr['status']==='waiting'){$firstWaiting=$mr;break;}}
$queueAvailability=[];$queueProfessionalServices=[];
if(!$canManage){
  foreach($professionals as $p){
    $companyId=(int)$p['company_id'];$professionalId=(int)$p['id'];
    $companyServices=array_values(array_filter($specialties,fn($s)=>(int)$s['company_id']===$companyId));
    foreach($companyServices as $service){
      $serviceId=(int)$service['id'];if(!clinic_queue_professional_can_service($companyId,$professionalId,$serviceId))continue;
      $queueProfessionalServices[$professionalId][]=$serviceId;
      for($i=0;$i<180;$i++){
        $date=date('Y-m-d',strtotime('+'.$i.' days'));$cap=clinic_queue_capacity_for_day($companyId,$date,$professionalId,$serviceId);if(!$cap['open'])continue;
        $rule=$cap['rule'];$countSql="SELECT COUNT(*) FROM clinic_virtual_queue WHERE company_id=? AND queue_date=? AND status NOT IN ('cancelled','completed','skipped','no_show')";$countParams=[$companyId,$date];
        if(!empty($rule['professional_id'])){$countSql.=' AND professional_id=?';$countParams[]=(int)$rule['professional_id'];}
        if(!empty($rule['service_id'])){$countSql.=' AND specialty_id=?';$countParams[]=(int)$rule['service_id'];}
        $cq=db()->prepare($countSql);$cq->execute($countParams);$used=(int)$cq->fetchColumn();$remaining=max(0,(int)$cap['max']-$used);
        $mode=(string)($cap['settings']['attendance_mode']??'day_queue');$slots=[];if($mode==='scheduled_time')$slots=clinic_queue_time_slots_for_day($companyId,$professionalId,$serviceId,$date,(int)($service['duration_minutes']??0));
        $queueAvailability[$companyId.'|'.$serviceId.'|'.$professionalId.'|'.$date]=['date'=>$date,'start'=>$cap['start'],'end'=>$cap['end'],'max'=>(int)$cap['max'],'remaining'=>$remaining,'mode'=>$mode,'slots'=>$slots];
      }
    }
  }
}
?>
<section class="page-intro"><div><span class="mini-label"><?= $admin?'👨‍💼 PAINEL DO ADMINISTRADOR':'🎫 MINHA SAÚDE' ?></span><h2>Fila Virtual</h2><p><?= $admin?'Controle completo dos dias marcados, filas, clientes e estabelecimentos.':'A fila virtual faz parte da sua área Minha Saúde. Reserve o atendimento e acompanhe sua posição em tempo real.' ?></p></div><div class="actions"><?php if(!$admin):?><a class="btn btn-secondary" href="dashboard.php?page=clinic_patient">← Minha Saúde</a><?php endif;?><?php if($canManage&&$manageCompanyForView>0):?><a class="btn btn-secondary" href="#clinicQueuePanel">Gerenciar fila</a><?php endif;?></div></section>

<?php if(!$admin&&!$canManage):?>
<section class="panel"><div class="panel-header"><div><h3>🎫 Entrar / reservar atendimento</h3><p>Escolha a clínica, o serviço e o profissional. O sistema mostra somente os dias realmente liberados para a Fila Virtual.</p></div></div>
<?php if(!$clinics):?><div class="notice"><strong>Nenhum estabelecimento disponível.</strong><br>A Fila Virtual mostra somente clínicas em que você está cadastrado como paciente.</div><?php elseif(!$specialties):?><div class="notice"><strong>Nenhum serviço disponível.</strong><br>A clínica ainda não possui serviço de consulta/procedimento ativo para esta fila.</div><?php elseif(!$professionals):?><div class="notice"><strong>Nenhum profissional disponível.</strong><br>A clínica ainda não possui profissional ativo para atendimento.</div><?php endif;?>
<form method="post" action="actions.php" data-clinic-queue-form><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_create"><input type="hidden" name="return_page" value="clinic_queue"><div class="form-grid">
<div class="form-group"><label>🏥 Estabelecimento</label><select name="company_id" required data-queue-company><option value="">Escolha o estabelecimento</option><?php foreach($clinics as $c):?><option value="<?=(int)$c['id']?>" data-mode="<?=e($c['attendance_mode'])?>" data-open="<?=(int)$c['agenda_open']?>"><?=e($c['name'].' • '.trim(($c['city']??'').'/'.($c['state']??''),'/'))?> — <?=e(clinic_queue_mode_label((string)$c['attendance_mode']))?><?=(int)$c['agenda_open']?'':' — agenda geral fechada'?></option><?php endforeach;?></select><small data-queue-mode-help></small></div>
<div class="form-group"><label>🩺 Serviço</label><select name="specialty_id" required data-queue-specialty><option value="">Escolha o serviço</option><?php foreach($specialties as $s):?><option value="<?=(int)$s['id']?>" data-company="<?=(int)$s['company_id']?>"><?=e($s['name'])?></option><?php endforeach;?></select></div>
<div class="form-group"><label>👨‍⚕️ Profissional</label><select name="professional_id" required data-queue-professional><option value="">Escolha o profissional</option><?php foreach($professionals as $p):$services=array_values(array_unique(array_map('intval',$queueProfessionalServices[(int)$p['id']]??[])));?><option value="<?=(int)$p['id']?>" data-company="<?=(int)$p['company_id']?>" data-services=",<?=e(implode(',',$services))?>,"><?=e($p['name'].($p['specialty_name']?' • '.$p['specialty_name']:''))?></option><?php endforeach;?></select><small>São exibidos os profissionais liberados para o serviço na agenda/fila da clínica.</small></div>
<div class="form-group"><label>📅 Dia do atendimento</label><select name="queue_date" required data-queue-date><option value="">Escolha clínica, serviço e profissional</option></select><small>Somente datas com expediente e vaga aparecem aqui.</small></div>
<div class="form-group" data-queue-time-wrap hidden><label>🕐 Horário</label><select name="queue_time" data-queue-time><option value="">Escolha o horário</option></select><small>Mostramos somente horários livres para a data escolhida.</small></div>
</div><div class="notice" data-queue-availability-info>Escolha estabelecimento, serviço e profissional para carregar os dias disponíveis.</div><div class="notice" data-queue-presential hidden><strong>🔢 Senha presencial</strong><br>Este estabelecimento entrega a senha no próprio local; não é possível reservar online.</div><button class="btn btn-primary" data-queue-submit disabled>🎫 Reservar atendimento</button></form></section>

<section class="panel"><div class="panel-header"><div><h3>📅 Meus atendimentos</h3><p>Senha, posição, previsão, horário e status em um só lugar.</p></div></div><div class="cards-list">
<?php if(!$myQueue):?><div class="empty-state"><strong>Nenhum atendimento na fila</strong><span>Escolha um estabelecimento acima para reservar.</span></div><?php endif;?>
<?php foreach($myQueue as $q):$stats=clinic_queue_stats($q);$isToday=$q['queue_date']===$today;$active=!in_array($q['status'],['completed','cancelled'],true);?>
<article class="item-card" data-queue-watch="<?=(int)$q['id']?>"><div class="item-body"><h3>🎫 Senha Nº <?=str_pad((string)(int)$q['queue_number'],2,'0',STR_PAD_LEFT)?> • <?=e($q['clinic_name'])?></h3><p>📅 <?=e(date('d/m/Y',strtotime($q['queue_date'])))?><?=!empty($q['queue_time'])?' • 🕐 '.e(substr($q['queue_time'],0,5)):''?> • 🩺 <?=e($q['service_name']?:'Atendimento')?> • <?=e($q['professional_name']?:'Profissional')?></p><p><strong><?=e(clinic_queue_mode_label((string)($q['attendance_mode']??'day_queue')))?></strong></p>
<div class="item-meta"><span>👥 <strong data-queue-ahead><?=(int)$stats['people_ahead']?></strong> pessoa(s) à sua frente</span><span>⏱️ Estimativa: <strong data-queue-estimate><?=(int)$stats['estimate_minutes']?> min</strong><?=!empty($stats['estimated_time'])?' • ~'.e($stats['estimated_time']):''?></span><span>Status: <strong data-queue-status><?=e(clinic_queue_status_label((string)$q['status']))?></strong></span></div>
<?php if($q['status']==='scheduled'&&$isToday&&!in_array(($q['attendance_mode']??''),['scheduled_time'],true)):?><form method="post" action="actions.php" class="actions" style="margin-top:10px"><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_join_today"><input type="hidden" name="return_page" value="clinic_queue"><input type="hidden" name="id" value="<?=(int)$q['id']?>"><button class="btn btn-accent">🟢 Entrar na fila hoje</button></form><?php elseif($q['status']==='scheduled'&&($q['attendance_mode']??'')==='scheduled_time'):?><div class="notice" style="margin-top:10px">📅 Atendimento confirmado para <?=e(substr((string)$q['queue_time'],0,5))?>. Aguarde ser chamado.</div><?php elseif($q['status']==='scheduled'):?><div class="notice" style="margin-top:10px">✅ Dia reservado. No dia <?=e(date('d/m/Y',strtotime($q['queue_date'])))?>, volte aqui para entrar na fila.</div><?php elseif($q['status']==='waiting'&&$stats['people_ahead']===0):?><div class="notice" style="margin-top:10px"><strong>🔔 Você é o próximo!</strong></div><?php elseif($q['status']==='in_service'):?><div class="notice" style="margin-top:10px"><strong>🟢 É sua vez! Dirija-se ao atendimento.</strong></div><?php elseif($q['status']==='skipped'):?><div class="notice" style="margin-top:10px"><strong>⚠️ Sua senha foi pulada.</strong> Procure a recepção para orientação.</div><?php endif;?>
<?php if($active&&in_array($q['status'],['scheduled','waiting'],true)):?><form method="post" action="actions.php" style="margin-top:10px"><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_cancel"><input type="hidden" name="return_page" value="clinic_queue"><input type="hidden" name="id" value="<?=(int)$q['id']?>"><button class="btn btn-danger btn-sm" data-confirm="Cancelar este atendimento?">Cancelar</button></form><?php endif;?></div></article>
<?php endforeach;?></div></section>
<?php endif;?>

<?php if($admin):?>
<section class="panel"><div class="panel-header"><div><h3>🏥 Estabelecimentos</h3><p>Selecione uma clínica para administrar sua fila, agenda e clientes.</p></div><a class="btn btn-primary" href="dashboard.php?page=companies">+ Cadastrar / gerenciar empresas</a></div>
<form method="get" action="dashboard.php" class="filter-bar"><input type="hidden" name="page" value="clinic_queue"><div class="form-group"><label>Clínica / estabelecimento</label><select name="clinic_company" onchange="this.form.submit()"><?php foreach($allClinics as $c):?><option value="<?=(int)$c['id']?>"<?=selected($manageCompanyForView,(int)$c['id'])?>><?=e($c['name'])?> — <?=e(status_label($c['status']))?></option><?php endforeach;?></select></div></form>
<div class="table-wrap"><table><thead><tr><th>Estabelecimento</th><th>Tipo</th><th>Agenda</th><th>Status</th><th>Ação</th></tr></thead><tbody><?php foreach($allClinics as $c):?><tr><td><strong><?=e($c['name'])?></strong><small style="display:block"><?=e(trim(($c['city']??'').'/'.($c['state']??''),'/'))?></small></td><td><?=e(clinic_queue_mode_label((string)$c['attendance_mode']))?></td><td><?=(int)$c['agenda_open']?'Aberta':'Fechada'?></td><td><?=status_badge($c['status'])?></td><td><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_company_status"><input type="hidden" name="return_page" value="clinic_queue"><input type="hidden" name="company_id" value="<?=(int)$c['id']?>"><input type="hidden" name="status" value="<?=$c['status']==='active'?'inactive':'active'?>"><button class="btn btn-secondary btn-sm"><?=$c['status']==='active'?'Desativar':'Ativar'?></button></form></td></tr><?php endforeach;?></tbody></table></div></section>
<?php endif;?>

<?php if($admin&&$manageCompanyForView>0):?>
<section class="panel"><div class="panel-header"><div><h3>🩺 Serviços e profissionais — <?=e($manageCompanyName)?></h3><p>Cadastro rápido para deixar o estabelecimento pronto para operar a fila.</p></div></div><div class="form-grid">
<div><h4>+ Criar serviço</h4><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_admin_add_service"><input type="hidden" name="return_page" value="clinic_queue"><input type="hidden" name="company_id" value="<?=$manageCompanyForView?>"><div class="form-group"><label>Nome do serviço</label><input class="input" name="name" placeholder="Ex.: Consulta médica" required></div><div class="form-group"><label>Duração média</label><input class="input" type="number" name="duration_minutes" min="5" max="480" value="30"></div><button class="btn btn-primary">Cadastrar serviço</button></form></div>
<div><h4>+ Criar profissional</h4><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_admin_add_professional"><input type="hidden" name="return_page" value="clinic_queue"><input type="hidden" name="company_id" value="<?=$manageCompanyForView?>"><div class="form-group"><label>Nome</label><input class="input" name="name" required></div><div class="form-group"><label>Serviço / especialidade</label><select name="specialty_id"><option value="0">Sem vínculo específico</option><?php foreach($manageServices as $s):?><option value="<?=(int)$s['id']?>"><?=e($s['name'])?></option><?php endforeach;?></select></div><button class="btn btn-primary">Cadastrar profissional</button></form></div>
</div><div class="notice" style="margin-top:14px">Para dados completos da empresa, endereço, documentos e demais configurações, use <a href="dashboard.php?page=companies"><strong>Empresas</strong></a>.</div></section>
<?php endif;?>

<?php if($canConfigure&&$manageCompanyForView>0):?>
<section class="panel" id="queueSettings"><div class="panel-header"><div><h3>⭐ Configuração do tipo de atendimento — <?=e($manageCompanyName)?></h3><p>Escolha como o estabelecimento trabalhará e configure capacidade, previsão e mensagens.</p></div></div>
<form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_save_settings"><input type="hidden" name="return_page" value="clinic_queue"><input type="hidden" name="company_id" value="<?=$manageCompanyForView?>"><div class="form-grid">
<div class="form-group full"><label>Tipo de atendimento</label><select name="attendance_mode"><?php foreach(['virtual_queue','scheduled_time','day_queue','arrival_order','presential_ticket'] as $m):?><option value="<?=$m?>"<?=selected($manageSettings['attendance_mode']??'day_queue',$m)?>><?=e(clinic_queue_mode_label($m))?></option><?php endforeach;?></select></div>
<div class="form-group"><label>Início</label><input class="input" type="time" name="start_time" value="<?=e($manageSettings['start_time']??'08:00')?>" required></div><div class="form-group"><label>Término</label><input class="input" type="time" name="end_time" value="<?=e($manageSettings['end_time']??'18:00')?>" required></div>
<div class="form-group"><label>Máximo de clientes por dia</label><input class="input" type="number" name="max_clients_per_day" min="1" max="1000" value="<?=(int)($manageSettings['max_clients_per_day']??50)?>"></div><div class="form-group"><label>Tempo médio por atendimento (min)</label><input class="input" type="number" name="average_minutes" min="5" max="240" value="<?=(int)($manageSettings['average_minutes']??15)?>"></div>
<div class="form-group full"><label class="check-line"><input type="checkbox" name="agenda_open" value="1"<?=checked((int)($manageSettings['agenda_open']??1),1)?>> Agenda aberta para novas entradas</label><label class="check-line"><input type="checkbox" name="allow_reorder" value="1"<?=checked((int)($manageSettings['allow_reorder']??0),1)?>> Permitir alteração manual da ordem pela clínica</label></div>
<div class="form-group"><label>“Atendimento próximo”</label><input class="input" name="message_near" value="<?=e($manageSettings['message_near']??'Seu atendimento está próximo.')?>"></div><div class="form-group"><label>“Você é o próximo”</label><input class="input" name="message_next" value="<?=e($manageSettings['message_next']??'Você é o próximo!')?>"></div><div class="form-group"><label>“É sua vez”</label><input class="input" name="message_turn" value="<?=e($manageSettings['message_turn']??'É sua vez! Dirija-se ao atendimento.')?>"></div><div class="form-group"><label>Cancelamento</label><input class="input" name="message_cancelled" value="<?=e($manageSettings['message_cancelled']??'Seu atendimento foi cancelado.')?>"></div><div class="form-group full"><label>Horário alterado / transferência</label><input class="input" name="message_changed" value="<?=e($manageSettings['message_changed']??'Seu horário foi alterado.')?>"></div>
</div><button class="btn btn-primary">Salvar configuração</button></form></section>

<section class="panel"><div class="panel-header"><div><h3>📅 Gerenciar dias de atendimento</h3><p>Crie dias disponíveis, feche datas, registre feriados e defina limites específicos.</p></div></div>
<form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_save_day"><input type="hidden" name="return_page" value="clinic_queue"><input type="hidden" name="company_id" value="<?=$manageCompanyForView?>"><div class="form-grid"><div class="form-group"><label>Data</label><input class="input" type="date" name="service_date" min="<?=e($today)?>" required></div><div class="form-group"><label>Situação</label><select name="day_status"><option value="open">Aberto</option><option value="closed">Fechado</option><option value="holiday">Feriado / sem atendimento</option></select></div><div class="form-group"><label>Profissional (opcional)</label><select name="professional_id"><option value="0">Todos</option><?php foreach($manageProfessionals as $p):?><option value="<?=(int)$p['id']?>"><?=e($p['name'])?></option><?php endforeach;?></select></div><div class="form-group"><label>Serviço (opcional)</label><select name="service_id"><option value="0">Todos</option><?php foreach($manageServices as $s):?><option value="<?=(int)$s['id']?>"><?=e($s['name'])?></option><?php endforeach;?></select></div><div class="form-group"><label>Início (opcional)</label><input class="input" type="time" name="start_time"></div><div class="form-group"><label>Término (opcional)</label><input class="input" type="time" name="end_time"></div><div class="form-group"><label>Máximo neste dia</label><input class="input" type="number" name="max_clients" min="1" placeholder="Usar padrão"></div><div class="form-group"><label>Observação</label><input class="input" name="note" placeholder="Ex.: feriado municipal"></div></div><button class="btn btn-primary">Salvar dia</button></form>
<div class="table-wrap" style="margin-top:18px"><table><thead><tr><th>Data</th><th>Escopo</th><th>Horário</th><th>Limite</th><th>Status</th><th></th></tr></thead><tbody><?php if(!$dayRules):?><tr><td colspan="6">Nenhuma regra específica cadastrada.</td></tr><?php endif;?><?php foreach($dayRules as $d):?><tr><td><?=e(date('d/m/Y',strtotime($d['service_date'])))?></td><td><?=e(($d['professional_name']?:'Todos profissionais').' • '.($d['service_name']?:'Todos serviços'))?></td><td><?=e(($d['start_time']?:$manageSettings['start_time']).'–'.($d['end_time']?:$manageSettings['end_time']))?></td><td><?=e($d['max_clients']?:$manageSettings['max_clients_per_day'])?></td><td><?=status_badge($d['status'])?></td><td><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_delete_day"><input type="hidden" name="return_page" value="clinic_queue"><input type="hidden" name="id" value="<?=(int)$d['id']?>"><button class="btn btn-danger btn-sm" data-confirm="Remover esta regra de atendimento?">Remover</button></form></td></tr><?php endforeach;?></tbody></table></div></section>
<?php if($weeklyRules):$weekdayNames=['Domingo','Segunda-feira','Terça-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sábado'];?><section class="panel"><div class="panel-header"><div><h3>Repetições semanais</h3><p>As regras abaixo se repetem automaticamente até a data final ou até serem removidas.</p></div></div><div class="table-wrap"><table><thead><tr><th>Dia</th><th>Período</th><th>Horário</th><th>Vagas</th><th>Ação</th></tr></thead><tbody><?php foreach($weeklyRules as $w):?><tr><td><strong><?=e($weekdayNames[(int)$w['weekday']]??'')?></strong><small style="display:block"><?=e(($w['professional_name']?:'Todos profissionais').' • '.($w['service_name']?:'Todos serviços'))?></small></td><td><?=e(date('d/m/Y',strtotime($w['effective_from'])))?> até <?=!empty($w['effective_until'])?e(date('d/m/Y',strtotime($w['effective_until']))):'sem data final'?></td><td><?=e(($w['start_time']?:$manageSettings['start_time']).'–'.($w['end_time']?:$manageSettings['end_time']))?></td><td><?=(int)($w['max_clients']?:$manageSettings['max_clients_per_day'])?></td><td><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_delete_weekly"><input type="hidden" name="return_page" value="clinic_queue"><input type="hidden" name="id" value="<?=(int)$w['id']?>"><button class="btn btn-danger btn-sm" data-confirm="Remover esta repetição semanal?">Remover</button></form></td></tr><?php endforeach;?></tbody></table></div></section><?php endif;?>
<?php endif;?>

<?php if($canManage&&$manageCompanyForView>0):?>
<?php if($canConfigure):?><section class="panel"><div class="panel-header"><div><h3>Clientes e histórico da fila</h3><p>Cadastro, bloqueios, atendimentos e faltas ficam em uma página própria.</p></div><a class="btn btn-primary" href="dashboard.php?page=clinic_queue_clients&clinic_company=<?=$manageCompanyForView?>">Gerenciar clientes</a></div></section><?php endif;?>
<section class="panel" id="clinicQueuePanel"><div class="panel-header"><div><h3>🎫 Gerenciar a fila — <?=e($manageCompanyName)?></h3><p>Visualize aguardando, em atendimento, finalizados e controle a ordem.</p></div><?php if($firstWaiting):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_call"><input type="hidden" name="return_page" value="clinic_queue"><input type="hidden" name="id" value="<?=(int)$firstWaiting['id']?>"><button class="btn btn-primary">▶️ Chamar próximo</button></form><?php endif;?></div>
<form method="get" action="dashboard.php" class="filter-bar"><input type="hidden" name="page" value="clinic_queue"><?php if($admin||($role==='clinic_professional'&&count($professionalMemberships)>1)):?><div class="form-group"><label>Estabelecimento</label><select name="clinic_company" onchange="this.form.submit()"><?php $list=$admin?$allClinics:$professionalMemberships;foreach($list as $m):$cid=(int)($m['company_id']??$m['id']);$cn=(string)($m['company_name']??$m['name']);?><option value="<?=$cid?>"<?=selected($manageCompanyForView,$cid)?>><?=e($cn)?></option><?php endforeach;?></select></div><?php endif;?><div class="form-group"><label>Data</label><input class="input" type="date" name="queue_date" value="<?=e($selectedDate)?>" onchange="this.form.submit()"></div></form>
<?php if($canConfigure&&($manageSettings['attendance_mode']??'')==='presential_ticket'):?><div class="notice" style="margin-bottom:14px"><strong>🔢 Emitir senha presencial</strong><form method="post" action="actions.php" style="margin-top:10px"><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_create_presential"><input type="hidden" name="return_page" value="clinic_queue"><input type="hidden" name="company_id" value="<?=$manageCompanyForView?>"><div class="form-grid"><div class="form-group"><label>Paciente</label><select name="patient_id" required><option value="">Escolha</option><?php foreach($clientRows as $cp):?><option value="<?=(int)$cp['id']?>"><?=e($cp['name'])?></option><?php endforeach;?></select></div><div class="form-group"><label>Serviço</label><select name="specialty_id" required><?php foreach($manageServices as $s):?><option value="<?=(int)$s['id']?>"><?=e($s['name'])?></option><?php endforeach;?></select></div><div class="form-group"><label>Profissional</label><select name="professional_id" required><?php foreach($manageProfessionals as $p):?><option value="<?=(int)$p['id']?>"><?=e($p['name'])?></option><?php endforeach;?></select></div><div class="form-group" style="align-self:end"><button class="btn btn-primary">Emitir senha agora</button></div></div></form></div><?php endif;?>
<div class="table-wrap"><table><thead><tr><th>Senha</th><th>Paciente</th><th>Serviço / Profissional</th><th>Previsão</th><th>Status</th><th>Ações</th></tr></thead><tbody><?php if(!$manageRows):?><tr><td colspan="6"><div class="empty-state"><strong>Nenhum paciente nesta fila</strong></div></td></tr><?php endif;?><?php foreach($manageRows as $row):$st=clinic_queue_stats($row);?><tr><td><strong>Nº <?=str_pad((string)(int)$row['queue_number'],2,'0',STR_PAD_LEFT)?></strong><?=!empty($row['queue_time'])?'<small style="display:block">'.e(substr($row['queue_time'],0,5)).'</small>':''?></td><td><?=e($row['patient_name'])?><small style="display:block"><?=e(format_phone($row['patient_phone']))?></small></td><td><?=e($row['service_name']?:'Atendimento')?><small style="display:block"><?=e($row['professional_name']?:'—')?></small></td><td><?=(int)$st['people_ahead']?> à frente<br><small><?=(int)$st['estimate_minutes']?> min<?=!empty($st['estimated_time'])?' • ~'.e($st['estimated_time']):''?></small></td><td><?=status_badge($row['status'])?></td><td><div class="actions">
<?php if(in_array($row['status'],['waiting','scheduled'],true)):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_call"><input type="hidden" name="return_page" value="clinic_queue"><input type="hidden" name="id" value="<?=(int)$row['id']?>"><button class="btn btn-primary btn-sm">▶️ Chamar</button></form><?php endif;?>
<?php if(in_array($row['status'],['in_service','skipped'],true)):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_recall"><input type="hidden" name="return_page" value="clinic_queue"><input type="hidden" name="id" value="<?=(int)$row['id']?>"><button class="btn btn-secondary btn-sm">🔔 Rechamar</button></form><?php if($row['status']==='in_service'):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_finish"><input type="hidden" name="return_page" value="clinic_queue"><input type="hidden" name="id" value="<?=(int)$row['id']?>"><button class="btn btn-accent btn-sm">✅ Finalizar</button></form><?php endif;?><?php endif;?>
<?php if(in_array($row['status'],['waiting','scheduled'],true)):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_skip"><input type="hidden" name="return_page" value="clinic_queue"><input type="hidden" name="id" value="<?=(int)$row['id']?>"><button class="btn btn-secondary btn-sm">⏭ Pular</button></form><?php endif;?><?php if(in_array($row['status'],['waiting','scheduled'],true)):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_no_show"><input type="hidden" name="return_page" value="clinic_queue"><input type="hidden" name="id" value="<?=(int)$row['id']?>"><button class="btn btn-danger btn-sm" data-confirm="Registrar falta deste cliente?">Falta</button></form><?php endif;?>
<?php if($row['status']==='waiting'&&($admin||!empty($manageSettings['allow_reorder']))):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_reorder"><input type="hidden" name="return_page" value="clinic_queue"><input type="hidden" name="id" value="<?=(int)$row['id']?>"><input type="hidden" name="direction" value="up"><button class="btn btn-secondary btn-sm">↑</button></form><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_reorder"><input type="hidden" name="return_page" value="clinic_queue"><input type="hidden" name="id" value="<?=(int)$row['id']?>"><input type="hidden" name="direction" value="down"><button class="btn btn-secondary btn-sm">↓</button></form><?php endif;?>
<?php if(in_array($row['status'],['waiting','scheduled','skipped'],true)):?><details><summary class="btn btn-secondary btn-sm">Alterar data/horário</summary><form method="post" action="actions.php" style="min-width:230px;margin-top:8px"><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_reschedule_manage"><input type="hidden" name="return_page" value="clinic_queue"><input type="hidden" name="id" value="<?=(int)$row['id']?>"><div class="form-group"><label>Nova data</label><input class="input" type="date" name="new_date" min="<?=e($today)?>" value="<?=e($row['queue_date'])?>" required></div><?php if(($row['attendance_mode']??'')==='scheduled_time'):?><div class="form-group"><label>Novo horário</label><input class="input" type="time" name="new_time" value="<?=e(substr((string)$row['queue_time'],0,5))?>" required></div><?php endif;?><button class="btn btn-primary btn-sm">Salvar alteração</button></form></details><?php endif;?><?php if(in_array($row['status'],['waiting','scheduled','skipped'],true)&&count($manageProfessionals)>1):?><details><summary class="btn btn-secondary btn-sm">Transferir</summary><form method="post" action="actions.php" style="min-width:220px;margin-top:8px"><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_transfer"><input type="hidden" name="return_page" value="clinic_queue"><input type="hidden" name="id" value="<?=(int)$row['id']?>"><select name="target_professional_id" required><?php foreach($manageProfessionals as $p):if((int)$p['id']===(int)$row['professional_id'])continue;?><option value="<?=(int)$p['id']?>"><?=e($p['name'])?></option><?php endforeach;?></select><button class="btn btn-primary btn-sm" style="margin-top:6px">Confirmar</button></form></details><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_queue_cancel_manage"><input type="hidden" name="return_page" value="clinic_queue"><input type="hidden" name="id" value="<?=(int)$row['id']?>"><button class="btn btn-danger btn-sm" data-confirm="Cancelar esta senha?">Cancelar</button></form><?php endif;?>
</div></td></tr><?php endforeach;?></tbody></table></div></section>
<?php endif;?>

<?php if($canConfigure&&$manageCompanyForView>0):?>
<section class="panel"><div class="panel-header"><div><h3>👥 Gerenciar clientes da fila</h3><p>Cadastro, histórico de atendimentos, faltas/cancelamentos e bloqueio de novas senhas.</p></div></div><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ção</th></tr></thead><tbody><?php if(!$clientRows):?><tr><td colspan="6">Nenhum paciente cadastrado.</td></tr><?php endif;?><?php foreach($clientRows 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&clinic_company=<?=$manageCompanyForView?>&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"><input type="hidden" name="company_id" value="<?=$manageCompanyForView?>"><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)" style="margin-bottom:6px"><?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 else:?><span class="muted">Sem conta vinculada</span><?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section>
<?php if($selectedClientUser>0):?><section class="panel" id="clientHistory"><div class="panel-header"><div><h3>🗂️ Histórico do cliente</h3><p>Atendimentos, cancelamentos e senhas puladas neste estabelecimento.</p></div><a class="btn btn-secondary" href="dashboard.php?page=clinic_queue&clinic_company=<?=$manageCompanyForView?>">Fechar histórico</a></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(!$clientHistory):?><tr><td colspan="5">Sem histórico.</td></tr><?php endif;?><?php foreach($clientHistory 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;?>
<?php endif;?>

<script>
(function(){
 const availability=<?=json_encode($queueAvailability,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)?>;
 const company=document.querySelector('[data-queue-company]'),service=document.querySelector('[data-queue-specialty]'),professional=document.querySelector('[data-queue-professional]');
 if(!company)return;
 const dateSelect=document.querySelector('[data-queue-date]'),timeWrap=document.querySelector('[data-queue-time-wrap]'),timeSelect=document.querySelector('[data-queue-time]'),presential=document.querySelector('[data-queue-presential]'),submit=document.querySelector('[data-queue-submit]'),help=document.querySelector('[data-queue-mode-help]'),availabilityInfo=document.querySelector('[data-queue-availability-info]');
 const modeValue=()=>company.options[company.selectedIndex]?.dataset.mode||'day_queue';
 const currentAvailability=()=>availability[[company.value,service?.value||'',professional?.value||'',dateSelect?.value||''].join('|')]||null;
 function syncServices(){const cid=company.value;Array.from(service?.options||[]).forEach((o,i)=>{if(i===0)return;o.hidden=o.dataset.company!==cid;if(o.hidden&&o.selected)service.value='';});}
 function syncProfessionals(){const cid=company.value,sid=service?.value||'';Array.from(professional?.options||[]).forEach((o,i)=>{if(i===0)return;const services=o.dataset.services||',';const ok=o.dataset.company===cid&&(!sid||services.includes(','+sid+','));o.hidden=!ok;if(o.hidden&&o.selected)professional.value='';});}
 function rebuildDates(){if(!dateSelect)return;const old=dateSelect.value;dateSelect.innerHTML='<option value="">Escolha uma data disponível</option>';if(!company.value||!service?.value||!professional?.value){showAvailability();return;}const prefix=[company.value,service.value,professional.value].join('|')+'|';const rows=Object.entries(availability).filter(([k])=>k.startsWith(prefix)).map(([,a])=>a).sort((a,b)=>a.date.localeCompare(b.date));for(const a of rows){const d=new Date(a.date+'T12:00:00');const label=d.toLocaleDateString('pt-BR')+' • '+a.start+'–'+a.end+' • '+a.remaining+' vaga(s)';const o=document.createElement('option');o.value=a.date;o.textContent=label;o.disabled=Number(a.remaining)<=0;dateSelect.appendChild(o);}if(old&&rows.some(a=>a.date===old&&Number(a.remaining)>0))dateSelect.value=old;else{const first=Array.from(dateSelect.options).find((o,i)=>i>0&&!o.disabled);if(first)dateSelect.value=first.value;}rebuildTimes();showAvailability();}
 function rebuildTimes(){if(!timeSelect)return;const a=currentAvailability(),m=modeValue(),old=timeSelect.value;timeSelect.innerHTML='<option value="">Escolha o horário</option>';if(m==='scheduled_time'&&a){for(const t of (a.slots||[])){const o=document.createElement('option');o.value=t;o.textContent=t;timeSelect.appendChild(o);}if(old&&(a.slots||[]).includes(old))timeSelect.value=old;else if((a.slots||[]).length===1)timeSelect.value=a.slots[0];}syncMode();}
 function showAvailability(){if(!availabilityInfo)return;if(!company.value){availabilityInfo.textContent='Escolha o estabelecimento para começar.';return;}if(!service?.value){availabilityInfo.textContent='Escolha o serviço.';return;}if(!professional?.value){availabilityInfo.textContent='Escolha um profissional disponível para este serviço.';return;}const a=currentAvailability();if(!a){availabilityInfo.innerHTML='<strong>Nenhuma data disponível.</strong><br>A clínica precisa liberar um dia/expediente para este profissional e serviço.';return;}let text=`<strong>Expediente ${a.start}–${a.end}</strong> • ${a.remaining} de ${a.max} vaga(s) disponível(is)`;if(modeValue()==='scheduled_time')text+=(a.slots||[]).length?` • ${(a.slots||[]).length} horário(s) livre(s)`:' • sem horário livre';availabilityInfo.innerHTML=text;}
 function syncMode(){const m=modeValue(),a=currentAvailability(),isTime=m==='scheduled_time',isPresential=m==='presential_ticket';if(timeWrap)timeWrap.hidden=!isTime;if(timeSelect)timeSelect.required=isTime;if(presential)presential.hidden=!isPresential;const labels={virtual_queue:'Fila Virtual: entre e acompanhe sua posição.',scheduled_time:'Hora Marcada: escolha um dos horários livres.',day_queue:'Dia Marcado + Fila: reserve o dia e entre na fila no próprio dia.',arrival_order:'Ordem de chegada: sua posição é definida quando você confirmar chegada no dia.',presential_ticket:'Senha presencial: retire a senha no estabelecimento.'};if(help)help.textContent=labels[m]||'';const validDate=!!a&&Number(a.remaining)>0;const validTime=!isTime||!!timeSelect?.value;if(submit)submit.disabled=isPresential||!validDate||!validTime;}
 function companyChanged(){syncServices();syncProfessionals();rebuildDates();syncMode();}
 company.addEventListener('change',companyChanged);service?.addEventListener('change',()=>{syncProfessionals();rebuildDates();});professional?.addEventListener('change',rebuildDates);dateSelect?.addEventListener('change',()=>{rebuildTimes();showAvailability();});timeSelect?.addEventListener('change',syncMode);companyChanged();
})();
document.addEventListener('DOMContentLoaded',()=>{const dayForm=document.querySelector('form input[value="clinic_queue_save_day"]')?.closest('form');if(dayForm){const box=document.createElement('div');box.className='form-grid';box.style.marginTop='12px';box.innerHTML='<div class="form-group"><label>Repetição</label><select name="repeat_weekly"><option value="0">Somente esta data</option><option value="1">Repetir toda semana</option></select><small>Ex.: 10 vagas toda segunda-feira.</small></div><div class="form-group"><label>Repetir até (opcional)</label><input class="input" type="date" name="effective_until"><small>Vazio mantém até a clínica fechar ou remover a regra.</small></div>';dayForm.querySelector('button[type="submit"],button:not([type])')?.before(box);}document.querySelectorAll('section.panel').forEach(section=>{const h=section.querySelector('h3');if(h&&h.textContent.includes('Gerenciar clientes da fila'))section.remove();});});
</script>
