<?php
require_once __DIR__ . "/_commons.php";
$pdo = pdo_m(); $GF=get_global_filters();
if(!require_filters_guard($GF)){ echo '<div style="width:100%;height:260px"></div>'; return; }

[$from,$to]=build_range($GF['range'] ?? 'month', $GF['fromUi'] ?? '', $GF['toUi'] ?? '');
$entryCond=entry_condition_sql();
$params  = [':site'=>$GF['site'],':from'=>$from,':to'=>$to] + allowed_url_params();

list($campWhere,$campParams) = campaign_source_condition($GF,'v');
list($advWhere,$advParams,$needAin) = build_advanced_where($GF,'v','ain');

$rows=[];
try{
  $sql="
    SELECT COALESCE(v.config_browser_name,'') AS code, COUNT(*) AS cnt
    FROM matomo_log_visit v
    LEFT JOIN matomo_log_action ain ON ain.idaction = v.visit_entry_idaction_url
    WHERE v.idsite=:site AND v.visit_last_action_time BETWEEN :from AND :to
      AND $entryCond
      $campWhere
      $advWhere
    GROUP BY v.config_browser_name
    ORDER BY cnt DESC
  ";
  $st=$pdo->prepare($sql); $st->execute($params + $campParams + $advParams);
  foreach($st->fetchAll() as $t){ $rows[]=['br'=>browser_human($t['code']),'cnt'=>(int)$t['cnt']]; }
}catch(Throwable $e){}
?>
<div id="browsers_pie_chart" style="width:100%;height:260px"></div>
<script>
ensureGoogleCharts(function(){
  const data=new google.visualization.DataTable();
  data.addColumn('string','Navegador'); data.addColumn('number','Sesiones');
  data.addRows([<?php foreach($rows as $r): ?>['<?= e($r['br']) ?>', <?= (int)$r['cnt'] ?>],<?php endforeach; ?>]);
  new google.visualization.PieChart(document.getElementById('browsers_pie_chart'))
    .draw(data,{pieHole:0.35,legend:{position:'right'},chartArea:{left:10,top:10,right:10,bottom:10}});
});
</script>
