<?php
$u=current_user();$uid=(int)($u['id']??0);$role=(string)($u['role']??'');$linkedCompanyId=resolve_company_id_for_user($u);$isOwner=$role==='company'&&$linkedCompanyId>0&&company_is_clinic($linkedCompanyId)&&clinic_company_owner_user_id($linkedCompanyId)===$uid;$readOnly=false;$clinics=[];
if($isOwner){$q=db()->prepare('SELECT * FROM companies WHERE id=?');$q->execute([$linkedCompanyId]);$row=$q->fetch();if($row)$clinics=[$row];$companyId=$linkedCompanyId;}
elseif(is_super_admin()){$readOnly=true;$clinics=db()->query("SELECT DISTINCT c.* FROM companies c JOIN user_reports r ON r.reported_company_id=c.id WHERE r.status NOT IN ('finalized','dismissed') ORDER BY c.name")->fetchAll();$companyId=(int)request('clinic_company',($clinics[0]['id']??0));$allowed=false;foreach($clinics as $c)if((int)$c['id']===$companyId)$allowed=true;if(!$allowed)$companyId=0;}
else{http_response_code(403);exit('A área interna de Clínicas é exclusiva do proprietário da conta.');}
$company=null;foreach($clinics as $c){if((int)$c['id']===$companyId){$company=$c;break;}}
if(!$company){?><section class="panel"><div class="empty-state"><strong>Nenhuma clínica liberada</strong><?=is_super_admin()?'O Administrador Sênior só pode visualizar uma clínica enquanto existir denúncia clínica em análise.':'Clínica não encontrada.'?></div></section><?php return;}
$settings=clinic_settings($companyId);
$q=db()->prepare('SELECT * FROM clinic_specialties WHERE company_id=? ORDER BY status DESC,name');$q->execute([$companyId]);$specialties=$q->fetchAll();
$q=db()->prepare("SELECT p.*,s.name specialty_name,u.public_id platform_public_id,COALESCE((SELECT ROUND(AVG(r.rating),1) FROM reviews r WHERE r.target_type='clinic_professional' AND r.target_id=p.id AND r.status='published'),0) professional_rating,COALESCE((SELECT COUNT(*) FROM reviews r WHERE r.target_type='clinic_professional' AND r.target_id=p.id AND r.status='published'),0) professional_rating_count FROM clinic_professionals p LEFT JOIN clinic_specialties s ON s.id=p.specialty_id LEFT JOIN users u ON u.id=p.user_id WHERE p.company_id=? ORDER BY CASE COALESCE(p.link_state,'active') WHEN 'pending_professional' THEN 0 WHEN 'pending_admin' THEN 1 WHEN 'waiting_payment' THEN 2 ELSE 3 END,p.name");$q->execute([$companyId]);$professionals=$q->fetchAll();$activeProfessionals=array_values(array_filter($professionals,fn($p)=>($p['status']??'')==='active'&&($p['link_state']??'active')==='active'));
$q=db()->prepare('SELECT p.*,u.public_id platform_public_id FROM clinic_patients p LEFT JOIN users u ON u.id=p.platform_user_id WHERE p.company_id=? ORDER BY p.status DESC,p.name');$q->execute([$companyId]);$patients=$q->fetchAll();
$q=db()->prepare("SELECT a.*,pa.name patient_name,pa.platform_user_id,pr.name professional_name,s.name specialty_name FROM clinic_appointments a JOIN clinic_patients pa ON pa.id=a.patient_id LEFT JOIN clinic_professionals pr ON pr.id=a.professional_id LEFT JOIN clinic_specialties s ON s.id=a.specialty_id WHERE a.company_id=? ORDER BY CASE WHEN a.appointment_date>=date('now') AND a.status NOT IN ('cancelled','completed') THEN 0 ELSE 1 END,a.appointment_date,a.appointment_time LIMIT 300");$q->execute([$companyId]);$appointments=$q->fetchAll();
$q=db()->prepare("SELECT a.*,p.name professional_name FROM clinic_professional_availability a JOIN clinic_professionals p ON p.id=a.professional_id WHERE p.company_id=? ORDER BY p.name,a.weekday");$q->execute([$companyId]);$availability=$q->fetchAll();
$q=db()->prepare("SELECT e.*,pa.name patient_name,pr.name professional_name,s.name exam_name,s.price FROM clinic_exam_requests e JOIN clinic_patients pa ON pa.id=e.patient_id LEFT JOIN clinic_professionals pr ON pr.id=e.professional_id LEFT JOIN clinic_specialties s ON s.id=e.specialty_id WHERE e.company_id=? ORDER BY CASE e.status WHEN 'requested' THEN 0 WHEN 'scheduled' THEN 1 ELSE 2 END,e.id DESC");$q->execute([$companyId]);$exams=$q->fetchAll();
$consultSpecialties=array_values(array_filter($specialties,fn($s)=>($s['service_kind']??'consultation')!=='exam'));$todayRows=array_values(array_filter($appointments,fn($a)=>$a['appointment_date']===date('Y-m-d')&&!in_array($a['status'],['cancelled','completed'],true)));$todayAppointments=count($todayRows);$upcoming=0;foreach($appointments as $a){if($a['appointment_date']>=date('Y-m-d')&&!in_array($a['status'],['cancelled','completed'],true))$upcoming++;}
?>
<section class="page-intro clinic-page-intro"><div><span class="mini-label">🏥 ACESSAR CLÍNICA</span><h2><?=e($company['name'])?></h2><p><?=$readOnly?'Acesso temporário do Administrador Sênior liberado exclusivamente por denúncia em análise.':'Painel exclusivo do proprietário da clínica.'?></p></div><div class="actions"><a class="btn btn-secondary" href="dashboard.php?page=home">← Início</a><?php if(!$readOnly):?><a class="btn btn-primary" href="dashboard.php?page=clinic_queue">🎫 Fila Virtual</a><a class="btn btn-secondary" href="dashboard.php?page=companies">Dados da empresa</a><?php endif;?></div></section>
<?php if($readOnly):?><section class="panel"><div class="notice"><strong>🔐 Modo de verificação por denúncia</strong><br>Este acesso é somente para consulta. Ao finalizar/arquivar a denúncia, o acesso aos dados internos desta clínica é encerrado.</div><?php if(count($clinics)>1):?><form method="get" action="dashboard.php" class="module-toolbar"><input type="hidden" name="page" value="clinic"><div class="form-group"><label>Clínica com denúncia aberta</label><select name="clinic_company"><?php foreach($clinics as $c):?><option value="<?=(int)$c['id']?>"<?=selected($companyId,$c['id'])?>><?=e($c['name'])?></option><?php endforeach;?></select></div><button class="btn btn-secondary">Acessar</button></form><?php endif;?></section><?php endif;?>

<section class="stats-grid clinic-stats-grid"><a class="stat-card stat-card-link" href="#clinicPatients"><div class="stat-top"><span>Pacientes</span><span class="stat-icon">🧑‍⚕️</span></div><strong><?=count($patients)?></strong><small>cadastrados</small></a><a class="stat-card stat-card-link" href="#clinicProfessionals"><div class="stat-top"><span>Profissionais</span><span class="stat-icon">🩺</span></div><strong><?=count($activeProfessionals)?></strong><small>vínculos ativos</small></a><a class="stat-card stat-card-link" href="#clinicAgenda"><div class="stat-top"><span>Hoje</span><span class="stat-icon">📅</span></div><strong><?=$todayAppointments?></strong><small>consultas</small></a><a class="stat-card stat-card-link" href="#clinicAgenda"><div class="stat-top"><span>Próximas</span><span class="stat-icon">⏰</span></div><strong><?=$upcoming?></strong><small>agendamentos</small></a></section>

<?php if(!$readOnly):?><section class="panel" id="clinicSettings"><div class="panel-header"><div><h2>⚙️ Configurações</h2><p>Funcionamento, agendamento e pagamento da clínica.</p></div></div><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_clinic_settings"><input type="hidden" name="company_id" value="<?=$companyId?>"><div class="form-grid"><div class="form-group full"><label>Horários de funcionamento</label><input class="input" name="opening_hours" value="<?=e($settings['opening_hours'])?>"></div><div class="form-group"><label>Agendamento pelo paciente</label><select name="allow_self_booking"><option value="1"<?=selected($settings['allow_self_booking'],1)?>>Liberado</option><option value="0"<?=selected($settings['allow_self_booking'],0)?>>Somente clínica</option></select></div><div class="form-group"><label>Reagendamento pelo paciente</label><select name="allow_reschedule"><option value="1"<?=selected($settings['allow_reschedule'],1)?>>Liberado</option><option value="0"<?=selected($settings['allow_reschedule'],0)?>>Bloqueado</option></select></div><div class="form-group"><label>Pagamento online</label><select name="online_payment_enabled"><option value="1"<?=selected($settings['online_payment_enabled'],1)?>>Ativado</option><option value="0"<?=selected($settings['online_payment_enabled'],0)?>>Desativado</option></select></div><div class="form-group"><label>Forma de pagamento</label><select name="payment_method"><option value="pix"<?=selected($settings['payment_method'],'pix')?>>Pix</option><option value="link"<?=selected($settings['payment_method'],'link')?>>Link</option><option value="presential"<?=selected($settings['payment_method'],'presential')?>>Presencial</option></select></div><div class="form-group"><label>Pix</label><input class="input" name="pix_key" value="<?=e($settings['pix_key'])?>"></div><div class="form-group"><label>Link de pagamento</label><input class="input" type="url" name="payment_link" value="<?=e($settings['payment_link'])?>"></div><div class="form-group"><label>Limite de consultas por profissional/dia</label><input class="input" type="number" min="0" name="daily_consultation_limit" value="<?=e($settings['daily_consultation_limit']??0)?>"><small>0 = sem limite. O profissional pode ter um limite próprio.</small></div><div class="form-group"><label>Limite de exames por dia</label><input class="input" type="number" min="0" name="daily_exam_limit" value="<?=e($settings['daily_exam_limit']??0)?>"><small>Ao preencher as vagas, novos agendamentos são bloqueados.</small></div><div class="form-group"><label>Raio para confirmar presença</label><input class="input" type="number" min="50" max="5000" name="checkin_radius_meters" value="<?=e($settings['checkin_radius_meters']??250)?>"><small>Distância máxima do paciente até a clínica, em metros.</small></div></div><input type="hidden" name="professional_limit" value="<?=e($settings['professional_limit'])?>"><input type="hidden" name="patient_limit" value="<?=e($settings['patient_limit'])?>"><input type="hidden" name="attendant_limit" value="<?=e($settings['attendant_limit'])?>"><button class="btn btn-primary">Salvar configurações</button></form></section><?php endif;?>

<section class="panel"><div class="panel-header"><div><h2>🧪 Catálogo de consultas, procedimentos e exames</h2><p>Preço, descrição, preparo e dias/horários em que o serviço é realizado.</p></div></div>
<?php if(!$readOnly):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_clinic_specialty"><input type="hidden" name="company_id" value="<?=$companyId?>"><div class="form-grid"><div class="form-group"><label>Nome</label><input class="input" name="name" required></div><div class="form-group"><label>Tipo</label><select name="service_kind"><option value="consultation">Consulta</option><option value="exam">Exame</option><option value="procedure">Procedimento</option></select></div><div class="form-group"><label>Valor</label><input class="input" name="price" inputmode="decimal" placeholder="0,00"></div><div class="form-group"><label>Duração</label><select name="duration_minutes"><option value="30">30 min</option><option value="45">45 min</option><option value="60">60 min</option><option value="90">90 min</option><option value="120">120 min</option></select></div><div class="form-group"><label>Status</label><select name="status"><option value="active">Ativo</option><option value="inactive">Inativo</option></select></div><div class="form-group"><label>Paciente pode solicitar/agendar</label><select name="allow_patient_booking"><option value="1">Sim</option><option value="0">Não</option></select></div><div class="form-group full"><label>Descrição</label><textarea name="description"></textarea></div><div class="form-group full"><label>Preparo / o que o paciente precisa fazer</label><textarea name="preparation_instructions"></textarea></div><div class="form-group" data-exam-schedule-field><label>Forma de agendamento do exame</label><select name="exam_booking_mode"><option value="time">Data + horário</option><option value="arrival">Ordem de chegada (somente o dia)</option></select></div><div class="form-group full" data-exam-schedule-field><label>Dias de realização do exame</label><div class="chips"><?php foreach([1=>'Seg',2=>'Ter',3=>'Qua',4=>'Qui',5=>'Sex',6=>'Sáb',0=>'Dom'] as $wd=>$wl):?><label class="checkbox-row"><input type="checkbox" name="exam_weekdays[]" value="<?=$wd?>"> <?=$wl?></label><?php endforeach;?></div><small>Somente estes dias ficarão disponíveis para o paciente.</small></div><div class="form-group" data-exam-schedule-field><label>Início dos exames</label><input class="input" type="time" name="exam_start_time" value="07:00"></div><div class="form-group" data-exam-schedule-field><label>Fim dos exames</label><input class="input" type="time" name="exam_end_time" value="11:00"></div><div class="form-group" data-legacy-schedule-field><label>Dias de realização</label><input class="input" name="available_days" placeholder="Ex.: Seg, Qua e Sex"></div><div class="form-group" data-legacy-schedule-field><label>Horários de realização</label><input class="input" name="available_hours" placeholder="Ex.: 07:00–11:00"></div></div><button class="btn btn-primary">+ Cadastrar no catálogo</button></form><?php endif;?>
<div class="cards-list" style="margin-top:14px"><?php if(!$specialties):?><div class="empty-state"><strong>Catálogo vazio</strong></div><?php endif;?><?php foreach($specialties as $s):?><article class="item-card"><div class="item-body"><h3><?=e($s['name'])?> • <?=money($s['price'])?></h3><p><?=e(ucfirst($s['service_kind']??'consultation'))?> • <?=(int)$s['duration_minutes']?> min • <?=status_badge($s['status'])?></p><p><?=e($s['description'])?></p><?php if(!empty($s['preparation_instructions'])):?><div class="notice"><strong>Preparo:</strong> <?=nl2br(e($s['preparation_instructions']))?></div><?php endif;?><?php $examSch=clinic_exam_schedule($s);?><div class="item-meta"><span><strong>Dias:</strong> <?=e(($s['service_kind']??'')==='exam'&&$examSch['weekdays']?implode(', ',array_map('clinic_weekday_label',$examSch['weekdays'])):($s['available_days']?:'Não informado'))?></span><span><strong>Horários:</strong> <?=e(($s['service_kind']??'')==='exam'&&$examSch['start']&&$examSch['end']?$examSch['start'].'–'.$examSch['end']:($s['available_hours']?:'Não informado'))?></span><?php if(($s['service_kind']??'')==='exam'):?><span><strong>Agendamento:</strong> <?=$examSch['mode']==='arrival'?'Ordem de chegada':'Data + horário'?></span><?php endif;?><span><strong>Solicitação pelo paciente:</strong> <?=!empty($s['allow_patient_booking'])?'Sim':'Não'?></span></div><?php $servicePros=array_values(array_filter($activeProfessionals,fn($pr)=>empty($pr['specialty_id'])||(int)$pr['specialty_id']===(int)$s['id']));if($servicePros):?><div class="notice" style="margin-top:10px"><strong>🩺 Profissionais desta área</strong><div class="clinic-professional-list"><?php foreach($servicePros as $pr):?><div class="clinic-professional-row"><div><strong><?=e($pr['name'])?></strong><small><?=e($pr['professional_type']?:'Profissional')?><?=!empty($pr['registry'])?' • '.e($pr['registry']):''?></small></div><span class="badge success">Disponível para agendamento</span></div><?php endforeach;?></div></div><?php endif;?><?php if(!$readOnly&&($s['service_kind']??'')==='exam'):?><details style="margin-top:10px"><summary class="btn btn-secondary btn-sm">⚙️ Configurar agenda do exame</summary><form method="post" action="actions.php" style="margin-top:10px"><?=csrf_field()?><input type="hidden" name="action" value="save_clinic_exam_schedule"><input type="hidden" name="id" value="<?=(int)$s['id']?>"><div class="form-grid"><div class="form-group"><label>Forma de atendimento</label><select name="exam_booking_mode"><option value="time"<?=selected($examSch['mode'],'time')?>>Data + horário</option><option value="arrival"<?=selected($examSch['mode'],'arrival')?>>Ordem de chegada (somente o dia)</option></select></div><div class="form-group"><label>Início</label><input class="input" type="time" name="exam_start_time" value="<?=e($examSch['start'])?>" required></div><div class="form-group"><label>Fim</label><input class="input" type="time" name="exam_end_time" value="<?=e($examSch['end'])?>" required></div><div class="form-group full"><label>Dias disponíveis</label><div class="chips"><?php foreach([1=>'Seg',2=>'Ter',3=>'Qua',4=>'Qui',5=>'Sex',6=>'Sáb',0=>'Dom'] as $wd=>$wl):?><label class="checkbox-row"><input type="checkbox" name="exam_weekdays[]" value="<?=$wd?>"<?=in_array($wd,$examSch['weekdays'],true)?' checked':''?>> <?=$wl?></label><?php endforeach;?></div></div></div><button class="btn btn-primary btn-sm">Salvar agenda do exame</button></form></details><?php endif;?><?php if(!$readOnly):?><form method="post" action="actions.php" style="margin-top:8px"><?=csrf_field()?><input type="hidden" name="action" value="delete_clinic_specialty"><input type="hidden" name="id" value="<?=(int)$s['id']?>"><button class="btn btn-danger btn-sm" data-confirm="Apagar item do catálogo?">Apagar</button></form><?php endif;?></div></article><?php endforeach;?></div></section>
<script>document.addEventListener('DOMContentLoaded',()=>{document.querySelectorAll('form input[value="save_clinic_specialty"]').forEach(input=>{const form=input.closest('form');const group=form?.querySelector('[name="duration_minutes"]')?.closest('.form-group');group?.remove();const type=form?.querySelector('[name="service_kind"]');const sync=()=>{const exam=type?.value==='exam';form?.querySelectorAll('[data-exam-schedule-field]').forEach(el=>el.hidden=!exam);form?.querySelectorAll('[data-legacy-schedule-field]').forEach(el=>el.hidden=exam);};type?.addEventListener('change',sync);sync();});document.querySelectorAll('article.item-card .item-body>p:first-of-type').forEach(p=>{p.innerHTML=p.innerHTML.replace(/\s*•\s*\d+\s*min\s*•/i,' •');});});</script>

<section class="panel" id="clinicProfessionals"><div class="panel-header"><div><h2>🩺 Profissionais</h2><p>O vínculo por ID só fica ativo depois do aceite do profissional e das regras de múltiplas instituições.</p></div></div><?php if(!$readOnly):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_clinic_professional"><input type="hidden" name="company_id" value="<?=$companyId?>"><div class="form-grid"><div class="form-group full"><label>ID do usuário na plataforma</label><input class="input" name="platform_user_id" placeholder="LXU-..."><small>Ao vincular uma conta existente, o profissional recebe uma notificação para aceitar.</small></div><div class="form-group"><label>Nome</label><input class="input" name="name"></div><div class="form-group"><label>E-mail</label><input class="input" type="email" name="email"></div><div class="form-group"><label>Documento</label><input class="input" name="document"></div><div class="form-group"><label>Senha inicial</label><input class="input" name="password" value="123456"></div><div class="form-group"><label>Profissão</label><input class="input" name="professional_type" placeholder="Médico, Dentista..."></div><div class="form-group"><label>Registro</label><input class="input" name="registry" placeholder="CRM, CRO..."></div><div class="form-group"><label>Especialidade</label><select name="specialty_id"><option value="">Sem vínculo</option><?php foreach($specialties as $s):?><option value="<?=(int)$s['id']?>"><?=e($s['name'])?></option><?php endforeach;?></select></div><div class="form-group"><label>WhatsApp</label><input class="input" name="phone" data-phone-mask></div><div class="form-group"><label>Exibir WhatsApp</label><select name="share_whatsapp"><option value="0">Não</option><option value="1">Sim</option></select></div><div class="form-group"><label>Consultas/dia deste profissional</label><input class="input" type="number" min="0" name="daily_consultation_limit" value="0"><small>0 usa o limite geral da clínica.</small></div><div class="form-group"><label>Exames/dia deste profissional</label><input class="input" type="number" min="0" name="daily_exam_limit" value="0"><small>0 usa o limite geral da clínica.</small></div></div><button class="btn btn-primary">Solicitar / cadastrar profissional</button></form><?php endif;?>
<div class="table-wrap clinic-table-wrap" style="margin-top:14px"><table><thead><tr><th>Profissional</th><th>ID</th><th>Especialidade</th><th>Avaliação</th><th>Vínculo</th><th>Contato</th><th>Vagas/dia</th><th>Ação</th></tr></thead><tbody><?php if(!$professionals):?><tr><td colspan="8"><div class="empty-state"><strong>Nenhum profissional</strong></div></td></tr><?php endif;?><?php foreach($professionals as $p):?><tr><td><strong><?=e($p['name'])?></strong><small style="display:block"><?=e(trim(($p['professional_type']?:'Profissional').' '.($p['registry']?:'')))?></small></td><td><?=e($p['platform_public_id']?:'—')?></td><td><?=e($p['specialty_name']?:'—')?></td><td><?php if((int)($p['professional_rating_count']??0)>0):?><?=stars_html((float)$p['professional_rating'])?> <strong><?=number_format((float)$p['professional_rating'],1,',','.')?></strong><small style="display:block"><?=(int)$p['professional_rating_count']?> avaliação(ões)</small><?php else:?><span class="muted">Sem avaliações</span><?php endif;?></td><td><strong><?=e(clinic_link_state_label((string)($p['link_state']??'active')))?></strong><?php if(!empty($p['billing_required'])):?><small style="display:block">Mensalidade exigida</small><?php endif;?></td><td><?=e(format_phone($p['phone']))?></td><td><?php if(!$readOnly):?><form method="post" action="actions.php" class="actions" style="align-items:end"><?=csrf_field()?><input type="hidden" name="action" value="save_clinic_professional_limits"><input type="hidden" name="id" value="<?=(int)$p['id']?>"><label style="font-size:.76rem">Consultas<input class="input" style="width:76px" type="number" min="0" name="daily_consultation_limit" value="<?=e($p['daily_consultation_limit']??0)?>"></label><label style="font-size:.76rem">Exames<input class="input" style="width:76px" type="number" min="0" name="daily_exam_limit" value="<?=e($p['daily_exam_limit']??0)?>"></label><button class="btn btn-secondary btn-sm">Salvar</button></form><?php else:?><?=e(($p['daily_consultation_limit']??0).' / '.($p['daily_exam_limit']??0))?><?php endif;?></td><td><?php if(!$readOnly):?><div class="actions"><details><summary class="btn btn-secondary btn-sm">✏️ Editar</summary><form method="post" action="actions.php" style="margin-top:10px;min-width:280px"><?=csrf_field()?><input type="hidden" name="action" value="save_clinic_professional"><input type="hidden" name="company_id" value="<?=$companyId?>"><input type="hidden" name="id" value="<?=(int)$p['id']?>"><div class="form-group"><label>Nome</label><input class="input" name="name" value="<?=e($p['name'])?>" required></div><div class="form-group"><label>Profissão</label><input class="input" name="professional_type" value="<?=e($p['professional_type'])?>"></div><div class="form-group"><label>Registro</label><input class="input" name="registry" value="<?=e($p['registry'])?>"></div><div class="form-group"><label>Especialidade / função na clínica</label><select name="specialty_id"><option value="">Sem vínculo</option><?php foreach($specialties as $s):?><option value="<?=(int)$s['id']?>"<?=selected($p['specialty_id']??0,$s['id'])?>><?=e($s['name'])?></option><?php endforeach;?></select></div><div class="form-group"><label>E-mail</label><input class="input" type="email" name="email" value="<?=e($p['email'])?>"></div><div class="form-group"><label>WhatsApp</label><input class="input" name="phone" value="<?=e($p['phone'])?>" data-phone-mask></div><div class="form-group"><label>Exibir WhatsApp</label><select name="share_whatsapp"><option value="0"<?=selected((int)$p['share_whatsapp'],0)?>>Não</option><option value="1"<?=selected((int)$p['share_whatsapp'],1)?>>Sim</option></select></div><button class="btn btn-primary btn-sm">Salvar profissional</button></form></details><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="delete_clinic_professional"><input type="hidden" name="id" value="<?=(int)$p['id']?>"><button class="btn btn-danger btn-sm" data-confirm="Remover vínculo?">Remover</button></form></div><?php else:?>—<?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section>

<?php if(!$readOnly&&$activeProfessionals):?><section class="panel"><div class="panel-header"><div><h2>🕒 Disponibilidade dos profissionais</h2></div></div><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_clinic_professional_availability"><div class="form-grid"><div class="form-group"><label>Profissional</label><select name="professional_id"><?php foreach($activeProfessionals as $p):?><option value="<?=(int)$p['id']?>"><?=e($p['name'])?></option><?php endforeach;?></select></div><div class="form-group"><label>Dia</label><select name="weekday"><?php for($d=0;$d<=6;$d++):?><option value="<?=$d?>"><?=e(clinic_weekday_label($d))?></option><?php endfor;?></select></div><div class="form-group"><label>Início</label><input class="input" type="time" name="start_time" value="08:00"></div><div class="form-group"><label>Fim</label><input class="input" type="time" name="end_time" value="18:00"></div></div><button class="btn btn-primary">Salvar disponibilidade</button></form><?php if($availability):?><div class="table-wrap"><table><thead><tr><th>Profissional</th><th>Dia</th><th>Horário</th><th>Ação</th></tr></thead><tbody><?php foreach($availability as $av):?><tr><td><?=e($av['professional_name'])?></td><td><?=e(clinic_weekday_label((int)$av['weekday']))?></td><td><?=e(substr($av['start_time'],0,5).'–'.substr($av['end_time'],0,5))?></td><td><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="delete_clinic_professional_availability"><input type="hidden" name="id" value="<?=(int)$av['id']?>"><button class="btn btn-danger btn-sm" data-confirm="Retirar esta disponibilidade do profissional?">Retirar</button></form></td></tr><?php endforeach;?></tbody></table></div><?php endif;?></section><?php endif;?>

<section class="panel" id="clinicPatients"><div class="panel-header"><div><h2>👥 Pacientes</h2><p>Lista exclusiva desta instituição.</p></div></div><?php if(!$readOnly):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_clinic_patient"><input type="hidden" name="company_id" value="<?=$companyId?>"><div class="form-grid"><div class="form-group full"><label>ID do paciente (opcional)</label><input class="input" name="platform_user_id" placeholder="LXU-..."></div><div class="form-group"><label>Nome</label><input class="input" name="name"></div><div class="form-group"><label>E-mail</label><input class="input" type="email" name="email"></div><div class="form-group"><label>Documento</label><input class="input" name="document"></div><div class="form-group"><label>WhatsApp</label><input class="input" name="phone" data-phone-mask></div><div class="form-group"><label>Nascimento</label><input class="input" type="date" name="birth_date"></div><div class="form-group"><label>Senha inicial</label><input class="input" name="password" value="123456"></div><div class="form-group full"><label>Observações</label><textarea name="notes"></textarea></div></div><button class="btn btn-primary">+ Cadastrar paciente</button></form><?php endif;?>
<div class="table-wrap" style="margin-top:14px"><table><thead><tr><th>Paciente</th><th>ID</th><th>Contato</th><th>Nascimento</th><?php if(!$readOnly):?><th>Ação</th><?php endif;?></tr></thead><tbody><?php foreach($patients as $p):?><tr><td><strong><?=e($p['name'])?></strong><small style="display:block"><?=e($p['document'])?></small></td><td><?=e($p['platform_public_id']?:'—')?></td><td><?=e(format_phone($p['phone']))?><small style="display:block"><?=e($p['email'])?></small></td><td><?=$p['birth_date']?e(date('d/m/Y',strtotime($p['birth_date']))):'—'?></td><?php if(!$readOnly):?><td><div class="actions"><a class="btn btn-primary btn-sm" href="dashboard.php?page=clinic_record&id=<?=(int)$p['id']?>">Prontuário completo</a><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="delete_clinic_patient"><input type="hidden" name="id" value="<?=(int)$p['id']?>"><button class="btn btn-danger btn-sm" data-confirm="Remover paciente?">Remover</button></form></div></td><?php endif;?></tr><?php endforeach;?></tbody></table></div></section>

<?php if(!$readOnly):?><section class="panel"><div class="panel-header"><div><h2>➕ Agendar paciente</h2><p>Se existir atendimento próximo em outra instituição, o sistema exibirá um aviso antes de salvar.</p></div></div><?php if($patients):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_clinic_appointment"><input type="hidden" name="company_id" value="<?=$companyId?>"><div class="form-grid"><div class="form-group"><label>Paciente</label><select name="patient_id"><?php foreach($patients as $p):?><option value="<?=(int)$p['id']?>"><?=e($p['name'])?></option><?php endforeach;?></select></div><div class="form-group"><label>Especialidade</label><select name="specialty_id"><option value="">Selecione</option><?php foreach($consultSpecialties as $s):?><option value="<?=(int)$s['id']?>"><?=e($s['name'])?> — <?=money($s['price'])?></option><?php endforeach;?></select></div><div class="form-group"><label>Profissional</label><select name="professional_id"><option value="">Selecione</option><?php foreach($activeProfessionals as $p):?><option value="<?=(int)$p['id']?>"><?=e($p['name'])?></option><?php endforeach;?></select></div><div class="form-group"><label>Forma de atendimento</label><select name="booking_mode" data-booking-mode><option value="time">Data + horário</option><option value="arrival">Ordem de chegada</option></select></div><div class="form-group"><label>Data</label><input class="input" type="date" name="appointment_date" min="<?=e(date('Y-m-d'))?>" value="<?=e(date('Y-m-d'))?>"></div><div class="form-group" data-booking-time><label>Hora</label><input class="input" type="time" name="appointment_time"></div><div class="form-group"><label>Valor</label><input class="input" name="amount"></div><div class="form-group"><label>Pagamento</label><select name="payment_method"><option value="pix">Pix</option><option value="payment_link">Link</option><option value="card">Cartão</option><option value="cash">Presencial</option><option value="insurance">Convênio</option></select></div><div class="form-group full"><label>Observações</label><textarea name="notes"></textarea></div><label class="checkbox-row full"><input type="checkbox" name="confirm_conflict" value="1"> Confirmar mesmo se houver agendamento próximo em outra instituição</label></div><button class="btn btn-primary">Confirmar agendamento</button></form><?php else:?><div class="notice">Cadastre pelo menos um paciente.</div><?php endif;?></section><?php endif;?>

<section class="panel" id="clinicToday"><div class="panel-header"><div><h2>👥 Pacientes de hoje</h2><p>Lista operacional do dia para clínica e profissionais. A confirmação por localização aparece aqui.</p></div></div><div class="table-wrap"><table><thead><tr><th>Ordem/horário</th><th>Paciente</th><th>Profissional</th><th>Serviço</th><th>Presença</th><th>Status</th></tr></thead><tbody><?php if(!$todayRows):?><tr><td colspan="6"><div class="empty-state"><strong>Nenhum paciente para hoje</strong></div></td></tr><?php endif;?><?php foreach($todayRows as $a):?><tr><td><?=($a['booking_mode']??'time')==='arrival'?'Ordem #'.(int)($a['arrival_order']??0):e(substr((string)$a['appointment_time'],0,5))?></td><td><strong><?=e($a['patient_name'])?></strong></td><td><?=e($a['professional_name']?:'—')?></td><td><?=e($a['specialty_name']?:'Consulta')?></td><td><?php if(!empty($a['checkin_at'])):?><span class="badge success">📍 No local</span><small style="display:block"><?=e(date('H:i',strtotime($a['checkin_at'])))?> • <?=round((float)($a['checkin_distance_m']??0))?> m</small><?php else:?><span class="muted">Aguardando</span><?php endif;?></td><td><?=status_badge($a['status'])?></td></tr><?php endforeach;?></tbody></table></div></section>

<section class="panel" id="clinicAgenda"><div class="panel-header"><div><h2>📅 Agenda geral</h2><p>Primeira consulta e retorno aparecem identificados.</p></div></div><div class="table-wrap"><table><thead><tr><th>Paciente</th><th>Tipo</th><th>Serviço</th><th>Profissional</th><th>Data</th><th>Valor</th><th>Status</th><th>Ações</th></tr></thead><tbody><?php if(!$appointments):?><tr><td colspan="8"><div class="empty-state"><strong>Nenhum agendamento</strong></div></td></tr><?php endif;?><?php foreach($appointments as $a):?><tr><td><strong><?=e($a['patient_name'])?></strong><small style="display:block"><?=e($a['platform_user_id']?public_user_id((int)$a['platform_user_id']):'')?></small></td><td><?=!empty($a['first_visit'])?'Primeira consulta':'Retorno'?></td><td><?=e($a['specialty_name']?:'—')?></td><td><?=e($a['professional_name']?:'—')?></td><td><?=e(date('d/m/Y',strtotime($a['appointment_date'])))?><small style="display:block"><?=(($a['booking_mode']??'time')==='arrival')?'Ordem de chegada #'.(int)($a['arrival_order']??0):e(substr((string)$a['appointment_time'],0,5))?></small><?php if(!empty($a['checkin_at'])):?><small style="display:block">📍 presença <?=e(date('H:i',strtotime($a['checkin_at'])))?></small><?php endif;?></td><td><?=money($a['amount'])?></td><td><?=status_badge($a['status'])?></td><td><?php if(!empty($a['payment_proof'])):?><a class="btn btn-secondary btn-sm" target="_blank" href="<?=e(media_url($a['payment_proof']))?>">Comprovante Pix</a><?php if(!$readOnly&&($a['payment_status']??'pending')!=='paid'):?><form method="post" action="actions.php" style="display:inline"><?=csrf_field()?><input type="hidden" name="action" value="clinic_confirm_payment"><input type="hidden" name="kind" value="appointment"><input type="hidden" name="id" value="<?=(int)$a['id']?>"><button class="btn btn-accent btn-sm">Confirmar Pix</button></form><?php endif;?><?php endif;?><?php if(!$readOnly&&!in_array($a['status'],['completed','cancelled'],true)):?><form method="post" action="actions.php" class="actions"><?=csrf_field()?><input type="hidden" name="action" value="update_clinic_appointment"><input type="hidden" name="id" value="<?=(int)$a['id']?>"><button class="btn btn-primary btn-sm" name="status" value="confirmed">Confirmar</button><button class="btn btn-accent btn-sm" name="status" value="completed">Concluir</button><button class="btn btn-danger btn-sm" name="status" value="cancelled">Cancelar</button></form><?php else:?>—<?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section>

<section class="panel"><div class="panel-header"><div><h2>🧪 Solicitações de exames</h2><p>Pedidos, agendamentos e resultados da instituição.</p></div></div><div class="cards-list"><?php if(!$exams):?><div class="empty-state"><strong>Nenhuma solicitação de exame</strong></div><?php endif;?><?php foreach($exams as $ex):?><article class="item-card"><div class="item-body"><h3><?=e($ex['exam_name']?:'Exame')?> • <?=e($ex['patient_name'])?></h3><p><?=status_badge($ex['status'])?><?=!empty($ex['scheduled_date'])?' • '.e(date('d/m/Y',strtotime($ex['scheduled_date'])).' '.substr((string)$ex['scheduled_time'],0,5)):''?></p><small>Profissional: <?=e($ex['professional_name']?:'Solicitação do paciente')?></small><?php if(!empty($ex['payment_proof'])):?><div class="actions" style="margin-top:8px"><a class="btn btn-secondary btn-sm" target="_blank" href="<?=e(media_url($ex['payment_proof']))?>">Comprovante Pix</a><?php if(!$readOnly&&($ex['payment_status']??'pending')!=='paid'):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_confirm_payment"><input type="hidden" name="kind" value="exam"><input type="hidden" name="id" value="<?=(int)$ex['id']?>"><button class="btn btn-accent btn-sm">Confirmar Pix</button></form><?php endif;?></div><?php endif;?><?php if(!$readOnly):?><form method="post" action="actions.php" enctype="multipart/form-data" style="margin-top:10px"><?=csrf_field()?><input type="hidden" name="action" value="clinic_update_exam_request"><input type="hidden" name="id" value="<?=(int)$ex['id']?>"><div class="form-grid"><div class="form-group"><label>Data</label><input class="input" type="date" name="scheduled_date" value="<?=e($ex['scheduled_date'])?>"></div><div class="form-group"><label>Hora</label><input class="input" type="time" name="scheduled_time" value="<?=e($ex['scheduled_time'])?>"></div><div class="form-group"><label>Status</label><select name="status"><?php foreach(['requested'=>'Solicitado','scheduled'=>'Agendado','completed'=>'Concluído','cancelled'=>'Cancelado'] as $k=>$v):?><option value="<?=$k?>"<?=selected($ex['status'],$k)?>><?=$v?></option><?php endforeach;?></select></div><div class="form-group"><label>Resultado</label><input class="input" type="file" name="result_file"></div><div class="form-group full"><label>Observação do resultado</label><textarea name="result_notes"><?=e($ex['result_notes'])?></textarea></div></div><button class="btn btn-primary btn-sm">Salvar exame</button></form><?php elseif(!empty($ex['result_notes'])):?><div class="notice"><?=nl2br(e($ex['result_notes']))?></div><?php endif;?></div></article><?php endforeach;?></div></section>

<?php if($readOnly):$q=db()->prepare("SELECT r.*,pa.name patient_name,pr.name professional_name FROM clinic_patient_records r JOIN clinic_patients pa ON pa.id=r.patient_id JOIN clinic_professionals pr ON pr.id=r.professional_id WHERE r.company_id=? ORDER BY r.id DESC LIMIT 200");$q->execute([$companyId]);$records=$q->fetchAll();$q=db()->prepare("SELECT c.*,pa.name patient_name FROM clinic_professional_contacts c LEFT JOIN clinic_patients pa ON pa.id=c.patient_id WHERE c.company_id=? ORDER BY c.id DESC LIMIT 200");$q->execute([$companyId]);$contacts=$q->fetchAll();?><section class="panel"><div class="panel-header"><div><h2>🔎 Dados liberados pela denúncia</h2><p>Prontuários e contatos internos disponíveis somente enquanto a denúncia estiver aberta.</p></div></div><div class="table-wrap"><table><thead><tr><th>Paciente</th><th>Profissional</th><th>Diagnóstico</th><th>Observações</th><th>Data</th></tr></thead><tbody><?php foreach($records as $r):?><tr><td><?=e($r['patient_name'])?></td><td><?=e($r['professional_name'])?></td><td><?=e(short_text((string)$r['diagnosis'],100))?></td><td><?=e(short_text((string)$r['observations'],120))?></td><td><?=e(date('d/m/Y H:i',strtotime($r['created_at'])))?></td></tr><?php endforeach;?></tbody></table></div><h3 style="margin-top:18px">Contatos internos</h3><div class="table-wrap"><table><thead><tr><th>Nome</th><th>Telefone</th><th>E-mail</th><th>Notas</th></tr></thead><tbody><?php foreach($contacts as $c):?><tr><td><?=e($c['name'])?></td><td><?=e(format_phone($c['phone']))?></td><td><?=e($c['email'])?></td><td><?=e(short_text((string)$c['notes'],120))?></td></tr><?php endforeach;?></tbody></table></div></section><?php endif;?>

<script>document.querySelectorAll('[data-booking-mode]').forEach(sel=>{const f=sel.closest('form'),box=f?.querySelector('[data-booking-time]'),input=box?.querySelector('input');const sync=()=>{const arrival=sel.value==='arrival';if(box)box.style.display=arrival?'none':'';if(input){input.required=!arrival;if(arrival)input.value='';}};sel.addEventListener('change',sync);sync();});</script>
