<?php
//par niveau:
foreach($tabDebniveau as $niveau) {
	$activNiveau[$niveau] = array();
	$tabEsp[$niveau] = array();
	$tabEspNom[$niveau] = array();
	$tabEspODS[$niveau] = array();
	$tabEspNomODS[$niveau] = array();

	//fréquentation par activité :
	$tabNbPerEsp[$niveau] = array();
	$tabPercentPerEsp[$niveau] = array();
	$tabNbPerEspODS[$niveau] = array();
	$tabPercentPerEspODS[$niveau] = array();
	$act=0;
	if(isset($_SESSION['espace0'])||$filtre_espaces=="") {
		$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 (espace_id = '0' OR espace_id IS NULL) ".$filtre_activsonly.""));
		//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 (espace_id = '0' OR espace_id IS NULL) ".$filtre_activsonly."");
			foreach($elegrap_nb_glob as $elegrapglob) {
				$nbeleves_nivglob += $elegrapglob['nombre'];
			}
			foreach($elegrap_nb as $elegrapact) {
				$nbeleves_nivact += $elegrap['nombre'];
			}
		}
		if($nbeleves_nivact>0) {
			$tabEsp[$niveau][] = 0;
			$tabEspNom[$niveau][] = $esp0['valeur'];
			$percent_act = round(($nbeleves_nivact * 100 / $nbeleves_nivglob),2);
			array_push($tabPercentPerEsp[$niveau],$percent_act);
		}
		$tabEspODS[$niveau][] = 0;
		$tabEspNomODS[$niveau][] = $esp0['valeur'];
		$percent_act = round(($nbeleves_nivact * 100 / $nbeleves_nivglob),2);
		array_push($tabNbPerEspODS[$niveau],$nbeleves_nivact);
		array_push($tabPercentPerEspODS[$niveau],$percent_act);
		$act++;
	}
	foreach($espacs as $espacs_info) {
		$esp_id = $espacs_info['espace_id'];
		if($filtre_espaces==""||isset($_SESSION['espace'.$esp_id])) { // 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 espace_id = '".$esp_id."' ".$filtre_activsonly.""));
			//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 espace_id = '".$esp_id."' ".$filtre_activsonly."");
				foreach($elegrap_nb_glob as $elegrapglob) {
					$nbeleves_nivglob += $elegrapglob['nombre'];
				}
				foreach($elegrap_nb as $elegrapact) {
					$nbeleves_nivact += $elegrap['nombre'];
				}
			}
			if($nbeleves_nivact>0) {
				$tabEsp[$niveau][] = $espacs_info['espace_id'];
				$tabEspNom[$niveau][] = $espacs_info['espace_nom'];
				$percent_act = round(($nbeleves_nivact * 100 / $nbeleves_nivglob),2);
				array_push($tabPercentPerEsp[$niveau],$percent_act);
			}
			$tabEspODS[$niveau][] = $espacs_info['espace_id'];
			$tabEspNomODS[$niveau][] = $espacs_info['espace_nom'];
			$percent_act = round(($nbeleves_nivact * 100 / $nbeleves_nivglob),2);
			array_push($tabNbPerEspODS[$niveau],$nbeleves_nivact);
			array_push($tabPercentPerEspODS[$niveau],$percent_act);
			$act++;
		}
	}
}
$bctab2 = '<table style="text-align:right;">
<thead><tr><td colspan="'.($act+2).'" style="text-align:center;">'.FDIR_STATS_INF17.'<br>'.FROM2.' '.$affday1.' '.TO2.' '.$affday2.'</td></tr><tr><th></th>';
$bctab2 .= '<th>'.$esp0['valeur'].'</th>';
foreach($espacs as $espacs_info) {
	$bctab2 .= '<th>'.$espacs_info['espace_nom'].'</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;
	$bctab2 .= '<td>'.$tabNbPerEspODS[$niveau][$m].'</td>';
	$tot += $tabNbPerEspODS[$niveau][$m];
	$m++;
	foreach($espacs as $espacs_info) {
		$bctab2 .= '<td>'.$tabNbPerEspODS[$niveau][$m].'</td>';
		$tot += $tabNbPerEspODS[$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_INF18.'<br>'.FROM2.' '.$affday1.' '.TO2.' '.$affday2.'</td></tr><tr><th></th>';
$bctab3 .= '<th>'.$esp0['valeur'].'</th>';
foreach($espacs as $espacs_info) {
	$bctab3 .= '<th>'.$espacs_info['espace_nom'].'</th>';
}
$bctab3 .= '<th>'.TOTAL.'</th></tr></thead><tbody>';
$w=1;
$nivi=0;
foreach($tabDebniveau as $niveau) {
	$bctab3 .= '<tr><td>'.$tabNiveau[$nivi].'</td>';
	$m=0;
	$bctab3 .= '<td>'.number_format((float)$tabPercentPerEspODS[$niveau][$m],2,'.','').'</td>';
	$m++;
	foreach($espacs as $espacs_info) {
		$bctab3 .= '<td>'.number_format((float)$tabPercentPerEspODS[$niveau][$m],2,'.','').'</td>';
		$m++;
	}
	$bctab3 .= '<td>100.00</td></tr>';
	$w++;
	$nivi++;
}	
$bctab3 .= '</tbody></table>';

$i=0;
foreach($tabDebniveau as $niveau) { ?>
	<div id="wrapper" class="statcadre">
	<canvas id="chart_percentperesp<?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($tabEspNom[$niveau]); ?>;
	    const data = {
	      labels: labels,
	      datasets: [{
	            data: <?php echo json_encode($tabPercentPerEsp[$niveau]); ?>,
	            backgroundColor: <?php echo json_encode($basicColors); ?>,
	            borderColor: <?php echo json_encode($basicColors); ?>,
	        }]
	    };
	new Chart(
	    document.getElementById('chart_percentperesp<?php echo $niveau; ?>'),
	    {
	    type: 'pie',
	    data : data,
	    options: {
	        plugins: {
	            title: {
	                display: true,
	                text: "<?php echo FDIR_STATS_INF16.' en '.$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; 
?>