<?php
// Vérification de la dispo de ces stats
$i=1;
foreach($freq_nb as $addfreq) {
//foreach($an as $eachyear) {
	if(substr($_SESSION['nb_year'],1,1)=='p') { $ancheck = $an[$i+1]; }
	else { $ancheck = $an[$i]; }
	$eff_divs = mysqli_num_rows(mysqli_query($bdd,"SELECT * FROM ".$prefix."_etab_effectifs WHERE anneesco = '".$ancheck."'"));
	if($eff_divs==0) { $dispo = '3'; } else { $dispo = '1'; }
	$nbeleves_niv = mysqli_num_rows(mysqli_query($bdd,"SELECT freq.freq_id FROM ".$prefix."_freq freq WHERE freq.date_freq >= '".$firstday[$i]."' AND freq.date_freq <= '".$lastday[$i]."' ".$filtre_activs." AND freq.eleves_id = 0"));
	if($nbeleves_niv>0) { $dispo = '2'; }
	$i++;
}
if($dispo=='3') {
	echo '<p class="max-width" style="margin-top:30px;"><b>'.FDIR_STATS_EVOL4.'</b><br>'.FDIR_STATS_EVOL5.'<a href="param.php?page=etab">param.php?page=etab</a>.</p>';
}
else if($dispo=='2') {
	echo '<p class="max-width" style="margin-top:30px;"><b>'.FDIR_STATS_EVOL4.'</b><br>'.FDIR_STATS_EVOL6.'</p>';
}
else if($dispo=='1') {
	// fréquentation par niveau par an :
	$i=1;
	foreach($an as $eachyear) {
		if(substr($_SESSION['nb_year'],1,1)=='p'&&$eachyear[$i]==0) { $i++; }
		else {
			$eff_divs = mysqli_query($bdd,"SELECT * FROM ".$prefix."_etab_effectifs WHERE anneesco = '".$an[$i]."'");
			$eff_glob=0;
			foreach($eff_divs as $eff_div) {
				$eff_glob += $eff_div['effectif'];
			}
			$tab[$i] = array();
			$nbeleves_niv = mysqli_query($bdd,"SELECT freq.freq_id FROM ".$prefix."_freq freq WHERE freq.date_freq >= '".$firstday[$i]."' AND freq.date_freq <= '".$lastday[$i]."' ".$filtre_activs." GROUP BY freq.eleves_id");
			$nbeleves = mysqli_num_rows($nbeleves_niv);
			$percent_act = round(($nbeleves * 100 / $eff_glob),2);
			if($percent_act>100) {$percent_act=100;}
			array_push($tab[$i], $percent_act);
			foreach ($tabDebniveau as $divdeb) {
				$nivcolor = mysqli_query($bdd,"SELECT bgcolor FROM ".$prefix."_edtnivcolor WHERE niveau = '".$divdeb."'");
				$nivcolor_info = mysqli_fetch_assoc($nivcolor);
				$tabColor[$i] = $nivcolor_info['bgcolor'];
				$eff_divs = mysqli_query($bdd,"SELECT * FROM ".$prefix."_etab_effectifs WHERE anneesco = '".$an[$i]."' AND division LIKE '".$divdeb."%'");
				$eff_nivglob=0;
				foreach($eff_divs as $eff_div) {
					$eff_nivglob += $eff_div['effectif'];
				}
				$nbeleves_niv = mysqli_query($bdd,"SELECT freq.freq_id FROM ".$prefix."_freq freq WHERE freq.date_freq >= '".$firstday[$i]."' AND freq.date_freq <= '".$lastday[$i]."' AND division LIKE '".$divdeb."%' ".$filtre_activs." GROUP BY freq.eleves_id");
				$nbeleves = mysqli_num_rows($nbeleves_niv);
				if($eff_nivglob!=0) {
					$percent_act = round(($nbeleves * 100 / $eff_nivglob),2);
				}
				else { $percent_act = 0; }
				if($percent_act>100) {$percent_act=100;}
				array_push($tab[$i], $percent_act);
			}
			$i++;
		}
	}
	$bctab3 = '<table style="text-align:right;">
	<thead><tr><td colspan="'.($i+3).'" style="text-align:center;">'.FDIR_STATS_EVOL3.'</td></tr><tr><th>'.YEAR.'</th><th>'.TOTAL.'</th>';
	$nivi=0;
	foreach($tabDebniveau as $divdeb) {
		$bctab3 .= '<th>'.$tabNiveau[$nivi].'</th>';
		$nivi++;
	}
	$bctab3 .= '</tr></thead><tbody>';
	$w=1;
	foreach($an as $eachyear) {
		$bctab3 .= '<tr><td>'.$an[$w].'</td>';
		$m=0;$tot=0;
		$bctab3 .= '<td>'.number_format((float)$tab[$w][$m],2,'.','').'</td>';
		$m++;
		foreach($tabDebniveau as $divdeb) {
			$bctab3 .= '<td>'.number_format((float)$tab[$w][$m],2,'.','').'</td>';
			$m++;
		}
		$bctab3 .= '</tr>';
		$w++;
	}	
	$bctab3 .= '</tbody></table>';
	?>
	<div id="wrapper" class="statcadre">
	<canvas id="chart_propperyearperniv" class="charts" width="600" height="300"></canvas>
	</div>
	<script type="text/javascript">
	(async function() {
	    
	    Chart.register(ChartDataLabels);
	    const labels = <?php echo json_encode($taballNiveau); ?>;
	    const data = {
	      labels: labels,
	      datasets: [ 
			<?php 
			if(isset($an[5])) { $i=5; }
			else if(isset($an[4])) { $i=4; }
			else if(isset($an[3])) { $i=3; }
			else { $i=2; }
			$j=1;
			if(substr($_SESSION['nb_year'],1,1)=='a') { $nb_sans=0; } else { $nb_sans=1; $j=2; }
			for($i;$i>$nb_sans;$i--) { ?>
			{
				label: <?php echo json_encode($an[$i]); ?>,
				data: <?php echo json_encode($tab[$i]); ?>,
				backgroundColor: <?php echo json_encode($tabBgallcolor); ?>,
				borderColor: <?php echo json_encode($tabBgallcolor); ?>,
				borderWidth: 1
			} <?php if($j<=count($an)) { echo ','; } $j++;} ?> ]
	    };
	new Chart(
	    document.getElementById('chart_propperyearperniv'),
	    {
	    type: 'bar',
	    data: data,
	    options: {
	        plugins: {
	            title: {
	                display: true,
	                text: "<?php echo FDIR_STATS_EVOL3; ?> (<?php if(isset($an[5])) { $i=5; } else if(isset($an[4])) { $i=4; } else if(isset($an[3])) { $i=3; } else { $i=2; } $j=1; if(substr($_SESSION['nb_year'],1,1)=='a') { $nb_sans=0; } else { $nb_sans=1; $j=2; } for($i;$i>$nb_sans;$i--) { echo $an[$i]; if($j<count($an)) { echo ' - '; } $j++; } ?>)"
	            },
	            legend: {
	    			display:false
	    		},
	            tooltip : {
	                mode: 'point',
	                intersect: false,
	              }  ,    
	            datalabels: {
	              display: true, // Affiche les étiquettes de données
	              color: function(context) {
				        var index = context.dataIndex;
				        var color = '#878787'; // Couleur par défaut

				        // Condition pour déterminer la couleur en fonction de l'index ou d'autres critères
				        if (index === 0) {
				            color = '#fff';
				        } 
				        return color; // Retourne la couleur déterminée
				    },
	              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,
	        scales: {
	            yAxes: [{
	                ticks: {
	                    beginAtZero:true
	                }
	            }]
	        },
	      }
	    }
	);
	})();
	</script>
	<?php
	echo '<br> <br>'.$bctab3;
	$_SESSION['bctabs'] .= '<table></table>'.$bctab3;
}
?>