<?php
$u=current_user();
// Nem toda conta ligada a uma empresa possui users.company_id preenchido. Resolve também
// por proprietário/vínculo para que a reputação pública não apareça como 0,0 para essas contas.
$companyId=resolve_company_id_for_user($u);
$where='1=0';$args=[];$reviewScope='public';
if(is_admin()){
  $where='1=1';
  $reviewScope='admin';
}elseif($companyId>0){
  $where="r.target_type='company' AND r.target_id=?";
  $args=[$companyId];
  $reviewScope='company';
}elseif(is_role('service_provider')){
  $where="r.target_type='service_provider' AND r.target_id=?";
  $args=[(int)$u['id']];
  $reviewScope='provider';
}
$sql="SELECT r.*,u.name reviewer_name,u.username reviewer_username,u.public_id reviewer_public_id FROM reviews r LEFT JOIN users u ON u.id=r.reviewer_id WHERE $where ORDER BY r.created_at DESC";
$stmt=db()->prepare($sql);$stmt->execute($args);$reviews=$stmt->fetchAll();

$rankings=db()->query("SELECT c.*,COALESCE(AVG(CASE WHEN r.status='published' THEN r.rating END),0) rating_avg,COUNT(CASE WHEN r.status='published' THEN r.id END) rating_count FROM companies c LEFT JOIN reviews r ON r.target_type='company' AND r.target_id=c.id WHERE c.status='active' GROUP BY c.id ORDER BY rating_avg DESC,rating_count DESC,c.name ASC LIMIT 30")->fetchAll();

// Média pública das empresas: igual para qualquer perfil e calculada somente com avaliações publicadas.
$companyRatingStats=db()->query("SELECT COALESCE(AVG(r.rating),0) rating_avg,COUNT(r.id) rating_count FROM reviews r JOIN companies c ON c.id=r.target_id AND c.status='active' WHERE r.target_type='company' AND r.status='published'")->fetch()?:['rating_avg'=>0,'rating_count'=>0];

$ownRatingStats=['rating_avg'=>0,'rating_count'=>0];
if($reviewScope==='company' && $companyId>0){
  $st=db()->prepare("SELECT COALESCE(AVG(r.rating),0) rating_avg,COUNT(r.id) rating_count FROM reviews r WHERE r.target_type='company' AND r.target_id=? AND r.status='published'");
  $st->execute([$companyId]);
  $ownRatingStats=$st->fetch()?:$ownRatingStats;
}elseif($reviewScope==='provider'){
  $st=db()->prepare("SELECT COALESCE(AVG(r.rating),0) rating_avg,COUNT(r.id) rating_count FROM reviews r WHERE r.target_type='service_provider' AND r.target_id=? AND r.status='published'");
  $st->execute([(int)$u['id']]);
  $ownRatingStats=$st->fetch()?:$ownRatingStats;
}
?>
<div class="page-intro"><div><span class="mini-label">REPUTAÇÃO E DESTAQUE</span><h2>Marketplace LinkExpress</h2><p>Ranking, avaliações reais, selos de confiança e desempenho das empresas.</p></div><a class="btn btn-primary" href="<?= e(url('marketplace.php')) ?>">Acessar Marketplace →</a></div>
<div class="grid-2 marketplace-admin-grid">
<section class="panel"><div class="panel-header"><div><h3>Ranking de empresas</h3><p>Ordenação por qualidade, volume de avaliações e desempenho.</p></div></div><div class="table-wrap ranking-table-wrap" role="region" aria-label="Ranking de empresas" tabindex="0"><div class="ranking-swipe-hint">Arraste para o lado para ver todas as colunas →</div><table class="ranking-table"><thead><tr><th>#</th><th>Empresa</th><th>Nota</th><th>Avaliações</th><th>Selos</th></tr></thead><tbody><?php foreach($rankings as $i=>$company):?><tr><td><strong><?= $i+1 ?></strong></td><td><div class="table-title"><div class="table-thumb"><?php if($company['logo']):?><img src="<?= e(media_url($company['logo'])) ?>" alt=""><?php else:?>🏢<?php endif;?></div><div><strong><?= e($company['name']) ?></strong><small><?= e($company['city'].'/'.$company['state']) ?></small></div></div></td><td><?= stars_html($company['rating_avg']) ?> <?= number_format((float)$company['rating_avg'],1,',','.') ?></td><td><?= (int)$company['rating_count'] ?></td><td><?php if($company['verified']):?><span class="status status-active">Verificada</span><?php endif;?> <?php if($company['premium']):?><span class="status status-pending">Premium</span><?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section>
<section class="panel"><div class="panel-header"><div><h3>Resumo</h3><p>Pontuação média das empresas visível para todos os usuários.</p></div></div><div class="stats-grid compact-stats"><article class="stat-card"><span>Média das empresas</span><strong><?= number_format((float)$companyRatingStats['rating_avg'],1,',','.') ?></strong><small><?= stars_html((float)$companyRatingStats['rating_avg']) ?> de 5 estrelas</small></article><article class="stat-card"><span>Avaliações de empresas</span><strong><?= (int)$companyRatingStats['rating_count'] ?></strong><small>Avaliações públicas consideradas</small></article><?php if(in_array($reviewScope,['company','provider'],true)):?><article class="stat-card"><span><?= $reviewScope==='company'?'Nota da sua empresa':'Sua nota média' ?></span><strong><?= number_format((float)$ownRatingStats['rating_avg'],1,',','.') ?></strong><small><?= stars_html((float)$ownRatingStats['rating_avg']) ?> • <?= (int)$ownRatingStats['rating_count'] ?> avaliação(ões)</small></article><?php endif;?></div><div class="notice" style="margin-top:18px">A pontuação pública considera somente avaliações publicadas. Assim, clientes, funcionários, entregadores, prestadores e empresas enxergam a mesma média no ranking.</div></section>
</div>
<section class="panel"><div class="panel-header"><div><h3><?= in_array($reviewScope,['company','provider','admin'],true)?'Avaliações recebidas':'Avaliações e reputação' ?></h3><p><?= in_array($reviewScope,['company','provider','admin'],true)?'Empresas e prestadores podem responder; a administração pode moderar.':'Consulte acima a pontuação média e o ranking público das empresas.' ?></p></div></div><?php if(!$reviews):?><div class="empty-state"><strong><?= $reviewScope==='public'?'Reputação pública disponível no ranking':'Nenhuma avaliação' ?></strong><?= $reviewScope==='public'?'As notas de cada empresa continuam visíveis no ranking acima.':'As avaliações aparecerão aqui.' ?></div><?php else:?><div class="review-list"><?php foreach($reviews as $review):?><article class="review-card"><div class="review-head"><div><strong><?= e(user_public_name(['username'=>$review['reviewer_username'],'public_id'=>$review['reviewer_public_id'],'name'=>$review['reviewer_name']?:'Cliente'])) ?></strong><div><?= stars_html($review['rating']) ?></div></div><?= status_badge($review['status']) ?></div><p><?= e($review['comment']?:'Avaliação sem comentário.') ?></p><?php if($review['response']):?><div class="review-response"><strong>Resposta:</strong> <?= e($review['response']) ?></div><?php endif;?><div class="actions"><?php if(!is_admin()):?><button class="btn btn-secondary btn-sm" data-modal-open="#review<?= (int)$review['id'] ?>">Responder</button><?php else:?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="moderate_review"><input type="hidden" name="return_page" value="marketplace_admin"><input type="hidden" name="id" value="<?= (int)$review['id'] ?>"><input type="hidden" name="status" value="<?= $review['status']==='published'?'hidden':'published' ?>"><button class="btn btn-secondary btn-sm"><?= $review['status']==='published'?'Ocultar':'Publicar' ?></button></form><?php endif;?></div></article><?php if(!is_admin()):?><div class="modal" id="review<?= (int)$review['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Responder avaliação</h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="respond_review"><input type="hidden" name="return_page" value="marketplace_admin"><input type="hidden" name="id" value="<?= (int)$review['id'] ?>"><div class="form-group"><label>Resposta pública</label><textarea name="response" required><?= e($review['response']) ?></textarea></div><div class="form-actions"><button class="btn btn-primary">Publicar resposta</button></div></form></div></div><?php endif;?><?php endforeach;?></div><?php endif;?></section>
