<?php
$u=current_user();$uid=(int)($u['id']??0);if($uid<1){http_response_code(403);exit('Faça login para acessar o painel profissional.');}
clinic_refresh_professional_link_states($uid);
$memberships=clinic_professional_memberships($uid,true);
if(!$memberships){http_response_code(403);exit('Seu usuário ainda não possui vínculo com uma clínica.');}
$pending=[];$active=[];foreach($memberships as $m){if(($m['status']??'')==='active'&&($m['link_state']??'active')==='active')$active[]=$m;else $pending[]=$m;}
$requestedCompany=(int)request('clinic_company',0);$pr=null;foreach($active as $m){if($requestedCompany>0&&(int)$m['company_id']===$requestedCompany){$pr=$m;break;}}if(!$pr&&$active)$pr=$active[0];
?>
<section class="page-intro"><div><span class="mini-label">🩺 PAINEL DO PROFISSIONAL</span><h2><?=e($u['name'])?></h2><p>Agenda, pacientes, prontuário, exames, contatos e cobranças separados por instituição.</p></div><div class="actions"><a class="btn btn-secondary" href="dashboard.php?page=home">← Início</a><a class="btn btn-primary" href="dashboard.php?page=clinic_queue">🎫 Fila Virtual</a><a class="btn btn-secondary" href="dashboard.php?page=clinic_patient">Minha Saúde</a></div></section>

<?php if($pending):?><section class="panel"><div class="panel-header"><div><h2>🔔 Solicitações e vínculos pendentes</h2><p>Confirme os pedidos feitos pelas clínicas. Cada instituição fica separada.</p></div></div><div class="cards-list">
<?php foreach($pending as $m):$state=(string)($m['link_state']??'pending_professional');?><article class="item-card"><div class="item-body"><h3><?=e($m['company_name'])?></h3><p><?=e($m['specialty_name']?:$m['professional_type']?:'Profissional')?> • <?=e(clinic_link_state_label($state))?></p>
<?php if($state==='pending_professional'):?><form method="post" action="actions.php" class="actions"><?=csrf_field()?><input type="hidden" name="action" value="clinic_professional_link_response"><input type="hidden" name="id" value="<?=(int)$m['id']?>"><button class="btn btn-accent btn-sm" name="decision" value="accept">Aceitar vínculo</button><button class="btn btn-danger btn-sm" name="decision" value="reject">Recusar</button></form>
<?php elseif($state==='pending_admin'):?><div class="notice">Seu aceite foi registrado. O segundo vínculo aguarda liberação do Administrador Sênior.</div>
<?php elseif($state==='waiting_payment'):?><div class="notice"><strong>Mensalidade necessária.</strong><br>A partir do terceiro vínculo, a conta precisa ter mensalidade ativa. Após a ativação, o vínculo é liberado automaticamente ao acessar este painel.</div><a class="btn btn-primary btn-sm" href="dashboard.php?page=subscriptions">Ver mensalidade</a>
<?php else:?><span class="status status-blocked"><?=e(clinic_link_state_label($state))?></span><?php endif;?></div></article><?php endforeach;?></div></section><?php endif;?>

<?php if(!$pr):?><section class="panel"><div class="empty-state"><strong>Nenhuma instituição ativa</strong>Aceite uma solicitação e conclua as etapas de liberação acima.</div></section><?php return; endif;
$professionalId=(int)$pr['id'];$companyId=(int)$pr['company_id'];
$q=db()->prepare("SELECT a.*,pa.name patient_name,pa.phone patient_phone,pa.email patient_email,pa.platform_user_id patient_user_id,pa.document patient_document,pa.birth_date patient_birth_date,s.name specialty_name,s.service_kind FROM clinic_appointments a JOIN clinic_patients pa ON pa.id=a.patient_id LEFT JOIN clinic_specialties s ON s.id=a.specialty_id WHERE a.professional_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");$q->execute([$professionalId]);$appointments=$q->fetchAll();
$q=db()->prepare("SELECT * FROM clinic_professional_availability WHERE professional_id=? AND status='active' ORDER BY weekday");$q->execute([$professionalId]);$availability=$q->fetchAll();
$q=db()->prepare("SELECT * FROM clinic_professional_blocks WHERE professional_id=? AND block_date>=date('now') ORDER BY block_date,start_time");$q->execute([$professionalId]);$blocks=$q->fetchAll();
$q=db()->prepare("SELECT * FROM clinic_patients WHERE company_id=? AND status='active' ORDER BY name");$q->execute([$companyId]);$patients=$q->fetchAll();
$q=db()->prepare("SELECT * FROM clinic_specialties WHERE company_id=? AND status='active' ORDER BY name");$q->execute([$companyId]);$specialties=$q->fetchAll();$examSpecialties=array_values(array_filter($specialties,fn($s)=>($s['service_kind']??'consultation')==='exam'));$consultSpecialties=array_values(array_filter($specialties,fn($s)=>($s['service_kind']??'consultation')!=='exam'));
$q=db()->prepare("SELECT * FROM clinic_professional_contacts WHERE owner_user_id=? AND company_id=? ORDER BY name");$q->execute([$uid,$companyId]);$contacts=$q->fetchAll();
$q=db()->prepare("SELECT r.*,pa.name patient_name FROM clinic_patient_records r JOIN clinic_patients pa ON pa.id=r.patient_id WHERE r.professional_id=? ORDER BY r.id DESC");$q->execute([$professionalId]);$records=$q->fetchAll();$recordByAppointment=[];foreach($records as $r)if(!empty($r['appointment_id']))$recordByAppointment[(int)$r['appointment_id']]=$r;
$q=db()->prepare("SELECT e.*,pa.name patient_name,pa.platform_user_id,s.name exam_name,s.price FROM clinic_exam_requests e JOIN clinic_patients pa ON pa.id=e.patient_id LEFT JOIN clinic_specialties s ON s.id=e.specialty_id WHERE e.company_id=? AND (e.professional_id=? OR e.professional_id IS NULL) ORDER BY CASE e.status WHEN 'requested' THEN 0 WHEN 'scheduled' THEN 1 ELSE 2 END,e.id DESC");$q->execute([$companyId,$professionalId]);$exams=$q->fetchAll();
$ratingSummary=['rating_avg'=>0,'rating_count'=>0];$professionalReviews=[];
try{$rq=db()->prepare("SELECT COALESCE(ROUND(AVG(rating),1),0) rating_avg,COUNT(*) rating_count FROM reviews WHERE target_type='clinic_professional' AND target_id=? AND status='published'");$rq->execute([$professionalId]);$ratingSummary=$rq->fetch()?:$ratingSummary;$rq=db()->prepare("SELECT r.*,u.name reviewer_name FROM reviews r LEFT JOIN users u ON u.id=r.reviewer_id WHERE r.target_type='clinic_professional' AND r.target_id=? AND r.status='published' ORDER BY r.id DESC LIMIT 20");$rq->execute([$professionalId]);$professionalReviews=$rq->fetchAll();}catch(Throwable $e){}
$today=0;$upcoming=0;$completed=0;$pendingCount=0;$revenue=0;$patientIds=[];$todayStr=date('Y-m-d');$todayRows=array_values(array_filter($appointments,fn($a)=>$a['appointment_date']===$todayStr&&!in_array($a['status'],['cancelled','completed'],true)));foreach($appointments as $a){if($a['appointment_date']===$todayStr&&!in_array($a['status'],['cancelled','completed'],true))$today++;if($a['appointment_date']>=$todayStr&&!in_array($a['status'],['cancelled','completed'],true))$upcoming++;if($a['status']==='completed'){$completed++;$revenue+=(float)$a['amount'];}if(in_array($a['status'],['scheduled','confirmed'],true))$pendingCount++;$patientIds[(int)$a['patient_id']]=1;}
?>
<section class="panel"><div class="panel-header"><div><h2>🏥 Instituições vinculadas</h2><p>Toque no nome para acessar somente a agenda e os pacientes daquela instituição.</p></div><span class="status status-active"><?=count($active)?> vínculo(s) ativo(s)</span></div><div class="actions"><?php foreach($active as $m):?><a class="btn <?=((int)$m['company_id']===$companyId)?'btn-primary':'btn-secondary'?>" href="dashboard.php?page=clinic_professional&clinic_company=<?=(int)$m['company_id']?>"><?=e($m['company_name'])?></a><?php endforeach;?></div></section>

<section class="page-intro clinic-page-intro"><div><span class="mini-label">INSTITUIÇÃO ATUAL</span><h2><?=e($pr['company_name'])?></h2><p><?=e($pr['specialty_name']?:$pr['professional_type']?:'Profissional')?><?=!empty($pr['registry'])?' • '.e($pr['registry']):''?></p></div><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="toggle_clinic_professional_whatsapp"><input type="hidden" name="professional_id" value="<?=$professionalId?>"><button class="btn <?=!empty($pr['share_whatsapp'])?'btn-danger':'btn-accent'?>"><?=!empty($pr['share_whatsapp'])?'Ocultar WhatsApp':'Liberar WhatsApp aos pacientes'?></button></form></section>

<section class="stats-grid clinic-stats-grid"><a class="stat-card stat-card-link" href="#professionalReviews"><div class="stat-top"><span>Avaliação</span><span class="stat-icon">⭐</span></div><strong><?=number_format((float)($ratingSummary['rating_avg']??0),1,',','.')?>/5</strong><small><?=(int)($ratingSummary['rating_count']??0)?> avaliação(ões)</small></a><a class="stat-card stat-card-link" href="#professionalAgenda"><div class="stat-top"><span>Consultas hoje</span><span class="stat-icon">📅</span></div><strong><?=$today?></strong><small>na instituição atual</small></a><a class="stat-card stat-card-link" href="#professionalAgenda"><div class="stat-top"><span>Próximas</span><span class="stat-icon">⏰</span></div><strong><?=$upcoming?></strong><small>agendadas</small></a><a class="stat-card stat-card-link" href="#professionalPatients"><div class="stat-top"><span>Pacientes</span><span class="stat-icon">👥</span></div><strong><?=count($patients)?></strong><small>na clínica</small></a><a class="stat-card stat-card-link" href="#professionalFinance"><div class="stat-top"><span>Faturamento</span><span class="stat-icon">💰</span></div><strong><?=money($revenue)?></strong><small>consultas concluídas</small></a><a class="stat-card stat-card-link" href="#professionalAgenda"><div class="stat-top"><span>Pendentes</span><span class="stat-icon">🔔</span></div><strong><?=$pendingCount?></strong><small>confirmar / atender</small></a></section>

<section class="grid-2"><article class="panel"><div class="panel-header"><div><h2>📆 Disponibilidade</h2><p>Agenda semanal.</p></div></div><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_clinic_professional_availability"><input type="hidden" name="professional_id" value="<?=$professionalId?>"><div class="form-grid"><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 horário</button></form><?php if($availability):?><div class="cards-list" style="margin-top:12px"><?php foreach($availability as $av):?><div class="item-card"><div class="item-body"><strong><?=e(clinic_weekday_label((int)$av['weekday']).' '.substr($av['start_time'],0,5).'–'.substr($av['end_time'],0,5))?></strong><form method="post" action="actions.php" style="margin-top:8px"><?=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?">Retirar disponibilidade</button></form></div></div><?php endforeach;?></div><?php endif;?></article>
<article class="panel"><div class="panel-header"><div><h2>⛔ Bloquear horário</h2><p>Folga, reunião ou indisponibilidade.</p></div></div><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="save_clinic_professional_block"><input type="hidden" name="professional_id" value="<?=$professionalId?>"><div class="form-grid"><div class="form-group"><label>Data</label><input class="input" type="date" name="block_date" min="<?=e(date('Y-m-d'))?>" required></div><div class="form-group"><label>Início</label><input class="input" type="time" name="start_time"></div><div class="form-group"><label>Fim</label><input class="input" type="time" name="end_time"></div><div class="form-group"><label>Motivo</label><input class="input" name="reason"></div></div><button class="btn btn-secondary">Adicionar</button></form><?php if($blocks):?><div class="cards-list" style="margin-top:12px"><?php foreach($blocks as $b):?><div class="item-card"><div class="item-body"><strong><?=e(date('d/m/Y',strtotime($b['block_date'])))?></strong><small><?=e(($b['start_time']?$b['start_time'].'–'.$b['end_time']:'Dia inteiro').' '.$b['reason'])?></small><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="delete_clinic_professional_block"><input type="hidden" name="id" value="<?=(int)$b['id']?>"><button class="btn btn-danger btn-sm">Remover</button></form></div></div><?php endforeach;?></div><?php endif;?></article></section>

<section class="grid-2" id="professionalPatients"><article class="panel"><div class="panel-header"><div><h2>➕ Cadastrar paciente</h2><p>O profissional pode incluir um paciente usando o ID existente ou criar uma conta.</p></div></div><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_professional_save_patient"><input type="hidden" name="professional_id" value="<?=$professionalId?>"><div class="form-grid"><div class="form-group full"><label>ID da plataforma (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>WhatsApp</label><input class="input" name="phone" data-phone-mask></div><div class="form-group"><label>Documento</label><input class="input" name="document"></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><button class="btn btn-primary">Salvar paciente</button></form></article>
<article class="panel"><div class="panel-header"><div><h2>📅 Criar agendamento</h2><p>O sistema avisa se o paciente já tiver horário próximo em outra clínica/hospital.</p></div></div><?php if($patients&&$consultSpecialties):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_professional_create_appointment"><input type="hidden" name="professional_id" value="<?=$professionalId?>"><div class="form-grid"><div class="form-group"><label>Paciente</label><select name="patient_id" required><?php foreach($patients as $p):?><option value="<?=(int)$p['id']?>"><?=e($p['name'].' • '.($p['platform_user_id']?public_user_id((int)$p['platform_user_id']):'sem ID'))?></option><?php endforeach;?></select></div><div class="form-group"><label>Especialidade / procedimento</label><select name="specialty_id" required><?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>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'))?>" required></div><div class="form-group" data-booking-time><label>Hora</label><input class="input" type="time" name="appointment_time" required></div><div class="form-group"><label>Valor</label><input class="input" name="amount" inputmode="decimal"></div><div class="form-group"><label>Pagamento</label><select name="payment_method"><option value="pix">Pix</option><option value="link">Link</option><option value="card">Cartão</option><option value="cash">Presencial</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">Agendar paciente</button></form><?php else:?><div class="notice">Cadastre paciente e especialidade para criar um agendamento.</div><?php endif;?></article></section>

<section class="panel" id="institutionPatients"><div class="panel-header"><div><h2>👥 Pacientes de <?=e($pr['company_name'])?></h2><p>Lista separada da instituição selecionada. Toque no nome da instituição acima para trocar a lista.</p></div><span class="status status-active"><?=count($patients)?> paciente(s)</span></div><div class="cards-list"><?php if(!$patients):?><div class="empty-state"><strong>Nenhum paciente nesta instituição</strong></div><?php endif;?><?php foreach($patients as $p):$histCount=0;foreach($appointments as $a)if((int)$a['patient_id']===(int)$p['id'])$histCount++;?><article class="item-card"><div class="item-body"><h3><?=e($p['name'])?></h3><p>ID: <?=e(!empty($p['platform_user_id'])?public_user_id((int)$p['platform_user_id']):'—')?> • <?=e(format_phone($p['phone']))?></p><div class="item-meta"><span><strong>Consultas com você:</strong> <?=$histCount?></span><span><strong>Nascimento:</strong> <?=$p['birth_date']?e(date('d/m/Y',strtotime($p['birth_date']))):'—'?></span></div><div class="actions"><a class="btn btn-primary btn-sm" href="dashboard.php?page=clinic_record&id=<?=(int)$p['id']?>">Prontuário completo</a><?php if($p['phone']):?><a class="btn btn-accent btn-sm" target="_blank" href="<?=e(whatsapp_url($p['phone'],'Olá, sou '.$u['name'].' da '.$pr['company_name'].'.'))?>">WhatsApp</a><?php endif;?></div></div></article><?php endforeach;?></div></section>

<section class="panel" id="professionalToday"><div class="panel-header"><div><h2>👥 Pacientes de hoje</h2><p>Fila e horários do dia deste profissional, incluindo confirmação de presença pela localização.</p></div><span class="status status-active"><?=count($todayRows)?> paciente(s)</span></div><div class="table-wrap"><table><thead><tr><th>Ordem/horário</th><th>Paciente</th><th>Serviço</th><th>Presença</th><th>Status</th></tr></thead><tbody><?php if(!$todayRows):?><tr><td colspan="5"><div class="empty-state"><strong>Nenhum atendimento 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><small style="display:block"><?=e(format_phone($a['patient_phone']))?></small></td><td><?=e($a['specialty_name']?:'Consulta')?></td><td><?php if(!empty($a['checkin_at'])):?><span class="badge success">📍 Presente</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="professionalAgenda"><div class="panel-header"><div><h2>🗓️ Agenda da instituição</h2><p>Cards com primeira consulta/retorno, contato e anotações. Use os detalhes para registrar o prontuário durante o atendimento.</p></div><span class="status status-active">Concluídos: <?=$completed?></span></div><div class="clinic-appointment-cards"><?php if(!$appointments):?><div class="empty-state"><strong>Nenhuma consulta nesta instituição</strong></div><?php endif;?><?php foreach($appointments as $a):$rec=$recordByAppointment[(int)$a['id']]??[];?><article class="panel clinic-appointment-card"><div class="panel-header"><div><h3><?=e($a['patient_name'])?> <small>#<?=e($a['patient_user_id']?public_user_id((int)$a['patient_user_id']):'sem ID')?></small></h3><p><?=e(date('d/m/Y',strtotime($a['appointment_date'])))?> • <?=(($a['booking_mode']??'time')==='arrival')?'Ordem de chegada #'.(int)($a['arrival_order']??0):'às '.e(substr($a['appointment_time'],0,5))?> • <?=e($a['specialty_name']?:'Atendimento')?></p></div><div><?=status_badge($a['status'])?> <span class="status <?=!empty($a['first_visit'])?'status-pending':'status-active'?>"><?=!empty($a['first_visit'])?'Primeira consulta':'Retorno'?></span></div></div><div class="item-meta"><span><strong>WhatsApp:</strong> <?=e(format_phone($a['patient_phone']))?></span><span><strong>E-mail:</strong> <?=e($a['patient_email']?:'—')?></span><span><strong>Valor:</strong> <?=money($a['amount'])?></span></div><div class="actions" style="margin-top:10px"><?php if($a['patient_phone']):?><a class="btn btn-accent btn-sm" target="_blank" href="<?=e(whatsapp_url($a['patient_phone'],'Olá, sou '.$u['name'].' da '.$pr['company_name'].'.'))?>">WhatsApp</a><?php endif;?><?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(($a['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="appointment"><input type="hidden" name="id" value="<?=(int)$a['id']?>"><button class="btn btn-primary btn-sm">Confirmar Pix</button></form><?php endif;?><?php endif;?></div>
<?php if(!in_array($a['status'],['cancelled','completed'],true)):?><form method="post" action="actions.php" style="margin-top:12px"><?=csrf_field()?><input type="hidden" name="action" value="clinic_professional_update_appointment"><input type="hidden" name="id" value="<?=(int)$a['id']?>"><textarea name="professional_notes" placeholder="Anotação rápida da consulta"><?=e($a['professional_notes'])?></textarea><div class="actions"><button class="btn btn-secondary 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="no_show">Faltou</button><button class="btn btn-danger btn-sm" name="status" value="cancelled" data-confirm="Cancelar este agendamento do paciente?">Cancelar</button></div></form><?php endif;?>
<details style="margin-top:12px"><summary class="btn btn-secondary btn-sm">🩺 Prontuário / Atendimento</summary><form method="post" action="actions.php" enctype="multipart/form-data" style="margin-top:12px"><?=csrf_field()?><input type="hidden" name="action" value="save_clinic_patient_record"><input type="hidden" name="appointment_id" value="<?=(int)$a['id']?>"><div class="form-grid"><div class="form-group full"><label>Sintomas</label><textarea name="symptoms"><?=e($rec['symptoms']??'')?></textarea></div><div class="form-group full"><label>Avaliação</label><textarea name="assessment"><?=e($rec['assessment']??'')?></textarea></div><div class="form-group"><label>Diagnóstico</label><textarea name="diagnosis"><?=e($rec['diagnosis']??'')?></textarea></div><div class="form-group"><label>Prescrição / medicamentos</label><textarea name="prescriptions"><?=e($rec['prescriptions']??'')?></textarea></div><div class="form-group"><label>Alergias</label><textarea name="allergies"><?=e($rec['allergies']??'')?></textarea></div><div class="form-group"><label>Medicamentos em uso</label><textarea name="medications"><?=e($rec['medications']??'')?></textarea></div><div class="form-group full"><label>Exames solicitados</label><textarea name="exam_requests"><?=e($rec['exam_requests']??'')?></textarea></div><div class="form-group full"><label>Observações médicas</label><textarea name="observations"><?=e($rec['observations']??'')?></textarea></div><div class="form-group full"><label>Anexar PDF, imagem ou documento</label><input class="input" type="file" name="attachment_file"><?php if(!empty($rec['attachment_path'])):?><small>Arquivo já anexado ao prontuário.</small><?php endif;?></div></div><button class="btn btn-primary">Salvar prontuário</button></form></details>
<?php if($a['status']==='completed'&&!empty($a['patient_user_id'])):?><details style="margin-top:10px"><summary class="btn btn-primary btn-sm">💳 Enviar cobrança rápida</summary><form method="post" action="actions.php" style="margin-top:10px"><?=csrf_field()?><input type="hidden" name="action" value="clinic_professional_quick_charge"><input type="hidden" name="source_type" value="appointment"><input type="hidden" name="source_id" value="<?=(int)$a['id']?>"><div class="form-grid"><div class="form-group"><label>Valor</label><input class="input" name="amount" value="<?=e(number_format((float)$a['amount'],2,',',''))?>"></div><div class="form-group"><label>Forma</label><select name="payment_method"><option value="pix">Pix</option><option value="link">Link de pagamento</option></select></div><div class="form-group full"><label>Link de pagamento (opcional)</label><input class="input" type="url" name="payment_link"></div></div><button class="btn btn-primary btn-sm">Enviar cobrança</button></form></details><?php endif;?></article><?php endforeach;?></div></section>

<section class="grid-2"><article class="panel"><div class="panel-header"><div><h2>🧪 Solicitar exame</h2><p>Envie uma solicitação diretamente ao paciente.</p></div></div><?php if($patients&&$examSpecialties):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_professional_request_exam"><input type="hidden" name="professional_id" value="<?=$professionalId?>"><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>Exame</label><select name="specialty_id"><?php foreach($examSpecialties as $s):?><option value="<?=(int)$s['id']?>"><?=e($s['name'])?></option><?php endforeach;?></select></div><div class="form-group full"><label>Observações</label><textarea name="notes"></textarea></div></div><button class="btn btn-primary">Solicitar exame</button></form><?php else:?><div class="notice">Cadastre no catálogo um procedimento do tipo “Exame”.</div><?php endif;?></article>
<article class="panel"><div class="panel-header"><div><h2>📋 Exames solicitados</h2><p>Agendamento, resultado e conclusão.</p></div></div><div class="cards-list"><?php if(!$exams):?><div class="empty-state"><strong>Nenhum 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><?php if(!empty($ex['payment_proof'])):?><div class="actions" style="margin-bottom:8px"><a class="btn btn-secondary btn-sm" target="_blank" href="<?=e(media_url($ex['payment_proof']))?>">Comprovante Pix</a><?php if(($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-primary btn-sm">Confirmar Pix</button></form><?php endif;?></div><?php endif;?><form method="post" action="actions.php" enctype="multipart/form-data"><?=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-secondary btn-sm">Atualizar exame</button></form><?php if($ex['status']==='completed'&&!empty($ex['platform_user_id'])):?><form method="post" action="actions.php" class="actions" style="margin-top:8px"><?=csrf_field()?><input type="hidden" name="action" value="clinic_professional_quick_charge"><input type="hidden" name="source_type" value="exam"><input type="hidden" name="source_id" value="<?=(int)$ex['id']?>"><input class="input" style="max-width:140px" name="amount" value="<?=e(number_format((float)$ex['price'],2,',',''))?>"><select name="payment_method"><option value="pix">Pix</option><option value="link">Link</option></select><button class="btn btn-primary btn-sm">Cobrar</button></form><?php endif;?></div></article><?php endforeach;?></div></article></section>

<section class="panel" id="professionalContacts"><div class="panel-header"><div><h2>📱 Contatos WhatsApp</h2><p>Pacientes agendados entram automaticamente; você também pode criar, editar ou apagar contatos.</p></div></div><details><summary class="btn btn-primary btn-sm">+ Novo contato</summary><form method="post" action="actions.php" style="margin-top:12px"><?=csrf_field()?><input type="hidden" name="action" value="save_clinic_professional_contact"><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>WhatsApp</label><input class="input" name="phone" data-phone-mask></div><div class="form-group"><label>E-mail</label><input class="input" type="email" name="email"></div><div class="form-group full"><label>Notas</label><textarea name="notes"></textarea></div></div><button class="btn btn-primary">Salvar</button></form></details><div class="cards-list" style="margin-top:14px"><?php if(!$contacts):?><div class="empty-state"><strong>Nenhum contato</strong></div><?php endif;?><?php foreach($contacts as $c):?><article class="item-card"><div class="item-body"><h3><?=e($c['name'])?> <?=!empty($c['is_automatic'])?'<small>• automático</small>':''?></h3><p><?=e(format_phone($c['phone']))?> • <?=e($c['email'])?></p><div class="actions"><?php if($c['phone']):?><a class="btn btn-accent btn-sm" target="_blank" href="<?=e(whatsapp_url($c['phone'],'Olá!'))?>">WhatsApp</a><?php endif;?><details><summary class="btn btn-secondary btn-sm">Editar</summary><form method="post" action="actions.php" style="margin-top:8px"><?=csrf_field()?><input type="hidden" name="action" value="save_clinic_professional_contact"><input type="hidden" name="id" value="<?=(int)$c['id']?>"><input type="hidden" name="company_id" value="<?=$companyId?>"><input class="input" name="name" value="<?=e($c['name'])?>" required><input class="input" name="phone" value="<?=e($c['phone'])?>"><input class="input" name="email" value="<?=e($c['email'])?>"><textarea name="notes"><?=e($c['notes'])?></textarea><button class="btn btn-primary btn-sm">Salvar</button></form></details><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="delete_clinic_professional_contact"><input type="hidden" name="id" value="<?=(int)$c['id']?>"><button class="btn btn-danger btn-sm" data-confirm="Apagar contato?">Apagar</button></form></div></div></article><?php endforeach;?></div></section>

<section class="panel" id="professionalReviews"><div class="panel-header"><div><h2>⭐ Minhas avaliações</h2><p>Avaliações publicadas por pacientes após atendimentos concluídos nesta instituição.</p></div><span class="status status-active"><?=number_format((float)($ratingSummary['rating_avg']??0),1,',','.')?> / 5</span></div><?php if(!$professionalReviews):?><div class="empty-state"><strong>Ainda sem avaliações</strong>Quando um paciente avaliar um atendimento concluído, a nota aparecerá aqui.</div><?php else:?><div class="cards-list"><?php foreach($professionalReviews as $rv):?><article class="item-card"><div class="item-body"><div class="service-title-line"><div><h3><?=stars_html((float)$rv['rating'])?> <?=number_format((float)$rv['rating'],1,',','.')?></h3><small><?=e($rv['reviewer_name']?:'Paciente')?> • <?=e(date('d/m/Y',strtotime($rv['created_at'])))?></small></div></div><?php if(trim((string)($rv['comment']??''))!==''):?><p><?=nl2br(e($rv['comment']))?></p><?php endif;?></div></article><?php endforeach;?></div><?php endif;?></section>

<section class="panel" id="professionalFinance"><div class="panel-header"><div><h2>📊 Relatório rápido</h2><p>Resumo da instituição atual.</p></div></div><div class="item-meta"><span><strong>Consultas concluídas:</strong> <?=$completed?></span><span><strong>Faltas:</strong> <?=count(array_filter($appointments,fn($a)=>$a['status']==='no_show'))?></span><span><strong>Cancelamentos:</strong> <?=count(array_filter($appointments,fn($a)=>$a['status']==='cancelled'))?></span><span><strong>Pacientes atendidos/agendados:</strong> <?=count($patientIds)?></span><span><strong>Faturamento:</strong> <?=money($revenue)?></span></div><div class="actions" style="margin-top:12px"><a class="btn btn-secondary" href="dashboard.php?page=charges">Acessar Cobranças</a></div></section>

<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>
