<?php
$u=current_user();
$city=trim(request('city',$u['city']?:setting('platform_city')));
$state=strtoupper(trim(request('state',$u['state']?:setting('platform_state'))));
$q=trim(request('q',''));
$selected=(int)request('org',0);
$sql="SELECT * FROM public_orgs WHERE ".(is_admin()?"1=1":"status='active'");$args=[];
if($q!==''){
    $sql.=" AND (name LIKE ? OR category LIKE ? OR address LIKE ? OR city LIKE ?)";$like='%'.$q.'%';$args=[$like,$like,$like,$like];
    if($city!==''){$sql.=" ORDER BY CASE WHEN lower(city)=lower(?) THEN 0 ELSE 1 END,name";$args[]=$city;}else $sql.=' ORDER BY city,name';
}else{
    $sql.=' AND lower(city)=lower(?)';$args[]=$city;
    if($state!==''){$sql.=' AND upper(state)=upper(?)';$args[]=$state;}
    $sql.=' ORDER BY category,name';
}
$stmt=db()->prepare($sql);$stmt->execute($args);$orgs=$stmt->fetchAll();
$mapOrg=null;if($selected){foreach($orgs as $o)if((int)$o['id']===$selected)$mapOrg=$o;}if(!$mapOrg&&$orgs)$mapOrg=$orgs[0];
function render_public_org_form(array $item): void { ?>
<form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="save_public_org"><input type="hidden" name="return_page" value="public_orgs"><input type="hidden" name="id" value="<?= (int)($item['id']??0) ?>">
<div class="form-grid"><div class="form-group"><label>Nome</label><input class="input" name="name" value="<?= e($item['name']??'') ?>" required></div><div class="form-group"><label>Categoria</label><input class="input" name="category" value="<?= e($item['category']??'') ?>" placeholder="Prefeitura, hospital, fórum..."></div><div class="form-group"><label>Cidade</label><input class="input" name="city" value="<?= e($item['city']??'') ?>" required></div><div class="form-group"><label>UF</label><input class="input" name="state" maxlength="2" data-state-mask value="<?= e($item['state']??'') ?>"></div><div class="form-group full"><label>Endereço</label><input class="input" name="address" value="<?= e($item['address']??'') ?>" data-address-autocomplete data-lat-field="latitude" data-lng-field="longitude" required><input type="hidden" name="latitude" value="<?= e($item['latitude']??'') ?>"><input type="hidden" name="longitude" value="<?= e($item['longitude']??'') ?>"></div><div class="form-group"><label>Abre</label><input class="input" type="time" name="opens_at" value="<?= e($item['opens_at']??'') ?>"></div><div class="form-group"><label>Fecha</label><input class="input" type="time" name="closes_at" value="<?= e($item['closes_at']??'') ?>"></div><div class="form-group"><label>Telefone</label><input class="input" name="phone" data-phone-mask value="<?= e($item['phone']??'') ?>"></div><div class="form-group"><label>Site</label><input class="input" name="website" value="<?= e($item['website']??'') ?>"></div><div class="form-group"><label>Status</label><select name="status"><option value="active"<?= selected($item['status']??'active','active') ?>>Ativo</option><option value="inactive"<?= selected($item['status']??'active','inactive') ?>>Oculto</option></select></div></div><div class="form-actions"><button class="btn btn-primary">Salvar órgão</button></div></form>
<?php }
?>
<section class="page-intro"><div><span class="mini-label">UTILIDADE PÚBLICA</span><h2>Órgãos públicos próximos</h2><p>Por padrão aparecem apenas os órgãos do seu município. Pesquise outro município quando precisar.</p></div><?php if(is_admin()):?><button class="btn btn-primary" data-modal-open="#orgModal">+ Cadastrar órgão</button><?php endif;?></section>
<form class="panel filter-bar" method="get" data-public-org-filter><input type="hidden" name="page" value="public_orgs"><input type="hidden" name="located" value="<?= e(request('located','')) ?>"><div class="form-group"><label>Nome ou categoria</label><input class="input" name="q" value="<?= e($q) ?>" placeholder="Prefeitura, hospital, fórum..."></div><div class="form-group"><label>Município</label><input class="input" name="city" value="<?= e($city) ?>"></div><div class="form-group"><label>UF</label><input class="input" name="state" maxlength="2" data-state-mask value="<?= e($state) ?>"></div><div class="actions"><button class="btn btn-secondary" type="button" data-public-org-locate>📍 Usar minha localização</button><button class="btn btn-primary">Pesquisar</button></div></form>
<div class="grid-2"><section class="panel"><div class="panel-header"><div><h3>Resultados</h3><p><?= count($orgs) ?> local(is) encontrado(s).</p></div></div><div class="activity-list"><?php foreach($orgs as $o):?><div class="activity"><span class="activity-dot"></span><div style="flex:1"><p><strong><?= e($o['name']) ?></strong> <?php if(is_admin()):?><?= status_badge($o['status']) ?><?php endif;?></p><small><?= e($o['category']) ?> • <?= e($o['city'].'/'.$o['state']) ?><br><?= e($o['address']) ?><br>Horário: <?= e($o['opens_at']?:'—') ?> às <?= e($o['closes_at']?:'—') ?></small><div class="actions" style="margin-top:8px"><a class="btn btn-secondary btn-sm" href="<?= e(url('dashboard.php?page=public_orgs&city='.rawurlencode($city).'&state='.rawurlencode($state).'&q='.rawurlencode($q).'&org='.(int)$o['id'])) ?>">Ver mapa</a><a class="btn btn-secondary btn-sm" target="_blank" rel="noopener" href="<?= e(maps_link($o['address'],$o['latitude'],$o['longitude'])) ?>">Google Maps</a><a class="btn btn-accent btn-sm" target="_blank" rel="noopener" href="<?= e(waze_link($o['address'],$o['latitude'],$o['longitude'])) ?>">Waze</a><?php if(is_admin()):?><button class="btn btn-secondary btn-sm" type="button" data-modal-open="#orgModal<?= (int)$o['id'] ?>">Editar</button><?php endif;?></div></div><?php if(is_admin()):?><form method="post" action="actions.php" style="margin-top:8px"><?= csrf_field() ?><input type="hidden" name="action" value="delete_public_org"><input type="hidden" name="return_page" value="public_orgs"><input type="hidden" name="id" value="<?= (int)$o['id'] ?>"><button class="btn btn-danger btn-sm" data-confirm="Apagar este órgão público?">Apagar</button></form><?php endif;?></div><?php endforeach;?></div><?php if(!$orgs):?><div class="empty-state"><strong>Nenhum órgão encontrado</strong>O administrador ainda não cadastrou locais para esta cidade.</div><?php endif;?></section>
<section class="panel"><div class="panel-header"><div><h3>Mapa do local</h3><p><?= $mapOrg?e($mapOrg['name']):'Selecione um órgão' ?></p></div></div><?php if($mapOrg):?><iframe title="Mapa" style="width:100%;height:430px;border:0;border-radius:16px" loading="lazy" referrerpolicy="no-referrer-when-downgrade" src="https://www.google.com/maps?q=<?= rawurlencode(($mapOrg['latitude']&&$mapOrg['longitude'])?$mapOrg['latitude'].','.$mapOrg['longitude']:$mapOrg['address'].', '.$mapOrg['city']) ?>&output=embed"></iframe><?php else:?><div class="empty-state"><strong>Mapa indisponível</strong>Faça uma pesquisa.</div><?php endif;?></section></div>
<?php if(is_admin()):?>
<div class="modal" id="orgModal"><div class="modal-card"><div class="modal-head"><h2>Novo órgão público</h2><button class="close-btn" data-modal-close>×</button></div><?php render_public_org_form(['id'=>0,'status'=>'active']); ?></div></div>
<?php foreach($orgs as $o):?><div class="modal" id="orgModal<?= (int)$o['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Editar órgão público</h2><button class="close-btn" data-modal-close>×</button></div><?php render_public_org_form($o); ?></div></div><?php endforeach;?>
<?php endif;?>
