<?php
if(!is_admin()){http_response_code(403);exit('Sem permissão.');}
$month=trim((string)request('month',date('Y-m')));if(!preg_match('/^\d{4}-\d{2}$/',$month))$month=date('Y-m');
$q=db()->prepare("SELECT COUNT(*) FROM whatsapp_clicks WHERE substr(created_at,1,7)=?");$q->execute([$month]);$total=(int)$q->fetchColumn();
$q=db()->prepare("SELECT COUNT(*) FROM whatsapp_clicks WHERE substr(created_at,1,10)=? ");$q->execute([today()]);$todayClicks=(int)$q->fetchColumn();
$q=db()->prepare("SELECT wc.target_user_id,wc.target_company_id,u.name user_name,u.username,u.public_id,c.name company_name,COUNT(*) clicks,COUNT(DISTINCT wc.visitor_user_id) unique_users,MAX(wc.created_at) last_click FROM whatsapp_clicks wc LEFT JOIN users u ON u.id=wc.target_user_id LEFT JOIN companies c ON c.id=wc.target_company_id WHERE substr(wc.created_at,1,7)=? GROUP BY wc.target_user_id,wc.target_company_id ORDER BY clicks DESC,last_click DESC");$q->execute([$month]);$rows=$q->fetchAll();
$q=db()->prepare("SELECT source,COUNT(*) clicks FROM whatsapp_clicks WHERE substr(created_at,1,7)=? GROUP BY source ORDER BY clicks DESC");$q->execute([$month]);$sources=$q->fetchAll();
?>
<section class="page-intro"><div><span class="mini-label">📲 WHATSAPP</span><h2>Acessos por WhatsApp</h2><p>Quantidade de direcionamentos feitos pela plataforma para usuários e empresas.</p></div><form method="get"><input type="hidden" name="page" value="whatsapp_stats"><input class="input" type="month" name="month" value="<?= e($month) ?>" onchange="this.form.submit()"></form></section>
<div class="stats-grid"><div class="stat-card"><div class="stat-top"><span>Cliques no mês</span><span class="stat-icon">📲</span></div><strong><?= number_format($total,0,',','.') ?></strong><small><?= e($month) ?></small></div><div class="stat-card"><div class="stat-top"><span>Cliques hoje</span><span class="stat-icon">📅</span></div><strong><?= number_format($todayClicks,0,',','.') ?></strong><small><?= e(date('d/m/Y')) ?></small></div><div class="stat-card"><div class="stat-top"><span>Destinos alcançados</span><span class="stat-icon">👥</span></div><strong><?= count($rows) ?></strong><small>Usuários/empresas no mês</small></div></div>
<section class="panel"><div class="panel-header"><div><h3>Direcionamentos por usuário/empresa</h3><p>Ranking mensal dos contatos que receberam acessos pelo botão de WhatsApp.</p></div></div><?php if(!$rows):?><div class="empty-state"><strong>Nenhum acesso registrado neste mês</strong>Os próximos cliques em botões da plataforma aparecerão aqui.</div><?php else:?><div class="table-wrap"><table><thead><tr><th>Destino</th><th>Cliques</th><th>Usuários identificados</th><th>Último acesso</th></tr></thead><tbody><?php foreach($rows as $r):?><tr><td><strong><?= e($r['company_name']?:(!empty($r['user_name'])?user_public_name(['username'=>$r['username'],'public_id'=>$r['public_id'],'name'=>$r['user_name']]):'Suporte da plataforma')) ?></strong></td><td><?= number_format((int)$r['clicks'],0,',','.') ?></td><td><?= number_format((int)$r['unique_users'],0,',','.') ?></td><td><?= e(date('d/m/Y H:i',strtotime($r['last_click']))) ?></td></tr><?php endforeach;?></tbody></table></div><?php endif;?></section>
<?php if($sources):?><section class="panel"><div class="panel-header"><div><h3>Origem dos acessos</h3></div></div><div class="activity-list"><?php foreach($sources as $s):?><div class="activity"><span class="activity-dot"></span><div><p><strong><?= e($s['source']?:'Plataforma') ?></strong></p><small><?= (int)$s['clicks'] ?> clique(s)</small></div></div><?php endforeach;?></div></section><?php endif;?>
