<?php
require __DIR__ . '/app/bootstrap.php';
require __DIR__ . '/app/layout.php';
require_auth();
$viewer=current_user();
$id=(int)request('id',0);
$stmt=db()->prepare("SELECT u.*,c.name company_name,c.logo company_logo,c.type company_type FROM users u LEFT JOIN companies c ON c.id=u.company_id WHERE u.id=? AND u.status='active'");
$stmt->execute([$id]);$person=$stmt->fetch();
if(!$person){http_response_code(404);render_public_header('Perfil não encontrado');echo '<section class="section"><div class="empty-state"><strong>Perfil não encontrado</strong>O usuário pode estar inativo ou o endereço está incorreto.</div></section>';render_public_footer();exit;}
$rating=user_rating_summary($id);
$reviews=[];
$q=db()->prepare("SELECT r.*,u.name reviewer_name,u.username reviewer_username,u.public_id reviewer_public_id,u.avatar reviewer_avatar FROM reviews r JOIN users u ON u.id=r.reviewer_id WHERE r.target_id=? AND r.target_type IN ('service_provider','moving_driver') AND r.status='published' ORDER BY r.id DESC LIMIT 20");$q->execute([$id]);$reviews=$q->fetchAll();
$saved=false;$q=db()->prepare('SELECT COUNT(*) FROM contact_book WHERE owner_user_id=? AND contact_user_id=?');$q->execute([$viewer['id'],$id]);$saved=(int)$q->fetchColumn()>0;
render_public_header('Perfil de '.user_public_name($person));
?>
<section class="section profile-public-section">
  <div class="grid-2">
    <article class="panel">
      <div class="profile-hero"><?= avatar_html($person,'professional-avatar') ?><div><span class="mini-label"><?= e(public_user_id($person)) ?></span><h1><?= e(user_public_name($person)) ?></h1><p><strong>Nome real:</strong> <?= e($person['name']) ?></p><p><?= e(role_label($person['role'])) ?><?php if($person['company_name']):?> • <?= e($person['company_name']) ?><?php endif;?></p></div></div>
      <div class="market-rating" style="margin:20px 0"><?= stars_html($rating['rating_avg']) ?><strong><?= number_format((float)$rating['rating_avg'],1,',','.') ?></strong><small><?= (int)$rating['rating_count'] ?> avaliação(ões)</small></div>
      <div class="activity-list"><div class="activity"><span class="activity-dot"></span><div><p>Cidade</p><small><?= e(($person['city']?:'Não informada').($person['state']?'/'.$person['state']:'')) ?></small></div></div><div class="activity"><span class="activity-dot"></span><div><p>Disponibilidade</p><small><?= e(status_label($person['work_status']?:'offline')) ?></small></div></div><div class="activity"><span class="activity-dot"></span><div><p>WhatsApp</p><small><?= e(format_phone($person['phone'])) ?></small></div></div></div>
      <div class="actions" style="margin-top:20px"><?php if($person['phone']):?><a class="btn btn-accent" target="_blank" rel="noopener" href="<?= e(whatsapp_url($person['phone'],'Olá, encontrei seu perfil na LinkExpress.',(int)$person['id'],0,'public_profile')) ?>">Conversar no WhatsApp</a><?php endif;?><?php if($person['telegram']):?><a class="btn btn-secondary" target="_blank" rel="noopener" href="<?= e(telegram_url($person['telegram'])) ?>">Telegram</a><?php endif;?><?php if($person['instagram']):?><a class="btn btn-secondary" target="_blank" rel="noopener" href="<?= e(instagram_url($person['instagram'])) ?>">Instagram</a><?php endif;?><?php if((int)$person['id']!==(int)$viewer['id']&&!$saved):?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="save_contact"><input type="hidden" name="return_page" value="contacts"><input type="hidden" name="contact_user_id" value="<?= (int)$person['id'] ?>"><button class="btn btn-primary">Salvar nos contatos</button></form><?php elseif($saved):?><span class="status status-active">✓ Contato salvo</span><?php endif;?><?php if((int)$person['id']!==(int)$viewer['id']):?><a class="btn btn-danger" href="<?= e(url('dashboard.php?page=reports&reported_id='.(int)$person['id'])) ?>">🚩 Denunciar usuário</a><?php endif;?><a class="btn btn-secondary" href="<?= e(url('dashboard.php?page=contacts')) ?>">Meus contatos</a></div>
    </article>
    <article class="panel"><div class="panel-header"><div><h2>Avaliações verificadas</h2><p>Somente avaliações após atendimentos concluídos.</p></div></div><?php if(!$reviews):?><div class="empty-state"><strong>Ainda sem avaliações</strong>Este perfil aparecerá no marketplace após receber uma avaliação válida.</div><?php endif;?><div class="activity-list"><?php foreach($reviews as $r):?><div class="activity"><?= avatar_html(['name'=>$r['reviewer_name'],'avatar'=>$r['reviewer_avatar']]) ?><div><p><strong><?= e(user_public_name(['username'=>$r['reviewer_username'],'public_id'=>$r['reviewer_public_id'],'name'=>$r['reviewer_name']])) ?></strong> <?= stars_html($r['rating']) ?></p><small><?= e($r['comment']?:'Avaliação sem comentário.') ?></small></div></div><?php endforeach;?></div></article>
  </div>
</section>
<?php render_public_footer(); ?>
