<?php
//par niveau:
foreach($tabDebniveau as $niveau) {
	$activNiveau[$niveau] = array();
	$tabActivites[$niveau] = array();
	$tabActivitesNom[$niveau] = array();
	$tabActivitesODS[$niveau] = array();
	$tabActivitesNomODS[$niveau] = array();

	//fréquentation par activité :
	$tabNbPerActivite[$niveau] = array();
	$tabNbPerActiviteODS[$niveau] = array();
	$tabPercentPerActivite[$niveau] = array();
	$tabPercentPerActiviteODS[$niveau] = array();
	$act=0;
	foreach($activ as $activ_info) {
		$activ_code = $activ_info['code_activ'];
		if(($filtre_activs==""||@$_SESSION['verif_activ'][0]==""||in_array($activ_code,$_SESSION['verif_activ']))&&$activ_code!='ZERO') { // on vérifie qu'elle n'est pas décochée
			$nbeleves_nivglob = mysqli_num_rows(mysqli_query($bdd,"SELECT freq.freq_id FROM ".$prefix."_freq freq WHERE date_freq >= '".$day1."' AND date_freq <= '".$day2."' AND division LIKE '".$niveau."%' ".$filtre_activs.""));
			$nbeleves_nivact = mysqli_num_rows(mysqli_query($bdd,"SELECT freq.freq_id FROM ".$prefix."_freq freq WHERE date_freq >= '".$day1."' AND date_freq <= '".$day2."' AND division LIKE '".$niveau."%' AND code_activ = '".$activ_code."' ".$filtre_espaces.""));
			//si grappes
			if($grappes_check==1) {
				$elegrap_nb_glob = mysqli_query($bdd,"SELECT nombre FROM ".$prefix."_freqgrappes WHERE date_freq >= '".$day1."' AND date_freq <= '".$day2."' AND niveau = '".$niveau."' AND passage = '0' ".$filtre_activs."");
				$elegrap_nb = mysqli_query($bdd,"SELECT nombre FROM ".$prefix."_freqgrappes WHERE date_freq >= '".$day1."' AND date_freq <= '".$day2."' AND niveau = '".$niveau."' AND passage = '0' AND code_activ = '".$activ_code."' ".$filtre_espaces."");
				foreach($elegrap_nb_glob as $elegrapglob) {
					$nbeleves_nivglob += $elegrapglob['nombre'];
				}
				foreach($elegrap_nb as $elegrapact) {
					$nbeleves_nivact += $elegrap['nombre'];
				}
			}
			if($nbeleves_nivact>0) {
				$tabActivites[$niveau][] = $activ_info['code_activ'];
				$tabActivitesNom[$niveau][] = $activ_info['nom_activ'];
				$percent_act = round(($nbeleves_nivact * 100 / $nbeleves_nivglob),2);
				array_push($tabPercentPerActivite[$niveau],$percent_act);				
			}
			$tabActivitesODS[$niveau][] = $activ_info['code_activ'];
			$tabActivitesNomODS[$niveau][] = $activ_info['nom_activ'];
			$percent_actODS = round(($nbeleves_nivact * 100 / $nbeleves_nivglob),2);
			array_push($tabNbPerActiviteODS[$niveau],$nbeleves_nivact);
			array_push($tabPercentPerActiviteODS[$niveau],$percent_actODS);
		}
		$act++;
	}
}
$bctab2 = '<table style="text-align:right;">
<thead><tr><td colspan="'.($act+2).'" style="text-align:center;">'.FDIR_STATS_TIT7.'<br>'.FROM2.' '.$affday1.' '.TO2.' '.$affday2.'</td></tr><tr><th></th>';
foreach($activ as $activ_info) {
	$bctab2 .= '<th>'.$activ_info['nom_activ'].'</th>';
}
$bctab2 .= '<th>'.TOTAL.'</th></tr></thead><tbody>';
$w=1;
$nivi=0;
foreach($tabDebniveau as $niveau) {
	$bctab2 .= '<tr><td>'.$tabNiveau[$nivi].'</td>';
	$m=0;
	$tot = 0;
	foreach($activ as $activ_info) {
		$bctab2 .= '<td>'.$tabNbPerActiviteODS[$niveau][$m].'</td>';
		$tot += $tabNbPerActiviteODS[$niveau][$m];
		$m++;		
	}
	$bctab2 .= '<td>'.$tot.'</td></tr>';
	$w++;
	$nivi++;
}	
$bctab2 .= '</tbody></table>';
$bctab3 = '<table style="text-align:right;">
<thead><tr><td colspan="'.($act+2).'" style="text-align:center;">'.FDIR_STATS_TIT8.'<br>'.FROM2.' '.$affday1.' '.TO2.' '.$affday2.'</td></tr><tr><th></th>';
foreach($activ as $activ_info) {
	$bctab3 .= '<th>'.$activ_info['nom_activ'].'</th>';
}
$bctab3 .= '<th>'.TOTAL.'</th></tr></thead><tbody>';
$w=1;
$nivi=0;
foreach($tabDebniveau as $niveau) {
	$bctab3 .= '<tr><td>'.$tabNiveau[$nivi].'</td>';
	$m=0;
	foreach($activ as $activ_info) {
		$bctab3 .= '<td>'.number_format((float)$tabPercentPerActiviteODS[$niveau][$m],2,'.','').'</td>';
		$m++;
	}
	$bctab3 .= '<td>100.00</td></tr>';
	$w++;
	$nivi++;
}	
$bctab3 .= '</tbody></table>';
$i=0;
foreach($tabDebniveau as $niveau) { 
	if(json_encode($tabPercentPerActivite[$niveau])!="[]") {
		?>
		<div id="wrapper" class="statcadre">
		<canvas id="chart_percentperactiv<?php echo $niveau; ?>" class="charts" width="400" height="400"></canvas>
		</div>
		<script type="text/javascript">
		(async function() {
		    
		    Chart.register(ChartDataLabels);
		    const labels = <?php echo json_encode($tabActivitesNom[$niveau]); ?>;
		    const data = {
		      labels: labels,
		      datasets: [{
		            data: <?php echo json_encode($tabPercentPerActivite[$niveau]); ?>,
		            backgroundColor: <?php echo json_encode($basicColors); ?>,
		            borderColor: <?php echo json_encode($basicColors); ?>,
		        }]
		    };
		new Chart(
		    document.getElementById('chart_percentperactiv<?php echo $niveau; ?>'),
		    {
		    type: 'pie',
		    data : data,
		    options: {
		        plugins: {
		            title: {
		                display: true,
		                text: "<?php echo FDIR_STATS_TIT9.' '.$tabNiveau[$i]; ?>"
		            },
		            legend: {
		                display:true
		            },
		            tooltip : {
		                mode: 'point',
		                intersect: false,
		              }  ,    
		            datalabels: {
		              display: true, // Affiche les étiquettes de données
		              formatter: function(value, context) {
		                    return value + ' %'; // Ajoute le symbole "%" après la valeur
		                },
		              color: '#878787', // Couleur du texte
		              align: 'center', // Alignement horizontal
		              anchor: 'center', // Alignement vertical
		              font: {
		                weight: 'bold', // Style de police
		              },
		              display: function(context) {
		                  return context.dataset.data[context.dataIndex] !== 0; // N'affiche pas si la valeur est égale à 0
		                },
		            },
		        },
		        responsive: true,
		      }
		    }
		);
		})();
		</script>
<?php 
$i++; 
	} 
}
echo '<br> <br>'.$bctab2;
$_SESSION['bctabs'] .= '<table></table>'.$bctab2; 
echo '<br> <br>'.$bctab3;
$_SESSION['bctabs'] .= '<table></table>'.$bctab3; 
?>