<?php
require __DIR__ . '/app/bootstrap.php';
require __DIR__ . '/app/layout.php';
require_auth();
if (account_restricted(current_user())) redirect('dashboard.php?page=charges');
$q = trim(request('q',''));
$city = trim(request('city',''));
$segment = trim(request('segment','all'));
$like = '%' . $q . '%';

$companySql = "SELECT c.*, COALESCE(AVG(r.rating),0) rating_avg, COUNT(r.id) rating_count
  FROM companies c LEFT JOIN reviews r ON r.target_type='company' AND r.target_id=c.id AND r.status='published'
  WHERE c.status='active'";
$args=[];
if($q!==''){ $companySql.=" AND (c.name LIKE ? OR c.description LIKE ? OR c.type LIKE ?)"; $args=[$like,$like,$like]; }
if($city!==''){ $companySql.=" AND c.city LIKE ?"; $args[]='%'.$city.'%'; }
if($segment!=='all' && !in_array($segment,['professionals','properties','vehicles'],true)){ $companySql.=" AND c.type=?"; $args[]=$segment; }
$companySql.=" GROUP BY c.id";
$stmt=db()->prepare($companySql);$stmt->execute($args);$companies=$stmt->fetchAll();
usort($companies,function($a,$b){return marketplace_score($b)<=>marketplace_score($a);});

$providers=[];
if(in_array($segment,['all','professionals'],true)){
  $sql="SELECT u.*, COALESCE(AVG(r.rating),0) rating_avg,COUNT(r.id) rating_count,
    (SELECT GROUP_CONCAT(name, ', ') FROM services s WHERE s.provider_id=u.id AND s.status='active') service_names
    FROM users u LEFT JOIN reviews r ON r.target_id=u.id AND r.target_type IN ('service_provider','ride_driver','delivery_courier','moving_driver') AND r.status='published'
    WHERE u.role IN ('service_provider','mototaxi','taxi','private_driver','courier','motofreight','moving_provider') AND u.status='active' AND u.marketplace_visible=1";
  $a=[];
  if($q!==''){ $sql.=" AND (u.name LIKE ? OR COALESCE(u.username,'') LIKE ? OR COALESCE(u.public_id,'') LIKE ? OR EXISTS(SELECT 1 FROM services sx WHERE sx.provider_id=u.id AND (sx.name LIKE ? OR sx.description LIKE ?)))";$a=[$like,$like,$like,$like,$like]; }
  if($city!==''){ $sql.=" AND (u.city LIKE ? OR EXISTS(SELECT 1 FROM services sx WHERE sx.provider_id=u.id AND sx.city LIKE ?))";$a[]='%'.$city.'%';$a[]='%'.$city.'%'; }
  $sql.=" GROUP BY u.id HAVING COUNT(r.id)>0 ORDER BY rating_avg DESC,rating_count DESC";
  $st=db()->prepare($sql);$st->execute($a);$providers=$st->fetchAll();
}

$properties=[];
if(in_array($segment,['all','properties'],true)){
  $sql="SELECT p.*,u.name owner_name FROM properties p JOIN users u ON u.id=p.owner_id WHERE p.status='available'";$a=[];
  if($q!==''){ $sql.=" AND (p.title LIKE ? OR p.description LIKE ? OR p.type LIKE ?)";$a=[$like,$like,$like]; }
  if($city!==''){ $sql.=" AND p.city LIKE ?";$a[]='%'.$city.'%'; }
  $sql.=" ORDER BY p.created_at DESC LIMIT 24";$st=db()->prepare($sql);$st->execute($a);$properties=$st->fetchAll();
}

$vehicles=[];
if(in_array($segment,['all','vehicles'],true)){
  $sql="SELECT v.*,c.name company_name,u.name owner_name FROM vehicles v LEFT JOIN companies c ON c.id=v.company_id LEFT JOIN users u ON u.id=v.owner_user_id WHERE v.listing_mode='sale' AND v.status='available'";$a=[];
  if($q!==''){ $sql.=" AND (v.brand LIKE ? OR v.model LIKE ? OR v.type LIKE ?)";$a=[$like,$like,$like]; }
  $sql.=" ORDER BY v.premium DESC,v.created_at DESC LIMIT 24";
  // Compatibilidade: premium pertence à empresa, não ao veículo.
  $sql=str_replace('v.premium DESC,','COALESCE(c.premium,0) DESC,',$sql);
  $st=db()->prepare($sql);$st->execute($a);$vehicles=$st->fetchAll();
}

render_public_header('Marketplace');
render_platform_banners('marketplace');
?>
<section class="marketplace-hero">
  <div class="marketplace-hero-copy"><span class="mini-label">MARKETPLACE MULTISSERVIÇOS</span><h1>O que você procura<br><span>perto de você?</span></h1><p>Empresas, profissionais, imóveis e veículos organizados por qualidade, avaliações e localização.</p></div>
  <form class="marketplace-search" method="get">
    <div class="search-field"><span>⌕</span><input name="q" value="<?= e($q) ?>" placeholder="Ex.: eletricista, mercado, carro..."></div>
    <div class="search-field"><span>📍</span><input name="city" value="<?= e($city) ?>" placeholder="Cidade ou bairro"></div>
    <select name="segment"><option value="all">Todos os segmentos</option><?php foreach(['delivery'=>'Alimentação e delivery','market'=>'Mercados','pharmacy'=>'Farmácias','services'=>'Empresas de serviços','vehicle_store'=>'Lojas de veículos','moving'=>'Mudanças e fretes','professionals'=>'Profissionais','properties'=>'Imóveis','vehicles'=>'Veículos à venda','gas'=>'Gás e água','construction'=>'Construção','petshop'=>'Pet Shop','other'=>'Outros'] as $key=>$label):?><option value="<?= e($key) ?>"<?= selected($segment,$key) ?>><?= e($label) ?></option><?php endforeach;?></select>
    <button class="btn btn-primary">Pesquisar</button>
  </form>
</section>

<section class="section marketplace-section">
  <div class="section-head section-head-left"><span>Empresas recomendadas</span><h2>Melhor reputação primeiro</h2><p>O ranking considera avaliação, quantidade de opiniões, pedidos concluídos, tempo de resposta e selo verificado.</p></div>
  <?php if(!$companies):?><div class="empty-state"><strong>Nenhuma empresa encontrada</strong>Tente outro termo ou cidade.</div><?php else:?><div class="market-grid">
  <?php foreach(array_slice($companies,0,24) as $company):$canReview=false;if(current_user()){$rv=db()->prepare("SELECT COUNT(*) FROM orders o LEFT JOIN reviews r ON r.order_id=o.id AND r.reviewer_id=? AND r.target_type='company' WHERE o.client_id=? AND o.company_id=? AND o.status IN ('completed','delivered') AND r.id IS NULL");$rv->execute([current_user()['id'],current_user()['id'],$company['id']]);$canReview=(int)$rv->fetchColumn()>0;}?>
    <article class="market-card">
      <div class="market-cover"><?php if($company['banner']):?><img src="<?= e(media_url($company['banner'])) ?>" alt=""><?php else:?><span>🏢</span><?php endif;?><div class="market-badges"><?php if($company['verified']):?><b>✓ Verificada</b><?php endif;?><?php if($company['premium']):?><b class="premium">◆ Premium</b><?php endif;?></div></div>
      <div class="market-body"><div class="market-brand"><?php if($company['logo']):?><img src="<?= e(media_url($company['logo'])) ?>" alt=""><?php else:?><span><?= e(strtoupper(substr($company['name'],0,1))) ?></span><?php endif;?><div><h3><?= e($company['name']) ?></h3><small><?= e(ucfirst(str_replace('_',' ',$company['type']))) ?> • <?= e($company['city']?:'Cidade não informada') ?></small></div></div>
      <div class="market-rating"><?= stars_html($company['rating_avg']) ?><strong><?= number_format((float)$company['rating_avg'],1,',','.') ?></strong><small>(<?= (int)$company['rating_count'] ?> avaliações)</small></div>
      <p><?= e(short_text($company['description']?:'Empresa cadastrada na plataforma LinkExpress.',110)) ?></p>
      <div class="market-metrics"><span>⏱ <?= (int)$company['response_minutes'] ?> min</span><span>✓ <?= (int)$company['completed_orders'] ?> atendimentos</span></div>
      <div class="market-actions"><a class="btn btn-secondary btn-sm" href="<?= e(whatsapp_url($company['phone'],'Olá, encontrei sua empresa na LinkExpress.',0,(int)$company['id'],'marketplace_company')) ?>" target="_blank" rel="noopener">WhatsApp</a><?php if(current_user()&&is_role('client')):?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="toggle_favorite"><input type="hidden" name="target_type" value="company"><input type="hidden" name="target_id" value="<?= (int)$company['id'] ?>"><input type="hidden" name="return_page" value="marketplace"><button class="btn btn-secondary btn-sm">♡ Favoritar</button></form><?php endif;?><?php if($canReview):?><button class="btn btn-secondary btn-sm" data-modal-open="#rateCompany<?= (int)$company['id'] ?>">★ Avaliar</button><?php endif;?></div>
      </div>
    </article>
    <?php if($canReview):?><div class="modal" id="rateCompany<?= (int)$company['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Avaliar <?= e($company['name']) ?></h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="save_review"><input type="hidden" name="return_page" value="marketplace"><input type="hidden" name="target_type" value="company"><input type="hidden" name="target_id" value="<?= (int)$company['id'] ?>"><div class="form-grid"><div class="form-group"><label>Nota geral</label><select name="rating"><option value="5">★★★★★ Excelente</option><option value="4">★★★★☆ Muito bom</option><option value="3">★★★☆☆ Bom</option><option value="2">★★☆☆☆ Regular</option><option value="1">★☆☆☆☆ Ruim</option></select></div><div class="form-group"><label>Atendimento</label><select name="service_rating"><option>5</option><option>4</option><option>3</option><option>2</option><option>1</option></select></div><div class="form-group"><label>Qualidade</label><select name="quality_rating"><option>5</option><option>4</option><option>3</option><option>2</option><option>1</option></select></div><div class="form-group"><label>Preço</label><select name="price_rating"><option>5</option><option>4</option><option>3</option><option>2</option><option>1</option></select></div><div class="form-group full"><label>Comentário</label><textarea name="comment" required></textarea></div></div><div class="form-actions"><button class="btn btn-primary">Publicar avaliação</button></div></form></div></div><?php endif;?>
  <?php endforeach;?></div><?php endif;?>
</section>

<?php if($providers):?><section class="section marketplace-section alt"><div class="section-head section-head-left"><span>Profissionais</span><h2>Especialistas mais bem avaliados</h2></div><div class="market-grid compact-grid"><?php foreach($providers as $provider):?><article class="professional-card"><?= avatar_html($provider,'professional-avatar') ?><div><h3><?= e(user_public_name($provider)) ?></h3><div class="market-rating"><?= stars_html($provider['rating_avg']) ?><strong><?= number_format((float)$provider['rating_avg'],1,',','.') ?></strong></div><p><?= e(short_text($provider['service_names']?:role_label($provider['role']).' avaliado na plataforma.',100)) ?></p><small><?= e(role_label($provider['role'])) ?> • 📍 <?= e($provider['city']?:'Localização a combinar') ?></small></div><a class="btn btn-primary btn-sm" href="<?= e(whatsapp_url($provider['phone'],'Olá, encontrei seu perfil na LinkExpress.',(int)$provider['id'],0,'marketplace_professional')) ?>" target="_blank" rel="noopener">Conversar</a></article><?php endforeach;?></div></section><?php endif;?>

<?php if($vehicles):?><section class="section marketplace-section"><div class="section-head section-head-left"><span>Automóveis</span><h2>Veículos disponíveis</h2></div><div class="market-grid"><?php foreach($vehicles as $vehicle):?><article class="market-card"><div class="market-cover vehicle-cover"><?php if($vehicle['image']):?><img src="<?= e(media_url($vehicle['image'])) ?>" alt=""><?php else:?><span>🚙</span><?php endif;?></div><div class="market-body"><h3><?= e($vehicle['brand'].' '.$vehicle['model']) ?></h3><p><?= e(($vehicle['year']?:'Ano não informado').' • '.($vehicle['mileage']?number_format($vehicle['mileage'],0,',','.').' km':'0 km').' • '.($vehicle['fuel']?:'Combustível não informado')) ?></p><div class="market-price"><?= money($vehicle['sale_price']) ?></div><small><?= e($vehicle['company_name']?:$vehicle['owner_name']) ?></small><a class="btn btn-primary btn-sm btn-block" href="<?= e(url('login.php')) ?>">Ver proposta e test drive</a></div></article><?php endforeach;?></div></section><?php endif;?>

<?php if($properties):?><section class="section marketplace-section alt"><div class="section-head section-head-left"><span>Imóveis</span><h2>Casas, apartamentos e espaços</h2></div><div class="market-grid"><?php foreach($properties as $property):?><article class="market-card"><div class="market-cover"><?php if($property['image']):?><img src="<?= e(media_url($property['image'])) ?>" alt=""><?php else:?><span>🏠</span><?php endif;?></div><div class="market-body"><h3><?= e($property['title']) ?></h3><p><?= e($property['city'].'/'.$property['state'].' • '.$property['bedrooms'].' quartos • '.$property['bathrooms'].' banheiros') ?></p><div class="market-price"><?= money($property['price']) ?><?= $property['purpose']==='rent'?'<small>/mês</small>':'' ?></div><a class="btn btn-secondary btn-sm btn-block" href="<?= e(url('login.php')) ?>">Demonstrar interesse</a></div></article><?php endforeach;?></div></section><?php endif;?>
<?php render_public_footer(); ?>
