<?php
$u=current_user();$uid=(int)$u['id'];
if($uid<1){http_response_code(403);exit('Faça login para acessar sua área de paciente.');}
$memberships=clinic_patient_memberships($uid);
$appointments=[];
try{
    $q=db()->prepare("SELECT a.*,pa.name patient_name,c.name clinic_name,c.phone clinic_phone,c.address clinic_address,c.address_number clinic_address_number,c.city clinic_city,c.state clinic_state,c.latitude clinic_lat,c.longitude clinic_lng,s.name specialty_name,s.duration_minutes,pr.name professional_name,pr.phone professional_phone,pr.share_whatsapp,pr.registry FROM clinic_appointments a JOIN clinic_patients pa ON pa.id=a.patient_id JOIN companies c ON c.id=a.company_id LEFT JOIN clinic_specialties s ON s.id=a.specialty_id LEFT JOIN clinic_professionals pr ON pr.id=a.professional_id WHERE pa.platform_user_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([$uid]);$appointments=$q->fetchAll();
}catch(Throwable $e){}
$upcoming=array_values(array_filter($appointments,fn($a)=>$a['appointment_date']>=date('Y-m-d')&&!in_array($a['status'],['cancelled','completed'],true)));
$history=array_values(array_filter($appointments,fn($a)=>!in_array($a,$upcoming,true)));
$examRequests=[];$patientRecords=[];
$queueItems=[];
try{$q=db()->prepare("SELECT q.*,c.name clinic_name,p.name professional_name,s.name service_name FROM clinic_virtual_queue q JOIN companies c ON c.id=q.company_id LEFT JOIN clinic_professionals p ON p.id=q.professional_id LEFT JOIN clinic_specialties s ON s.id=q.specialty_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 LIMIT 20");$q->execute([$uid]);$queueItems=$q->fetchAll();}catch(Throwable $e){}
try{$q=db()->prepare("SELECT e.*,c.name clinic_name,s.name exam_name,s.price,s.preparation_instructions,s.available_days,s.available_hours FROM clinic_exam_requests e JOIN clinic_patients pa ON pa.id=e.patient_id JOIN companies c ON c.id=e.company_id LEFT JOIN clinic_specialties s ON s.id=e.specialty_id WHERE pa.platform_user_id=? ORDER BY e.id DESC");$q->execute([$uid]);$examRequests=$q->fetchAll();}catch(Throwable $e){}
try{$q=db()->prepare("SELECT r.*,c.name clinic_name,pr.name professional_name,ps.name professional_specialty FROM clinic_patient_records r JOIN clinic_patients pa ON pa.id=r.patient_id JOIN companies c ON c.id=r.company_id LEFT JOIN clinic_professionals pr ON pr.id=r.professional_id LEFT JOIN clinic_specialties ps ON ps.id=pr.specialty_id WHERE pa.platform_user_id=? ORDER BY r.id DESC");$q->execute([$uid]);$patientRecords=$q->fetchAll();}catch(Throwable $e){}
$patientDiagnoses=[];$patientPrescriptions=[];$patientPrescriptionItems=[];$patientDocuments=[];
try{$q=db()->prepare("SELECT d.*,c.name clinic_name,pr.name professional_name,ps.name professional_specialty FROM clinic_diagnoses d JOIN clinic_patients pa ON pa.id=d.patient_id JOIN companies c ON c.id=d.company_id LEFT JOIN clinic_professionals pr ON pr.id=d.professional_id LEFT JOIN clinic_specialties ps ON ps.id=pr.specialty_id WHERE pa.platform_user_id=? ORDER BY d.diagnosed_at DESC,d.id DESC");$q->execute([$uid]);$patientDiagnoses=$q->fetchAll();}catch(Throwable $e){}
try{$q=db()->prepare("SELECT p.*,c.name clinic_name,pr.name professional_name,ps.name professional_specialty FROM clinic_prescriptions p JOIN clinic_patients pa ON pa.id=p.patient_id JOIN companies c ON c.id=p.company_id LEFT JOIN clinic_professionals pr ON pr.id=p.professional_id LEFT JOIN clinic_specialties ps ON ps.id=pr.specialty_id WHERE pa.platform_user_id=? AND COALESCE(p.release_to_patient,1)=1 ORDER BY p.prescribed_at DESC,p.id DESC");$q->execute([$uid]);$patientPrescriptions=$q->fetchAll();if($patientPrescriptions){$ids=array_map('intval',array_column($patientPrescriptions,'id'));$marks=implode(',',array_fill(0,count($ids),'?'));$iq=db()->prepare("SELECT * FROM clinic_prescription_items WHERE prescription_id IN ($marks) ORDER BY id");$iq->execute($ids);foreach($iq->fetchAll() as $it)$patientPrescriptionItems[(int)$it['prescription_id']][]=$it;}}catch(Throwable $e){}
try{$q=db()->prepare("SELECT d.*,c.name clinic_name FROM clinic_patient_documents d JOIN clinic_patients pa ON pa.id=d.patient_id JOIN companies c ON c.id=d.company_id WHERE pa.platform_user_id=? ORDER BY d.id DESC");$q->execute([$uid]);$patientDocuments=$q->fetchAll();}catch(Throwable $e){}

function clinic_patient_slots_for_professional(array $professional,int $days=30): array {
    $out=[];$duration=max(15,(int)($professional['duration_minutes']??30));
    for($i=0;$i<$days;$i++){$date=date('Y-m-d',strtotime('+'.$i.' days'));foreach(clinic_available_slots((int)$professional['id'],$date,$duration) as $slot){$out[]=['date'=>$date,'time'=>$slot];if(count($out)>=80)break 2;}}
    return $out;
}
?>
<section class="page-intro"><div><span class="mini-label">🧑‍⚕️ ÁREA DO PACIENTE</span><h2>Minha Saúde</h2><p>Clínicas, consultas, fila virtual, reagendamentos, comprovantes e histórico em um só lugar.</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=clinics">🏥 Encontrar clínicas</a><a class="btn btn-secondary" href="dashboard.php?page=favorite_addresses">📍 Meus endereços</a></div></section>

<section class="stats-grid clinic-stats-grid">
  <a class="stat-card stat-card-link" href="#myClinics"><div class="stat-top"><span>Minhas clínicas</span><span class="stat-icon">🏥</span></div><strong><?=count($memberships)?></strong><small>vínculos ativos • tocar para acessar</small></a>
  <a class="stat-card stat-card-link" href="#myMedicalRecords"><div class="stat-top"><span>Meus prontuários</span><span class="stat-icon">🩺</span></div><strong><?=count($memberships)?></strong><small>informações do prontuário</small></a>
  <a class="stat-card stat-card-link" href="#upcomingAppointments"><div class="stat-top"><span>Próximas consultas</span><span class="stat-icon">📅</span></div><strong><?=count($upcoming)?></strong><small>agendamentos futuros • tocar para acessar</small></a>
  <a class="stat-card stat-card-link" href="#appointmentHistory"><div class="stat-top"><span>Histórico</span><span class="stat-icon">🗂️</span></div><strong><?=count($history)?></strong><small>consultas anteriores • tocar para acessar</small></a>
  <a class="stat-card stat-card-link" href="#myExams"><div class="stat-top"><span>Exames</span><span class="stat-icon">🧪</span></div><strong><?=count($examRequests)?></strong><small>solicitações e resultados</small></a>
  <a class="stat-card stat-card-link" href="#virtualQueue"><div class="stat-top"><span>Fila Virtual</span><span class="stat-icon">🎫</span></div><strong><?=count(array_filter($queueItems,fn($x)=>!in_array($x['status'],['completed','cancelled'],true)))?></strong><small>senhas e atendimentos ativos</small></a>
</section>

<section class="panel" id="virtualQueue"><div class="panel-header"><div><h2>🎫 Fila Virtual</h2><p>Reserve um dia, escolha o profissional e acompanhe sua posição, previsão e status em tempo real.</p></div><a class="btn btn-accent" href="dashboard.php?page=clinic_queue">Abrir Fila Virtual</a></div><div class="cards-list"><?php if(!$queueItems):?><div class="empty-state"><strong>Nenhuma senha ou atendimento na fila</strong><span>Toque em “Abrir Fila Virtual” para reservar.</span></div><?php endif;?><?php foreach(array_slice($queueItems,0,5) as $qi):$qs=clinic_queue_stats($qi);?><article class="item-card"><div class="item-body"><h3>Senha Nº <?=str_pad((string)(int)$qi['queue_number'],2,'0',STR_PAD_LEFT)?> • <?=e($qi['clinic_name'])?></h3><p><?=e(date('d/m/Y',strtotime($qi['queue_date'])))?><?=!empty($qi['queue_time'])?' às '.e(substr($qi['queue_time'],0,5)):''?> • <?=e($qi['service_name']?:'Atendimento')?> • <?=e($qi['professional_name']?:'Profissional')?></p><div class="item-meta"><span><?=e(clinic_queue_status_label((string)$qi['status']))?></span><span><?=(int)$qs['people_ahead']?> à frente</span><span><?=(int)$qs['estimate_minutes']?> min estimados</span></div></div></article><?php endforeach;?></div></section>

<section class="panel" id="myClinics">
<div class="panel-header"><div><h2>🏥 Minhas clínicas</h2><p>Escolha o serviço, veja as datas com vagas e agende no mesmo fluxo visual do Lava-Jato.</p></div></div>
<?php if(!$memberships):?><div class="empty-state"><strong>Você ainda não está cadastrado como paciente</strong>Abra Clínicas Próximas, escolha uma clínica e toque em “Cadastrar como paciente”.</div>
<?php else:?><div class="cards-list clinic-membership-list">
<?php foreach($memberships as $m):
$cid=(int)$m['company_id'];$settings=clinic_settings($cid);
$q=db()->prepare("SELECT * FROM clinic_specialties WHERE company_id=? AND status='active' ORDER BY CASE service_kind WHEN 'consultation' THEN 0 WHEN 'procedure' THEN 1 ELSE 2 END,name");$q->execute([$cid]);$specialties=$q->fetchAll();
$q=db()->prepare("SELECT p.*,s.name specialty_name,s.price specialty_price,s.duration_minutes specialty_duration,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 WHERE p.company_id=? AND p.status='active' AND COALESCE(p.link_state,'active')='active' ORDER BY p.name");$q->execute([$cid]);$pros=$q->fetchAll();
$consultCatalog=array_values(array_filter($specialties,fn($sp)=>($sp['service_kind']??'consultation')!=='exam'));
$examCatalog=array_values(array_filter($specialties,fn($sp)=>($sp['service_kind']??'consultation')==='exam'));
$requestedDate=trim((string)request('clinic_date',date('Y-m-d')));if(!preg_match('/^\d{4}-\d{2}-\d{2}$/',$requestedDate)||$requestedDate<date('Y-m-d'))$requestedDate=date('Y-m-d');
$clinicDays=[];$firstOpenDate='';
for($di=0;$di<21;$di++){
  $d=date('Y-m-d',strtotime('+'.$di.' days'));$open=0;
  if((int)$settings['allow_self_booking'] && $consultCatalog && $pros){foreach($consultCatalog as $sp){$duration=max(15,(int)$sp['duration_minutes']);foreach($pros as $pr){if(!empty($pr['specialty_id'])&&(int)$pr['specialty_id']!==(int)$sp['id'])continue;$cap=clinic_professional_daily_capacity((int)$pr['id'],$d,'consultation');if($cap['reached'])continue;if(clinic_available_slots((int)$pr['id'],$d,$duration)){$open++;break 2;}}}}
  if(!$open && $examCatalog){foreach($examCatalog as $exsp){if(empty($exsp['allow_patient_booking']))continue;if(clinic_exam_available_dates($exsp,$cid,21)){$open++;break;}}}
  if($open&&!$firstOpenDate)$firstOpenDate=$d;$clinicDays[]=['date'=>$d,'open'=>$open];
}
if(!$firstOpenDate)$firstOpenDate=date('Y-m-d');
$clinicDayMap=[];foreach($clinicDays as $d)$clinicDayMap[$d['date']]=$d['open'];
if(empty($clinicDayMap[$requestedDate])&&$requestedDate!==$firstOpenDate)$clinicSelectedDate=$firstOpenDate;else $clinicSelectedDate=$requestedDate;
$clinicWeekdayNames=['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado'];
?>
<article class="item-card clinic-membership-card" id="clinicBooking<?=$cid?>"><div class="item-body">
<h3>🏥 <?=e($m['company_name'])?></h3><p>📍 <?=e(trim(($m['company_city']??'').'/'.($m['company_state']??''),'/'))?></p>
<div class="notice"><strong>🕒 Funcionamento</strong><br><?=e($settings['opening_hours']?:'Consulte a clínica.')?></div>
<div class="actions" style="margin-top:12px"><a class="btn btn-secondary btn-sm" href="dashboard.php?page=clinics&clinic=<?=$cid?>">Ver clínica</a></div>
<section class="panel" style="margin-top:14px;background:var(--panel2)"><div class="panel-header"><div><h3>📅 Escolha a data</h3><p>Assim como no Lava-Jato, somente dias com vagas aparecem como disponíveis.</p></div></div>
<div class="available-date-strip" data-auto-scroll-available><?php foreach($clinicDays as $d):$available=$d['open']>0;?><a class="date-chip<?= $available?' available':' busy' ?><?= $clinicSelectedDate===$d['date']?' active':'' ?>" data-available="<?= $available?'1':'0' ?>" href="dashboard.php?page=clinic_patient&clinic_date=<?=e($d['date'])?>#clinicBooking<?=$cid?>"><b><?=e($clinicWeekdayNames[(int)date('w',strtotime($d['date']))])?></b><span><?=e(date('d/m',strtotime($d['date'])))?></span><small><?=$available?'Vagas disponíveis':'Sem vaga'?></small></a><?php endforeach;?></div></section>

<?php
$selectedDate=$clinicSelectedDate;
$consultSlotOptions=[];$examForDate=[];
if((int)$settings['allow_self_booking'] && $consultCatalog && $pros){
 foreach($consultCatalog as $sp){$duration=max(15,(int)$sp['duration_minutes']);foreach($pros as $pr){if(!empty($pr['specialty_id'])&&(int)$pr['specialty_id']!==(int)$sp['id'])continue;$cap=clinic_professional_daily_capacity((int)$pr['id'],$selectedDate,'consultation');if($cap['reached'])continue;foreach(clinic_available_slots((int)$pr['id'],$selectedDate,$duration) as $slot){$consultSlotOptions[]=['value'=>(int)$pr['id'].'|'.$selectedDate.'|'.$slot,'specialty'=>(int)$sp['id'],'service'=>$sp['name'],'service_price'=>$sp['price'],'duration'=>$duration,'professional'=>$pr['name'],'rating'=>(float)$pr['professional_rating'],'rating_count'=>(int)$pr['professional_rating_count'],'time'=>$slot];}}}
}
foreach($examCatalog as $exsp){if(empty($exsp['allow_patient_booking']))continue;$sch=clinic_exam_schedule($exsp);$dates=clinic_exam_available_dates($exsp,$cid,21);$found=false;foreach($dates as $ed)if($ed['date']===$selectedDate){$examForDate[]=['sp'=>$exsp,'sch'=>$sch,'times'=>$sch['mode']==='time'?clinic_exam_available_times($exsp,$selectedDate):[],'date'=>$selectedDate];$found=true;break;}}
?>
<section class="panel" style="margin-top:14px;background:var(--panel2)"><div class="panel-header"><div><h3>🩺 Consultas e procedimentos</h3><p><?=e(date('d/m/Y',strtotime($selectedDate)))?> • horários livres dos profissionais.</p></div></div>
<div class="availability-grid">
<?php if(!$consultSlotOptions):?><div class="empty-state"><strong>Nenhum horário livre nesta data</strong><span>Escolha outra data disponível acima.</span></div><?php else:foreach($consultCatalog as $sp):$spSlots=array_values(array_filter($consultSlotOptions,fn($o)=>(int)$o['specialty']===(int)$sp['id']));if(!$spSlots)continue;?><article class="availability-card"><h3><?=e($sp['name'])?></h3><p class="muted"><?=e($sp['description']?:'Consulta/procedimento')?></p><div class="item-meta"><span><strong>Valor:</strong> <?=money($sp['price'])?></span><span><strong>Duração:</strong> <?=(int)$sp['duration_minutes']?> min</span></div><div class="slot-list"><?php foreach($spSlots as $op):?><button class="slot-pill available" type="button" data-modal-open="#clinicBook<?=$cid?>" data-clinic-slot-value="<?=e($op['value'])?>" data-clinic-specialty-value="<?=e((string)$op['specialty'])?>"><?=e($op['time'])?> • <?=e($op['professional'])?></button><?php endforeach;?></div></article><?php endforeach;endif;?><div class="actions" style="margin-top:14px"><button class="btn btn-primary btn-sm" type="button" data-modal-open="#clinicBook<?=$cid?>"<?= $consultSlotOptions?'':' disabled'?>>Agendar consulta</button></div>
</div></section>

<section class="panel" style="margin-top:14px;background:var(--panel2)"><div class="panel-header"><div><h3>🧪 Exames</h3><p><?=e(date('d/m/Y',strtotime($selectedDate)))?> • escolha o exame e siga a agenda da clínica.</p></div></div><div class="availability-grid">
<?php if(!$examForDate):?><div class="empty-state"><strong>Nenhum exame disponível nesta data</strong><span>As datas sem vagas não ficam disponíveis para seleção.</span></div><?php else:foreach($examForDate as $ef):$exsp=$ef['sp'];$sch=$ef['sch'];?><article class="availability-card"><h3><?=e($exsp['name'])?></h3><p class="muted"><?=e($exsp['description'])?></p><div class="item-meta"><span><strong>Valor:</strong> <?=money($exsp['price'])?></span><span><strong>Atendimento:</strong> <?=e($sch['mode']==='arrival'?'Ordem de chegada':$sch['start'].'–'.$sch['end'])?></span></div><?php if(!empty($exsp['preparation_instructions'])):?><div class="notice" style="margin-top:10px"><strong>Preparo:</strong> <?=nl2br(e($exsp['preparation_instructions']))?></div><?php endif;?><div class="slot-list"><?php if($sch['mode']==='arrival'):?><span class="slot-pill available">🚶 Dia disponível • ordem de chegada</span><?php elseif($ef['times']):foreach($ef['times'] as $tm):?><button class="slot-pill available" type="button" data-modal-open="#examBook<?=$cid?>_<?=((int)$exsp['id'])?>" data-exam-time-value="<?=e($tm)?>"><?=e($tm)?> • disponível</button><?php endforeach;else:?><span class="slot-pill full">Sem horário disponível</span><?php endif;?></div><?php if($sch['mode']==='arrival'||$ef['times']):?><button class="btn btn-primary btn-sm" style="margin-top:12px" type="button" data-modal-open="#examBook<?=$cid?>_<?=((int)$exsp['id'])?>">Solicitar exame</button><?php endif;?></article><?php endforeach;endif;?></div></section>

<?php if($consultSlotOptions):?><div class="modal" id="clinicBook<?=$cid?>"><div class="modal-card"><div class="modal-head"><h2>Agendar • <?=e($m['company_name'])?></h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_patient_book"><input type="hidden" name="company_id" value="<?=$cid?>"><input type="hidden" name="booking_mode" value="time"><div class="form-grid"><div class="form-group"><label>Serviço</label><select name="specialty_id" required data-clinic-modal-specialty><option value="">Selecione</option><?php foreach($consultCatalog as $sp):?><option value="<?=((int)$sp['id'])?>"><?=e($sp['name'])?> — <?=money($sp['price'])?></option><?php endforeach;?></select></div><div class="form-group"><label>Data</label><input class="input" type="date" name="appointment_date" value="<?=e($selectedDate)?>" readonly></div><div class="form-group full"><label>Profissional e horário</label><select name="slot_choice" required data-clinic-modal-slot><option value="">Escolha um horário</option><?php foreach($consultSlotOptions as $op):?><option value="<?=e($op['value'])?>" data-specialty="<?=e((string)$op['specialty'])?>"><?=e($op['professional'].' • '.$op['time'].' • '.$op['service'])?><?php if($op['rating_count']>0):?> • ★ <?=number_format($op['rating'],1,',','.')?><?php endif;?></option><?php endforeach;?></select></div><div class="form-group full"><label>Observações</label><textarea name="notes"></textarea></div></div><div class="form-actions"><button class="btn btn-primary">Confirmar agendamento</button></div></form></div></div><?php endif;?>
<?php foreach($examForDate as $ef):$exsp=$ef['sp'];$sch=$ef['sch'];if($sch['mode']!=='arrival'&&!$ef['times'])continue;?><div class="modal" id="examBook<?=$cid?>_<?=((int)$exsp['id'])?>"><div class="modal-card"><div class="modal-head"><h2>Solicitar exame • <?=e($exsp['name'])?></h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="clinic_patient_request_exam"><input type="hidden" name="company_id" value="<?=$cid?>"><input type="hidden" name="specialty_id" value="<?=((int)$exsp['id'])?>"><div class="form-grid"><div class="form-group"><label>Data</label><input class="input" type="date" name="scheduled_date" value="<?=e($selectedDate)?>" readonly></div><?php if($sch['mode']==='time'):?><div class="form-group"><label>Horário</label><select name="scheduled_time" required data-exam-modal-time><option value="">Selecione</option><?php foreach($ef['times'] as $tm):?><option value="<?=e($tm)?>"><?=e($tm)?></option><?php endforeach;?></select></div><?php else:?><div class="notice full">🚶 <strong>Ordem de chegada:</strong> não há horário reservado. O atendimento será realizado na ordem definida pela clínica.</div><?php endif;?><div class="form-group full"><label>Observações</label><textarea name="notes"></textarea></div></div><div class="form-actions"><button class="btn btn-primary">Confirmar solicitação</button></div></form></div></div><?php endforeach;?>
</div></article>
<?php endforeach;?></div><?php endif;?></section>

<section class="panel" id="myMedicalRecords"><div class="panel-header"><div><h2>🩺 Meus prontuários</h2><p>As informações registradas pela clínica aparecem diretamente aqui para o paciente.</p></div></div><div class="cards-list"><?php if(!$memberships):?><div class="empty-state"><strong>Nenhum prontuário disponível</strong>Quando uma clínica cadastrar você como paciente, o prontuário aparecerá aqui.</div><?php endif;?><?php foreach($memberships as $m):$mid=(int)$m['id'];$mcid=(int)$m['company_id'];$mRecords=array_values(array_filter($patientRecords,fn($r)=>(int)$r['patient_id']===$mid));$mDiagnoses=array_values(array_filter($patientDiagnoses,fn($r)=>(int)$r['patient_id']===$mid));$mPrescriptions=array_values(array_filter($patientPrescriptions,fn($r)=>(int)$r['patient_id']===$mid));$mExams=array_values(array_filter($examRequests,fn($r)=>(int)$r['patient_id']===$mid));$mDocuments=array_values(array_filter($patientDocuments,fn($r)=>(int)$r['patient_id']===$mid));?>
<article class="item-card"><div class="item-body"><div class="service-title-line"><div><h3><?=e($m['company_name'])?></h3><p><strong>Paciente:</strong> <?=e($m['name'])?><?=!empty($m['document'])?' • '.e($m['document']):''?></p></div></div>
<div class="item-meta" style="margin-top:10px"><span><strong><?=count($mRecords)?></strong> registros clínicos</span><span><strong><?=count($mDiagnoses)?></strong> diagnósticos</span><span><strong><?=count($mPrescriptions)?></strong> receitas</span><span><strong><?=count($mExams)?></strong> exames</span><span><strong><?=count($mDocuments)?></strong> documentos</span></div>
<?php if(!$mRecords&&!$mDiagnoses&&!$mPrescriptions&&!$mExams&&!$mDocuments):?><div class="notice" style="margin-top:12px">A clínica ainda não registrou informações clínicas neste prontuário.</div><?php endif;?>
<?php if($mRecords):?><details open style="margin-top:12px"><summary class="btn btn-secondary btn-sm">🧠 Histórico clínico</summary><div class="cards-list" style="margin-top:10px"><?php foreach(array_slice($mRecords,0,10) as $r):?><div class="notice"><strong>👨‍⚕️ Médico:</strong> <?=e($r['professional_name']?:'Profissional não informado')?><?php if(!empty($r['professional_specialty'])):?> • <strong>Especialidade:</strong> <?=e($r['professional_specialty'])?><?php endif;?><br><small><?=e(date('d/m/Y H:i',strtotime($r['created_at'])))?></small><br><strong>Sintomas:</strong> <?=nl2br(e($r['symptoms']?:'—'))?><br><strong>Avaliação:</strong> <?=nl2br(e($r['assessment']?:'—'))?><br><strong>Diagnóstico:</strong> <?=nl2br(e($r['diagnosis']?:'—'))?><br><strong>Alergias:</strong> <?=nl2br(e($r['allergies']?:'—'))?><br><strong>Medicamentos em uso:</strong> <?=nl2br(e($r['medications']?:'—'))?><br><strong>Prescrição/conduta:</strong> <?=nl2br(e($r['prescriptions']?:'—'))?><br><strong>Exames solicitados:</strong> <?=nl2br(e($r['exam_requests']?:'—'))?><br><strong>Observações/evolução:</strong> <?=nl2br(e($r['observations']?:'—'))?><?php if(!empty($r['attachment_path'])):?><br><a class="btn btn-secondary btn-sm" target="_blank" href="<?=e(media_url($r['attachment_path']))?>">Acessar Anexo</a><?php endif;?></div><?php endforeach;?></div></details><?php endif;?>
<?php if($mDiagnoses):?><details style="margin-top:10px"><summary class="btn btn-secondary btn-sm">🩺 Diagnósticos</summary><div class="cards-list" style="margin-top:10px"><?php foreach(array_slice($mDiagnoses,0,10) as $d):?><div class="notice"><strong><?=e($d['diagnosis'])?></strong><?=!empty($d['cid'])?' • CID '.e($d['cid']):''?><br><strong>👨‍⚕️ Médico:</strong> <?=e($d['professional_name']?:'Profissional não informado')?><?php if(!empty($d['professional_specialty'])):?> • <strong>Especialidade:</strong> <?=e($d['professional_specialty'])?><?php endif;?><br><?=e(date('d/m/Y',strtotime($d['diagnosed_at'])))?><?php if(!empty($d['observations'])):?><br><strong>Observações:</strong> <?=nl2br(e($d['observations']))?><?php endif;?><?php if(!empty($d['evolution'])):?><br><strong>Evolução:</strong> <?=nl2br(e($d['evolution']))?><?php endif;?></div><?php endforeach;?></div></details><?php endif;?>
<?php if($mPrescriptions):?><details style="margin-top:10px"><summary class="btn btn-secondary btn-sm">💊 Receitas liberadas</summary><div class="cards-list" style="margin-top:10px"><?php foreach(array_slice($mPrescriptions,0,10) as $rx):?><div class="notice"><strong><?=e($rx['title']?:'Receita eletrônica')?></strong><br><strong>👨‍⚕️ Médico:</strong> <?=e($rx['professional_name']?:'Profissional não informado')?><?php if(!empty($rx['professional_specialty'])):?> • <strong>Especialidade:</strong> <?=e($rx['professional_specialty'])?><?php endif;?><br><?=e(date('d/m/Y',strtotime($rx['prescribed_at'])))?><?php foreach($patientPrescriptionItems[(int)$rx['id']]??[] as $it):?><br><strong><?=e($it['medicine_name'])?></strong> — <?=e(trim(($it['dosage']??'').' '.($it['frequency']??'').' '.($it['duration_text']??'')))?><?php if(!empty($it['times_csv'])):?><br>⏰ <?=e($it['times_csv'])?><?php endif;?><?php endforeach;?><?php if(!empty($rx['instructions'])):?><br><?=nl2br(e($rx['instructions']))?><?php endif;?></div><?php endforeach;?></div></details><?php endif;?>
<?php if($mExams):?><details style="margin-top:10px"><summary class="btn btn-secondary btn-sm">🧪 Exames</summary><div class="cards-list" style="margin-top:10px"><?php foreach(array_slice($mExams,0,10) as $ex):?><div class="notice"><strong><?=e($ex['exam_name']?:'Exame')?></strong> • <?=status_badge($ex['status'])?><br><?=!empty($ex['scheduled_date'])?e(date('d/m/Y',strtotime($ex['scheduled_date']))):'Data a definir'?> <?=e(substr((string)($ex['scheduled_time']??''),0,5))?><?php if(!empty($ex['result_notes'])):?><br><strong>Resultado:</strong> <?=nl2br(e($ex['result_notes']))?><?php endif;?><?php if(!empty($ex['result_path'])):?><br><a class="btn btn-secondary btn-sm" target="_blank" href="<?=e(media_url($ex['result_path']))?>">Acessar Resultado</a><?php endif;?></div><?php endforeach;?></div></details><?php endif;?>
<?php if($mDocuments):?><details style="margin-top:10px"><summary class="btn btn-secondary btn-sm">📎 Documentos</summary><div class="cards-list" style="margin-top:10px"><?php foreach(array_slice($mDocuments,0,10) as $doc):?><div class="notice"><strong><?=e($doc['title'])?></strong> • <?=e(date('d/m/Y',strtotime($doc['created_at'])))?><br><?=e($doc['notes']?:'')?><br><a class="btn btn-secondary btn-sm" target="_blank" href="<?=e(media_url($doc['file_path']))?>">Acessar Documento</a></div><?php endforeach;?></div></details><?php endif;?>
</div></article>
<?php endforeach;?></div></section>

<section class="panel" id="upcomingAppointments"><div class="panel-header"><div><h2>Próximas consultas</h2><p>Consulte profissional, pagamento, comprovante, reagendamento e cancelamento.</p></div></div>
<div class="clinic-appointment-cards"><?php if(!$upcoming):?><div class="empty-state"><strong>Nenhuma consulta futura</strong></div><?php endif;?><?php foreach($upcoming as $a):$settings=clinic_settings((int)$a['company_id']);$route=google_directions_link(trim($a['clinic_address'].' '.$a['clinic_address_number'].' '.$a['clinic_city'].'/'.$a['clinic_state']),$a['clinic_lat'],$a['clinic_lng']);?>
<article class="panel clinic-appointment-card"><div class="panel-header"><div><h3><?=e($a['clinic_name'])?></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))?></p></div><?=status_badge($a['status'])?></div><div class="item-meta"><span><strong>Especialidade:</strong> <?=e($a['specialty_name']?:'—')?></span><span><strong>Profissional:</strong> <?=e($a['professional_name']?:'—')?></span><span><strong>Valor:</strong> <?=money($a['amount'])?></span><span><strong>Pagamento:</strong> <?=e($a['payment_status']==='paid'?'Pago':'Pendente')?></span></div>
<div class="actions" style="margin-top:12px"><a class="btn btn-secondary btn-sm" target="_blank" href="<?=e($route)?>">📍 Como chegar</a><a class="btn btn-secondary btn-sm" target="_blank" href="clinic_receipt.php?id=<?=$a['id']?>&download=1">🧾 Baixar PNG</a><?php if(!empty($a['share_whatsapp'])&&!empty($a['professional_phone'])):?><a class="btn btn-accent btn-sm" target="_blank" href="<?=e(whatsapp_url($a['professional_phone'],'Olá, sou '.$u['name'].'. Tenho uma consulta agendada em '.$a['clinic_name'].'.'))?>">WhatsApp do profissional</a><?php endif;?></div>
<?php if((int)$settings['online_payment_enabled'] && $a['payment_status']!=='paid'):?><div class="notice" style="margin-top:12px"><strong>Pagamento da consulta</strong><br><?php if(($settings['payment_method']??'')==='pix'&&!empty($settings['pix_key'])):?><code><?=e($settings['pix_key'])?></code> <button type="button" class="btn btn-secondary btn-sm" data-copy-text="<?=e($settings['pix_key'])?>" data-show-payment-proof="#clinicProof<?=(int)$a['id']?>">Copiar Pix</button><div id="clinicProof<?=(int)$a['id']?>" style="margin-top:10px"<?=empty($a['payment_proof'])?' hidden':''?>><?php if(!empty($a['payment_proof'])):?><a class="btn btn-secondary btn-sm" target="_blank" href="<?=e(media_url($a['payment_proof']))?>">Ver comprovante enviado</a><small style="display:block;margin-top:6px">Status: <?=e($a['payment_status']==='paid'?'confirmado pela clínica':'aguardando conferência')?></small><?php else:?><form method="post" action="actions.php" enctype="multipart/form-data" style="margin-top:8px"><?=csrf_field()?><input type="hidden" name="action" value="clinic_patient_upload_payment_proof"><input type="hidden" name="kind" value="appointment"><input type="hidden" name="id" value="<?=(int)$a['id']?>"><label>Enviar comprovante Pix</label><input class="input" type="file" name="proof_file" accept="image/*,.pdf" required><button class="btn btn-primary btn-sm" style="margin-top:8px">Enviar comprovante</button></form><?php endif;?></div><?php elseif(($settings['payment_method']??'')==='link'&&!empty($settings['payment_link'])):?><a class="btn btn-primary btn-sm" target="_blank" rel="noopener" href="<?=e($settings['payment_link'])?>">Acessar link de pagamento</a><?php else:?>Pagamento definido diretamente com a clínica.<?php endif;?></div><?php endif;?>
<?php if((int)$settings['allow_reschedule']&&!empty($a['professional_id'])):$p=['id'=>$a['professional_id'],'duration_minutes'=>$a['duration_minutes']?:30];$slots=clinic_patient_slots_for_professional($p,30);?><details style="margin-top:12px"><summary class="btn btn-secondary btn-sm">Reagendar</summary><form method="post" action="actions.php" style="margin-top:12px"><?=csrf_field()?><input type="hidden" name="action" value="clinic_patient_reschedule"><input type="hidden" name="id" value="<?=$a['id']?>"><div class="form-group"><label>Novo horário</label><select name="slot_choice" required><?php foreach($slots as $sl):?><option value="<?=e($sl['date'].'|'.$sl['time'])?>"><?=e(date('d/m/Y',strtotime($sl['date'])).' às '.$sl['time'])?></option><?php endforeach;?></select></div><button class="btn btn-primary btn-sm">Confirmar reagendamento</button></form></details><?php endif;?>
<?php if($a['appointment_date']===date('Y-m-d')&&empty($a['checkin_at'])&&!in_array($a['status'],['completed','cancelled','no_show'],true)):?><form method="post" action="actions.php" data-clinic-checkin style="margin-top:12px"><?=csrf_field()?><input type="hidden" name="action" value="clinic_patient_checkin"><input type="hidden" name="id" value="<?=(int)$a['id']?>"><input type="hidden" name="latitude" data-checkin-lat><input type="hidden" name="longitude" data-checkin-lng><button type="button" class="btn btn-accent btn-sm" data-checkin-button>📍 Confirmar que estou na clínica</button><small data-checkin-status style="display:block;margin-top:6px"></small></form><?php elseif(!empty($a['checkin_at'])):?><div class="notice" style="margin-top:12px">📍 Presença confirmada às <?=e(date('H:i',strtotime($a['checkin_at'])))?>, a <?=round((float)($a['checkin_distance_m']??0))?> m da clínica.</div><?php endif;?><form method="post" action="actions.php" style="margin-top:12px"><?=csrf_field()?><input type="hidden" name="action" value="clinic_patient_cancel"><input type="hidden" name="id" value="<?=$a['id']?>"><button class="btn btn-danger btn-sm" data-confirm="Cancelar esta consulta?">Cancelar consulta</button></form></article>
<?php endforeach;?></div></section>

<section class="panel" id="myExams"><div class="panel-header"><div><h2>🧪 Meus exames</h2><p>Solicitações, agendamentos, preparo e resultados liberados.</p></div></div><div class="clinic-appointment-cards"><?php if(!$examRequests):?><div class="empty-state"><strong>Nenhum exame solicitado</strong></div><?php endif;?><?php foreach($examRequests as $ex):?><article class="item-card"><div class="item-body"><h3><?=e($ex['exam_name']?:'Exame')?> • <?=e($ex['clinic_name'])?></h3><p><?=status_badge($ex['status'])?><?php if(!empty($ex['scheduled_date'])):?> • <?=e(date('d/m/Y',strtotime($ex['scheduled_date'])))?><?=(($ex['booking_mode']??'time')==='arrival')?' • ordem de chegada #'.(int)($ex['arrival_order']??0):(!empty($ex['scheduled_time'])?' • '.e(substr((string)$ex['scheduled_time'],0,5)):'')?><?php endif;?></p><div class="item-meta"><span><strong>Valor:</strong> <?=money($ex['price'])?></span><span><strong>Dias:</strong> <?=e($ex['available_days']?:'—')?></span><span><strong>Horários:</strong> <?=e($ex['available_hours']?:'—')?></span></div><?php if(!empty($ex['preparation_instructions'])):?><div class="notice"><strong>Preparo:</strong> <?=nl2br(e($ex['preparation_instructions']))?></div><?php endif;?><?php if(!empty($ex['result_notes'])):?><div class="notice"><strong>Resultado / observação:</strong> <?=nl2br(e($ex['result_notes']))?></div><?php endif;?><?php if(!empty($ex['result_path'])):?><a class="btn btn-primary btn-sm" target="_blank" href="<?=e(media_url($ex['result_path']))?>">Acessar Resultado</a><?php endif;?><?php $exSettings=clinic_settings((int)$ex['company_id']);if((($ex['payment_method']??$exSettings['payment_method']??'')==='pix')&&($ex['payment_status']??'pending')!=='paid'&&!empty($exSettings['pix_key'])):?><div class="notice" style="margin-top:10px"><strong>Pagamento Pix</strong><br><code><?=e($exSettings['pix_key'])?></code> <button type="button" class="btn btn-secondary btn-sm" data-copy-text="<?=e($exSettings['pix_key'])?>" data-show-payment-proof="#examProof<?=(int)$ex['id']?>">Copiar Pix</button><div id="examProof<?=(int)$ex['id']?>" style="margin-top:10px"<?=empty($ex['payment_proof'])?' hidden':''?>><?php if(!empty($ex['payment_proof'])):?><a class="btn btn-secondary btn-sm" target="_blank" href="<?=e(media_url($ex['payment_proof']))?>">Ver comprovante enviado</a><?php else:?><form method="post" action="actions.php" enctype="multipart/form-data"><?=csrf_field()?><input type="hidden" name="action" value="clinic_patient_upload_payment_proof"><input type="hidden" name="kind" value="exam"><input type="hidden" name="id" value="<?=(int)$ex['id']?>"><input class="input" type="file" name="proof_file" accept="image/*,.pdf" required><button class="btn btn-primary btn-sm" style="margin-top:8px">Enviar comprovante</button></form><?php endif;?></div></div><?php endif;?><?php if(!in_array($ex['status'],['completed','cancelled'],true)):?><form method="post" action="actions.php" style="margin-top:10px"><?=csrf_field()?><input type="hidden" name="action" value="clinic_patient_cancel_exam"><input type="hidden" name="id" value="<?=(int)$ex['id']?>"><button class="btn btn-danger btn-sm" data-confirm="Cancelar este exame? A vaga será liberada.">Cancelar exame</button></form><?php endif;?></div></article><?php endforeach;?></div></section>

<section class="panel" id="appointmentHistory"><div class="panel-header"><div><h2>Histórico de consultas</h2><p>Consultas concluídas, canceladas e avaliações.</p></div></div><div class="clinic-appointment-cards"><?php if(!$history):?><div class="empty-state"><strong>Sem histórico</strong></div><?php endif;?><?php foreach($history as $a):?><article class="item-card"><div class="item-body"><h3><?=e($a['clinic_name'])?></h3><p><?=e(date('d/m/Y',strtotime($a['appointment_date'])).' '.$a['appointment_time'].' • '.($a['specialty_name']?:'Consulta'))?></p><div class="item-meta"><span><?=status_badge($a['status'])?></span><span><?=e($a['professional_name']?:'—')?></span></div><div class="actions"><a class="btn btn-secondary btn-sm" target="_blank" href="clinic_receipt.php?id=<?=$a['id']?>&download=1">Baixar PNG</a></div><?php if($a['status']==='completed'):?><details style="margin-top:12px"><summary class="btn btn-secondary btn-sm">⭐ Avaliar atendimento</summary><form method="post" action="actions.php" style="margin-top:12px"><?=csrf_field()?><input type="hidden" name="action" value="save_clinic_review"><input type="hidden" name="appointment_id" value="<?=$a['id']?>"><div class="form-grid"><div class="form-group"><label>Clínica</label><select name="clinic_rating"><?php for($i=5;$i>=1;$i--):?><option value="<?=$i?>"><?=$i?> estrela(s)</option><?php endfor;?></select></div><div class="form-group"><label>Profissional</label><select name="professional_rating"><?php for($i=5;$i>=1;$i--):?><option value="<?=$i?>"><?=$i?> estrela(s)</option><?php endfor;?></select></div><div class="form-group full"><label>Comentário</label><textarea name="comment"></textarea></div></div><button class="btn btn-primary btn-sm">Publicar avaliação</button></form></details><?php endif;?></div></article><?php endforeach;?></div></section>

<script>
document.querySelectorAll('[data-clinic-slot-value]').forEach(btn=>btn.addEventListener('click',()=>{const modal=document.querySelector(btn.dataset.modalOpen);if(!modal)return;const slot=modal.querySelector('[data-clinic-modal-slot]');const specialty=modal.querySelector('[data-clinic-modal-specialty]');if(specialty&&btn.dataset.clinicSpecialtyValue){specialty.value=btn.dataset.clinicSpecialtyValue;specialty.dispatchEvent(new Event('change'));}if(slot)slot.value=btn.dataset.clinicSlotValue;}));
document.querySelectorAll('[data-clinic-modal-specialty]').forEach(sel=>{const form=sel.closest('form'),slot=form?.querySelector('[data-clinic-modal-slot]');const sync=()=>{if(!slot)return;const id=sel.value;Array.from(slot.options).forEach((o,i)=>{if(i===0)return;o.hidden=!!id&&o.dataset.specialty!==id;});if(slot.selectedOptions[0]?.hidden)slot.value='';};sel.addEventListener('change',sync);sync();});
document.querySelectorAll('[data-exam-date]').forEach(dateSel=>{const form=dateSel.closest('[data-exam-booking-form]'),timeSel=form?.querySelector('[data-exam-time]');if(!timeSel)return;const sync=()=>{const raw=dateSel.selectedOptions[0]?.dataset.times||'';const times=raw.split(',').map(x=>x.trim()).filter(Boolean);timeSel.innerHTML='<option value="">'+(dateSel.value?'Escolha um horário disponível':'Escolha primeiro a data')+'</option>';times.forEach(t=>{const o=document.createElement('option');o.value=t;o.textContent=t;timeSel.appendChild(o);});timeSel.disabled=!dateSel.value||!times.length;};dateSel.addEventListener('change',sync);sync();});
document.querySelectorAll('[data-clinic-specialty-select]').forEach(sel=>{const form=sel.closest('form'),slot=form?.querySelector('[data-clinic-slot-select]'),arrival=form?.querySelector('[data-clinic-arrival-professional]');const applySelect=el=>{if(!el)return;const id=sel.value;Array.from(el.options).forEach((o,i)=>{if(i===0)return;o.hidden=!!id&&o.dataset.specialty!==id&&o.dataset.specialty!=='*';});if(el.selectedOptions[0]?.hidden)el.value='';};const apply=()=>{applySelect(slot);applySelect(arrival);};sel.addEventListener('change',apply);apply();});
document.querySelectorAll('[data-patient-booking-mode]').forEach(sel=>{const form=sel.closest('form'),time=form.querySelector('[data-time-booking]'),slot=form.querySelector('[data-clinic-slot-select]'),arrivalBoxes=form.querySelectorAll('[data-arrival-booking]'),pro=form.querySelector('[data-clinic-arrival-professional]'),date=form.querySelector('input[name="appointment_date"]');const sync=()=>{const a=sel.value==='arrival';if(time)time.hidden=a;arrivalBoxes.forEach(x=>x.hidden=!a);if(slot)slot.required=!a;if(pro)pro.required=a;if(date)date.required=a;};sel.addEventListener('change',sync);sync();});
document.querySelectorAll('[data-copy-text]').forEach(b=>b.addEventListener('click',async()=>{try{await navigator.clipboard.writeText(b.dataset.copyText||'');const old=b.textContent;b.textContent='Copiado ✓';setTimeout(()=>b.textContent=old,1600);}catch(e){prompt('Copie o Pix:',b.dataset.copyText||'');}const target=b.dataset.showPaymentProof;if(target){const box=document.querySelector(target);if(box)box.hidden=false;}}));
document.querySelectorAll('[data-clinic-checkin]').forEach(form=>{const btn=form.querySelector('[data-checkin-button]'),st=form.querySelector('[data-checkin-status]');btn?.addEventListener('click',()=>{if(!navigator.geolocation){st.textContent='Seu aparelho não disponibilizou localização.';return;}btn.disabled=true;st.textContent='Confirmando sua localização…';navigator.geolocation.getCurrentPosition(pos=>{form.querySelector('[data-checkin-lat]').value=pos.coords.latitude;form.querySelector('[data-checkin-lng]').value=pos.coords.longitude;form.submit();},()=>{btn.disabled=false;st.textContent='Não foi possível acessar sua localização. Autorize o GPS e tente novamente.';},{enableHighAccuracy:true,timeout:12000,maximumAge:10000});});});
</script>
