<?php
$u=current_user();$uid=(int)($u['id']??0);$focusClinic=(int)request('clinic',0);
$clinicRows=db()->query("SELECT c.*,ou.public_id owner_public_id,
    COALESCE((SELECT ROUND(AVG(r.rating),1) FROM reviews r WHERE r.target_type='company' AND r.target_id=c.id AND r.status='published'),0) rating
    FROM companies c
    LEFT JOIN users ou ON ou.id=c.owner_user_id
    LEFT JOIN segments s ON s.slug=c.type
    WHERE c.status='active' AND (
      lower(COALESCE(c.type,''))='clinic' OR lower(COALESCE(c.sector,''))='clinic'
      OR lower(COALESCE(c.type,'')) LIKE '%clinic%' OR lower(COALESCE(c.type,'')) LIKE '%clínic%'
      OR lower(COALESCE(c.sector,'')) LIKE '%clinic%' OR lower(COALESCE(c.sector,'')) LIKE '%clínic%'
      OR lower(COALESCE(s.name,'')) LIKE '%clínic%' OR lower(COALESCE(s.name,'')) LIKE '%clinic%'
      OR lower(COALESCE(ou.segment_slug,'')) LIKE '%clinic%' OR lower(COALESCE(ou.segment_slug,'')) LIKE '%clínic%'
    ) ORDER BY c.premium DESC,c.verified DESC,c.name")->fetchAll();
// Segurança extra: uma distribuidora de gás nunca deve entrar no mapa/área de Clínicas,
// mesmo que tenha dados antigos de segmento ou vínculo reaproveitados no cadastro.
$clinicRows=array_values(array_filter($clinicRows,static function($row){$id=(int)($row['id']??0);return $id>0&&company_is_clinic($id)&&!company_is_gas($id);}));
$mapClinics=[];$clinicDetails=[];
foreach($clinicRows as $clinic){
    $cid=(int)$clinic['id'];$settings=clinic_settings($cid);
    $q=db()->prepare("SELECT * FROM clinic_specialties WHERE company_id=? AND status='active' ORDER BY name");$q->execute([$cid]);$specialties=$q->fetchAll();
    $q=db()->prepare("SELECT p.*,s.name specialty_name,s.price specialty_price,s.duration_minutes,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' ORDER BY p.name");$q->execute([$cid]);$professionals=$q->fetchAll();
    $clinicDetails[$cid]=['settings'=>$settings,'specialties'=>$specialties,'professionals'=>$professionals];
    $address=trim((string)$clinic['address'].' '.(string)$clinic['address_number'].' '.(string)$clinic['city'].'/'.(string)$clinic['state']);
    $mapClinics[]=['id'=>$cid,'name'=>$clinic['name'],'sector'=>'clinic','sector_label'=>'Clínica','icon'=>'🏥','address'=>$address,'lat'=>$clinic['latitude'],'lng'=>$clinic['longitude'],'phone'=>$clinic['phone'],'logo'=>media_url($clinic['logo'])];
}
?>
<section class="page-intro"><div><span class="mini-label">🏥 SAÚDE PERTO DE VOCÊ</span><h2>Clínicas próximas</h2><p>Escolha a clínica, veja funcionamento, especialidades, valores, profissionais e horários disponíveis.</p></div><div class="actions"><a class="btn btn-secondary" href="dashboard.php?page=home">← Início</a><?php if($clinicRows):?><button class="btn btn-primary" type="button" data-locate-user data-auto-locate>📍 Usar minha localização</button><?php endif;?></div></section>

<?php if(!$clinicRows):?><section class="panel"><div class="empty-state"><strong>Nenhuma clínica disponível</strong>As clínicas aparecem aqui quando uma empresa ativa está cadastrada no segmento Clínicas e Saúde.</div></section><?php else:?>
<section class="panel map-filter-panel"><div class="form-group"><label>Pesquisar clínica ou ID</label><input class="input" data-company-search placeholder="Nome da clínica ou LXU-..."></div><div class="notice" data-nearby-status>Localizando clínicas próximas...</div></section>

<div class="map-layout clinic-map-layout" data-entity-label="clínica" data-radius-km="80" data-user-city="<?=e(strtolower((string)($u['city']??'')))?>" data-user-lat="<?=e($u['home_lat']??'')?>" data-user-lng="<?=e($u['home_lng']??'')?>">
  <section class="company-near-list clinic-near-list" data-company-list>
  <?php foreach($clinicRows as $clinic):$cid=(int)$clinic['id'];$d=$clinicDetails[$cid];$settings=$d['settings'];$specialties=$d['specialties'];$pros=$d['professionals'];$clinicAddress=trim((string)$clinic['address'].' '.(string)$clinic['address_number'].' '.(string)$clinic['city'].'/'.(string)$clinic['state']);$specNames=implode(' • ',array_column($specialties,'name'));$member=$uid?clinic_patient_for_user($uid,$cid):null;?>
    <article class="near-card clinic-near-card<?=$focusClinic===$cid?' clinic-card-focus':''?>" id="clinic-card-<?=$cid?>" data-company-card data-company-id="<?=$cid?>" data-name="<?=e(strtolower($clinic['name'].' '.$clinic['description'].' '.$clinic['city'].' '.$clinicAddress.' '.$specNames.' '.($clinic['owner_public_id']??'').' #'.$cid))?>" data-sector="clinic" data-city="<?=e(strtolower((string)$clinic['city']))?>" data-lat="<?=e($clinic['latitude'])?>" data-lng="<?=e($clinic['longitude'])?>">
      <div class="near-logo"><?php if($clinic['logo']):?><img src="<?=e(media_url($clinic['logo']))?>" alt=""><?php else:?>🏥<?php endif;?></div>
      <div class="clinic-near-main"><div class="near-title"><button class="clinic-map-focus" type="button" data-map-focus-id="<?=$cid?>"><strong><?=e($clinic['name'])?></strong></button><?php if(!empty($clinic['verified'])):?><span>✓ Verificada</span><?php endif;?></div>
        <small>🏥 Clínica • <?=e($clinic['city'].($clinic['state']?'/'.$clinic['state']:''))?></small><?php if($clinic['owner_public_id']):?><small style="display:block">ID: <?=e($clinic['owner_public_id'])?></small><?php endif;?>
        <?php if((float)$clinic['rating']>0):?><div class="market-rating" style="margin:8px 0 0"><?=stars_html((float)$clinic['rating'])?> <strong><?=number_format((float)$clinic['rating'],1,',','.')?></strong></div><?php endif;?>
        <div class="notice clinic-opening-hours"><strong>🕒 Funcionamento</strong><br><?=e($settings['opening_hours']?:'Horário não informado pela clínica.')?></div>
        <?php if($specNames):?><p class="clinic-specialties"><strong>Especialidades:</strong> <?=e(short_text($specNames,180))?></p><?php endif;?>
        <p><?=e(short_text($clinicAddress?:$clinic['description'],120))?></p>
        <div class="near-actions"><button class="btn btn-primary btn-sm" type="button" data-modal-open="#clinicInfo<?=$cid?>">Ver atendimento</button><button class="btn btn-secondary btn-sm" type="button" data-map-focus-id="<?=$cid?>">📍 Ver no mapa</button><a class="btn btn-secondary btn-sm" target="_blank" rel="noopener" href="<?=e(google_directions_link($clinicAddress,$clinic['latitude'],$clinic['longitude']))?>">Como chegar</a><?php if($clinic['phone']):?><a class="btn btn-accent btn-sm" target="_blank" rel="noopener" href="<?=e(whatsapp_url($clinic['phone'],'Olá, encontrei sua clínica na LinkExpress. Gostaria de informações sobre atendimento e agendamento.'))?>">WhatsApp</a><?php endif;?><span class="distance-label" data-distance-label></span></div>
      </div>
    </article>
    <div class="modal" id="clinicInfo<?=$cid?>"><div class="modal-card clinic-info-modal"><div class="modal-head"><div><h2><?=e($clinic['name'])?></h2><small><?=e($settings['opening_hours']?:'Horário não informado')?></small></div><button class="close-btn" data-modal-close>×</button></div>
      <?php if(!$member && $uid && !is_admin()):?><div class="notice"><strong>Primeiro atendimento nesta clínica?</strong><br>Cadastre sua conta como paciente usando o mesmo usuário da plataforma.<form method="post" action="actions.php" style="margin-top:10px"><?=csrf_field()?><input type="hidden" name="action" value="clinic_patient_join"><input type="hidden" name="company_id" value="<?=$cid?>"><button class="btn btn-primary btn-sm">Cadastrar como paciente</button></form></div><?php endif;?>
      <div class="clinic-specialty-grid"><?php if(!$specialties):?><div class="empty-state"><strong>Nenhuma especialidade publicada</strong></div><?php endif;?><?php foreach($specialties as $sp):?><article class="clinic-specialty-card"><h3><?=e($sp['name'])?></h3><p><?=e($sp['description'])?></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="clinic-professional-list"><?php $found=0;foreach($pros as $pr):if((int)($pr['specialty_id']??0)!==(int)$sp['id'] && !empty($pr['specialty_id']))continue;$found++;?><div class="clinic-professional-row"><div><strong><?=e($pr['name'])?></strong><?php if((int)($pr['professional_rating_count']??0)>0):?><div class="market-rating" style="margin:4px 0"><?=stars_html((float)$pr['professional_rating'])?> <strong><?=number_format((float)$pr['professional_rating'],1,',','.')?></strong> <small>(<?=(int)$pr['professional_rating_count']?> avaliação(ões))</small></div><?php else:?><small style="display:block">☆ Ainda sem avaliações</small><?php endif;?><small><?=e(clinic_professional_schedule_text((int)$pr['id'])?:'Agenda ainda não informada')?></small></div><?php if(!empty($pr['share_whatsapp'])&&!empty($pr['phone'])):?><a class="btn btn-accent btn-sm" target="_blank" href="<?=e(whatsapp_url($pr['phone'],'Olá, encontrei seu perfil profissional na LinkExpress.'))?>">WhatsApp</a><?php endif;?></div><?php endforeach;?><?php if(!$found):?><small class="muted">Nenhum profissional vinculado no momento.</small><?php endif;?></div></article><?php endforeach;?></div>
      <div class="actions" style="margin-top:16px"><?php if($member):?><a class="btn btn-primary" href="dashboard.php?page=clinic_patient#myClinics">Agendar pela Minha Saúde</a><?php elseif($uid):?><span class="muted">Cadastre-se como paciente para liberar o agendamento online.</span><?php else:?><a class="btn btn-primary" href="login.php">Entrar para agendar</a><?php endif;?></div>
    </div></div>
  <?php endforeach;?></section>

  <section class="panel map-panel clinic-map-panel"><div id="companyMap" class="company-map clinic-company-map" aria-label="Mapa de clínicas próximas" data-map-companies='<?=e(json_encode($mapClinics,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES))?>'><div class="map-loading"><span>🗺️</span><strong>Carregando mapa das clínicas...</strong><small>A lista de clínicas permanece disponível.</small></div></div><p class="map-help">👤 Você • 🏥 Clínica. Toque no nome da clínica ou em “Ver no mapa” para centralizar a localização.</p></section>
</div>
<?php endif;?>
<?php if($focusClinic>0):?><script>setTimeout(()=>document.querySelector('[data-map-focus-id="<?=$focusClinic?>"]')?.click(),900);</script><?php endif;?>
