<?php
$u=current_user();$isAdmin=is_admin();$isSuper=is_super_admin();$reportedId=(int)request('reported_id',0);$scopeCompany=(int)request('reported_company_id',0);$scopeProfessional=(int)request('reported_clinic_professional_id',0);$target=null;
if($reportedId>0&&$reportedId!==(int)$u['id']){$q=db()->prepare("SELECT id,name,avatar,role,public_id,status FROM users WHERE id=? AND status<>'blocked'");$q->execute([$reportedId]);$target=$q->fetch();}
if($isAdmin){$filter=request('status','');$params=[];$where=[];if(!$isSuper)$where[]='COALESCE(r.reported_company_id,0)=0 AND COALESCE(r.reported_clinic_professional_id,0)=0';if($filter!==''){$where[]='r.status=?';$params[]=$filter;}$sql="SELECT r.*,ru.name reporter_current,tu.name reported_current,tu.avatar reported_avatar,tu.status reported_account_status,c.name reported_company_name,cp.name reported_professional_name FROM user_reports r LEFT JOIN users ru ON ru.id=r.reporter_user_id LEFT JOIN users tu ON tu.id=r.reported_user_id LEFT JOIN companies c ON c.id=r.reported_company_id LEFT JOIN clinic_professionals cp ON cp.id=r.reported_clinic_professional_id";if($where)$sql.=' WHERE '.implode(' AND ',$where);$sql.=' ORDER BY CASE r.status WHEN "pending" THEN 0 WHEN "reviewed" THEN 1 WHEN "actioned" THEN 2 ELSE 3 END,r.id DESC';$q=db()->prepare($sql);$q->execute($params);$reports=$q->fetchAll();}
else{$q=db()->prepare('SELECT r.*,tu.name reported_current,tu.avatar reported_avatar,c.name reported_company_name,cp.name reported_professional_name FROM user_reports r LEFT JOIN users tu ON tu.id=r.reported_user_id LEFT JOIN companies c ON c.id=r.reported_company_id LEFT JOIN clinic_professionals cp ON cp.id=r.reported_clinic_professional_id WHERE r.reporter_user_id=? ORDER BY r.id DESC');$q->execute([(int)$u['id']]);$reports=$q->fetchAll();}
?>
<section class="page-intro"><div><span class="mini-label">SEGURANÇA E CONFIANÇA</span><h2><?=$isAdmin?'Denúncias recebidas':'Denunciar usuário / instituição'?></h2><p><?=$isSuper?'Denúncias de clínicas liberam acesso temporário aos dados internos somente enquanto a análise estiver aberta.':($isAdmin?'Denúncias clínicas não ficam disponíveis para Administradores.':'Envie situações de abuso, fraude, cobrança indevida ou problema no atendimento.')?></p></div></section>
<?php if(!$isAdmin):?><section class="panel"><div class="panel-header"><div><h3>Nova denúncia</h3><p>A análise fica com o Administrador Sênior quando envolver clínica ou profissional de clínica.</p></div></div><?php if($target):?><div class="profile-hero" style="margin-bottom:18px"><?=avatar_html($target)?><div><h3><?=e($target['name'])?></h3><small><?=e(public_user_id($target))?> • <?=e(role_label($target['role']))?></small></div></div><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="submit_user_report"><input type="hidden" name="reported_user_id" value="<?=(int)$target['id']?>"><input type="hidden" name="reported_company_id" value="<?=$scopeCompany?>"><input type="hidden" name="reported_clinic_professional_id" value="<?=$scopeProfessional?>"><div class="form-grid"><div class="form-group"><label>Motivo</label><select name="reason" required><option value="">Selecione</option><?php foreach(['Comportamento inadequado','Fraude ou cobrança indevida','Problema no serviço','Spam ou abuso','Perfil ou informação falsa','Outro'] as $reason):?><option><?=e($reason)?></option><?php endforeach;?></select></div><div class="form-group full"><label>Conte o que aconteceu</label><textarea name="description" rows="5" required></textarea></div></div><button class="btn btn-danger">🚩 Enviar denúncia</button></form><?php else:?><div class="notice">Abra o perfil, contato ou uma clínica e toque em <strong>Denunciar</strong> para selecionar o alvo correto.</div><?php endif;?></section><?php endif;?>
<section class="panel"><div class="panel-header"><div><h3><?=$isAdmin?'Denúncias disponíveis':'Minhas denúncias'?></h3><p><?=count($reports)?> registro(s).</p></div><?php if($isAdmin):?><form method="get"><input type="hidden" name="page" value="reports"><select name="status" data-auto-submit><option value="">Todas</option><?php foreach(['pending'=>'Pendentes','reviewed'=>'Em análise','actioned'=>'Providência tomada','finalized'=>'Finalizadas','dismissed'=>'Arquivadas'] as $k=>$v):?><option value="<?=$k?>"<?=selected($filter,$k)?>><?=$v?></option><?php endforeach;?></select></form><?php endif;?></div>
<?php if(!$reports):?><div class="empty-state"><strong>Nenhuma denúncia</strong></div><?php endif;?><div class="activity-list"><?php foreach($reports as $r):$reportedName=$r['reported_current']?:$r['reported_name_snapshot'];$reporterName=$r['reporter_current']??$r['reporter_name_snapshot'];$clinicReport=(int)($r['reported_company_id']??0)>0||(int)($r['reported_clinic_professional_id']??0)>0;?><div class="activity report-item"><span class="activity-dot"></span><div style="flex:1"><p><strong><?=$isAdmin?e($reporterName).' → ':''?><?=e($reportedName)?></strong> <?=status_badge($r['status'])?><?php if($clinicReport):?> <span class="status status-pending">🏥 Clínica</span><?php endif;?></p><?php if($clinicReport):?><small style="display:block">Instituição: <?=e($r['reported_company_name']?:'—')?><?=!empty($r['reported_professional_name'])?' • Profissional: '.e($r['reported_professional_name']):''?></small><?php endif;?><small><strong><?=e($r['reason'])?></strong> • <?=e(date('d/m/Y H:i',strtotime($r['created_at'])))?></small><p style="margin-top:8px"><?=nl2br(e($r['description']?:'Sem descrição.'))?></p><?php if(!empty($r['admin_notes'])):?><div class="notice"><strong>Observação:</strong> <?=e($r['admin_notes'])?></div><?php endif;?>
<?php if($isSuper&&$clinicReport&&!in_array($r['status'],['finalized','dismissed'],true)):?><div class="actions" style="margin:10px 0"><a class="btn btn-danger btn-sm" href="dashboard.php?page=clinic&clinic_company=<?=(int)$r['reported_company_id']?>">🔐 Ver dados da clínica durante a análise</a></div><?php endif;?>
<?php if($isAdmin):?><form method="post" action="actions.php" style="margin-top:12px"><?=csrf_field()?><input type="hidden" name="action" value="review_user_report"><input type="hidden" name="id" value="<?=(int)$r['id']?>"><div class="form-grid"><div class="form-group"><label>Situação</label><select name="status"><option value="reviewed"<?=selected($r['status'],'reviewed')?>>Em análise</option><option value="actioned"<?=selected($r['status'],'actioned')?>>Providência tomada</option><option value="finalized"<?=selected($r['status'],'finalized')?>>Finalizada</option><option value="dismissed"<?=selected($r['status'],'dismissed')?>>Arquivada</option></select></div><div class="form-group full"><label>Observação administrativa</label><textarea name="admin_notes" rows="2"><?=e($r['admin_notes']??'')?></textarea></div><?php if((int)($r['reported_user_id']??0)>0):?><label class="checkbox-row"><input type="checkbox" name="block_user" value="1"> Bloquear conta denunciada</label><?php endif;?></div><button class="btn btn-primary btn-sm">Salvar análise</button></form><?php $delState=moderation_deletion_approval_state('user_report',(int)$r['id'],(int)$u['id']);?><form method="post" action="actions.php" style="margin-top:8px"><?=csrf_field()?><input type="hidden" name="action" value="delete_user_report"><input type="hidden" name="id" value="<?=(int)$r['id']?>"><button class="btn btn-danger btn-sm" data-confirm="<?= $isSuper?'Apagar definitivamente esta denúncia?':'Registrar sua confirmação? A exclusão exige dois Administradores.' ?>"><?= $isSuper?'Apagar registro':'Confirmar exclusão ('.(int)$delState['count'].'/2)' ?></button></form><?php endif;?></div></div><?php endforeach;?></div></section>
