<?php
include('edt_stats_arrays.php');

// Type d'exclusions
$tabPercentPerExcluCause = array();
$tabExcluCause = array();
$exclu_causes = mysqli_query($bdd,"SELECT causes.exclucause_txt, causes.exclucause_id FROM ".$prefix."_exclucauses causes INNER JOIN ".$prefix."_exclusions exclusions ON exclusions.exclucause_id = causes.exclucause_id GROUP BY causes.exclucause_id");
$exclusions = mysqli_query($bdd,"SELECT exclusion_id FROM ".$prefix."_exclusions WHERE exclucause_id <> '0' AND date_exclusion >= '".$day1."' AND date_exclusion <= '".$day2."'");
if(mysqli_num_rows($exclusions)>0) {
	echo '<p>'.mysqli_num_rows($exclusions).FSTATS_EXC1.'</p>';
	$bctab4 = '<table style="text-align:right;">
		<thead><tr><td colspan="3" style="text-align:center;">'.FSTATS_EXC2.'<br>du '.$affday1.' au '.$affday2.'</td></tr><tr><th></th><th>'.NUMBER.'</th><th>%</th></tr></thead><tbody>';
	foreach($exclu_causes as $cause) {
		$nbeleves_cause = mysqli_query($bdd,"SELECT exclu.exclusion_id FROM ".$prefix."_exclusions exclu WHERE exclu.date_exclusion >= '".$day1."' AND exclu.date_exclusion <= '".$day2."' AND exclu.exclucause_id = '".$cause['exclucause_id']."'");
		$nbeleves = mysqli_num_rows($nbeleves_cause);
		if($nbeleves>0) {
			$percent_cause = round(($nbeleves*100/mysqli_num_rows($exclusions)),2);
			array_push($tabPercentPerExcluCause, $percent_cause);
			array_push($tabExcluCause, $cause['exclucause_txt']);
			$bctab4 .= '<tr><td>'.$cause['exclucause_txt'].'</td><td>'.$nbeleves.'</td><td>'.number_format((float)$percent_cause,2,'.','').'</td></tr>';
		}		
	}
	$bctab4 .= '<tr><td>'.TOTAL.'</td><td>'.mysqli_num_rows($exclusions).'</td><td>100.00</td></tr></tbody></table>';	
	?>
	<div id="wrapper" class="statcadre">
	<canvas id="chart_percentperexclucause" class="charts" width="400" height="400"></canvas>
	</div>
	<script type="text/javascript">
	(async function() {
	    
	    Chart.register(ChartDataLabels);
	    const labels = <?php echo json_encode($tabExcluCause); ?>;
	    const data = {
	      labels: labels,
	      datasets: [{
				data: <?php echo json_encode($tabPercentPerExcluCause); ?>,
				backgroundColor: <?php echo json_encode($basicColors); ?>,
				borderColor: <?php echo json_encode($basicColors); ?>,
			}]
	    };
	new Chart(
	    document.getElementById('chart_percentperexclucause'),
	    {
	    type: 'pie',
	    data : data,
	    options: {
	        plugins: {
	            title: {
	                display: true,
	                text: "<?php echo FSTATS_EXC3; ?>"
	            },
	            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
	echo '<br> <br>'.$bctab4;	
	$_SESSION['bctabs'] .= '<table></table>'.$bctab4;

	$i=1;$count_exclu=0;
	$tabWeeks = array();
	$tabNbPerWeek = array();
	foreach (new DatePeriod($jourP1date, new DateInterval('P7D') /* pas de sept jours */, $jourP2date) as $dt) {
		$week = $dt->format('oW');
		$date = $dt->format('Y-m-d');
		$datetoend = strtotime(date("Y-m-d", strtotime($date)) . " +6 day"); // ajouter 6 jours
		$dateend = date('Y-m-d',$datetoend);
		array_push($tabWeeks, $week);
		$nbeleves_exclu = mysqli_num_rows(mysqli_query($bdd,"SELECT exclusion_id FROM ".$prefix."_exclusions WHERE date_exclusion >= '".$dt->format('Y-m-d')."' AND date_exclusion <= '".$dateend."'"));
		array_push($tabNbPerWeek,$nbeleves_exclu);
	}
	$tabExcluNom[$i] = array();
	foreach($exclu_causes as $cause) {
		$tabExcluNom[$i] = $cause['exclucause_txt'];
		$tab[$i] = array();
		$tabColors[$i] = array();
		foreach (new DatePeriod($jourP1date, new DateInterval('P7D') /* pas de sept jours */, $jourP2date) as $dt) {
			$date = $dt->format('Y-m-d');
			$week = $dt->format('oW');
			$datetoend = strtotime(date("Y-m-d", strtotime($date)) . " +6 day"); // ajouter 6 jours
			$dateend = date('Y-m-d',$datetoend);
			$nbeleves_exclu = mysqli_num_rows(mysqli_query($bdd,"SELECT exclusion_id FROM ".$prefix."_exclusions WHERE date_exclusion >= '".$dt->format('Y-m-d')."' AND date_exclusion <= '".$dateend."' AND exclucause_id = '".$cause['exclucause_id']."'"));
			array_push($tab[$i],$nbeleves_exclu);
			array_push($tabColors[$i],$basicColors[$i-1]);
		}
		$i++;$count_exclu++;
	}
	$bctab5 = '<table style="text-align:right;">
	<thead><tr><td colspan="'.($i+1).'" style="text-align:center;">'.FSTATS_EXC4.'<br>'.FROM2.' '.$affday1.' '.TO2.' '.$affday2.'</td></tr><tr><th></th>';
	$nivi=1;
	foreach($exclu_causes as $cause) {
		$bctab5 .= '<th>'.$tabExcluNom[$nivi].'</th>';
		$nivi++;
	}
	$bctab5 .= '<th>'.TOTAL.'</th></tr></thead><tbody>';
	$w=0;
	$tot=0;
	foreach($tabWeeks as $weekname) {
		$bctab5 .= '<tr><td>'.$weekname.'</td>';
		$m=1;
		foreach($exclu_causes as $cause) {
			$bctab5 .= '<td>'.$tab[$m][$w].'</td>';
			$m++;
		}
		$bctab5 .= '<td>'.$tabNbPerWeek[$w].'</td></tr>';
		$tot+=$tabNbPerWeek[$w];
		$w++;
	}	
	$bctab5 .= '<tr><td>'.TOTAL.'</td><td colspan="'.($i-1).'"></td><td>'.$tot.'</td></tr></tbody></table>';
	
	?>
	<div id="wrapper" class="statcadre">
		<canvas id="chart_excluperweek" class="charts" width="600" height="300"></canvas>
		</div>
		<script type="text/javascript">
		(async function() {
		    
		    Chart.register(ChartDataLabels);
		    const labels = <?php echo json_encode($tabWeeks); ?>;
		    const data = {
		      labels: labels,
		      datasets: [ 
		        <?php $i=1;$j=1;
		        foreach($exclu_causes as $cause) { 
		        	if($i>0) { // on vérifie qu'elle n'est pas décochée ?>
		        {
		            label: <?php echo json_encode($tabExcluNom[$i]); ?>,
		            data: <?php echo json_encode($tab[$i]); ?>,
		            backgroundColor: <?php echo json_encode($tabColors[$i]); ?>,
		            borderColor: <?php echo json_encode($tabColors[$i]); ?>,
		            borderWidth: 1
		        } <?php if($j<$count_exclu) { echo ','; } $i++; $j++;} ?> <?php } ?> ]
		    };
		new Chart(
		    document.getElementById('chart_excluperweek'),
		    {
		    type: 'bar',
		    data: data,
		    options: {
		        plugins: {
		            title: {
		                display: true,
		                text: "<?php echo FSTATS_EXC4;?>"
		            },
		            legend: {
		                display:false
		            },
		            tooltip : {
		                mode: 'point',
		                intersect: false,
		              }  ,    
		            datalabels: {
		              display: true, // Affiche les étiquettes de données
		              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,
		        scales: {
					xAxes: [{
						stacked: true,
						ticks: {
							beginAtZero:true
						}
					}],
					yAxes: [{
						stacked: true,
						ticks: {
							beginAtZero:true
						}
					}]
				},
		      }
		    }
		);
		})();
		</script>
	
<?php 
	echo '<br>'.$bctab5;	
	$_SESSION['bctabs'] .= '<table></table>'.$bctab5;
}

// Type de limitations
$tabPercentPerLimitType = array();
$tabLimitType = array();
$limit_types = mysqli_query($bdd,"SELECT types.limits_txt, types.limittxt_id FROM ".$prefix."_limitstxt types INNER JOIN ".$prefix."_limits limits ON limits.limittxt_id = types.limittxt_id GROUP BY types.limittxt_id");
$limitations = mysqli_query($bdd,"SELECT limit_id FROM ".$prefix."_limits WHERE date_debut >= '".$day1."' AND date_debut <= '".$day2."'");
if(mysqli_num_rows($limitations)>0) {
	echo '<br><p>'.mysqli_num_rows($limitations).FSTATS_EXC5.'</p>';
	$bctab6 = '<table style="text-align:right;">
	<thead><tr><td colspan="3" style="text-align:center;">'.FSTATS_EXC6.'<br>du '.$affday1.' au '.$affday2.'</td></tr><tr><th></th><th>'.NUMBER.'</th><th>%</th></tr></thead><tbody>';
	foreach($limit_types as $type) {
		$nbeleves_type = mysqli_query($bdd,"SELECT limit_id FROM ".$prefix."_limits WHERE date_debut >= '".$day1."' AND date_debut <= '".$day2."' AND limittxt_id = '".$type['limittxt_id']."' ");
		$nbeleves = mysqli_num_rows($nbeleves_type);
		if($nbeleves>0) {
			$percent_type = round((($nbeleves*100)/mysqli_num_rows($limitations)),2);
			array_push($tabPercentPerLimitType, $percent_type);
			array_push($tabLimitType, $type['limits_txt']);
			$bctab6 .= '<tr><td>'.$type['limits_txt'].'</td><td>'.$nbeleves.'</td><td>'.number_format((float)$percent_type,2,'.','').'</td></tr>';
		}			
	}
	$bctab6 .= '<tr><td>'.TOTAL.'</td><td>'.mysqli_num_rows($limitations).'</td><td>100.00</td></tr></tbody></table>';
	?>
	<div id="wrapper" class="statcadre">
	<canvas id="chart_percentperlimittype" class="charts" width="400" height="400"></canvas>
	</div>
	<script type="text/javascript">
	(async function() {
	    
	    Chart.register(ChartDataLabels);
	    const labels = <?php echo json_encode($tabLimitType); ?>;
	    const data = {
	      labels: labels,
	      datasets: [{
				data: <?php echo json_encode($tabPercentPerLimitType); ?>,
				backgroundColor: <?php echo json_encode($basicColors); ?>,
				borderColor: <?php echo json_encode($basicColors); ?>,
			}]
	    };
	new Chart(
	    document.getElementById('chart_percentperlimittype'),
	    {
	    type: 'pie',
	    data : data,
	    options: {
	        plugins: {
	            title: {
	                display: true,
	                text: "<?php echo FSTATS_EXC7; ?>"
	            },
	            legend: {
	                display:true
	            },
	            tooltip : {
	                mode: 'point',
	                intersect: false,
	              }  ,    
	            datalabels: {
	              display: true, // Affiche les étiquettes de données
	              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
	echo '<br> <br>'.$bctab6;	
	$_SESSION['bctabs'] .= '<table></table>'.$bctab6;

	$i=1;$count_limit=0;
	$tabWeeks = array();
	$tabNbPerWeek = array();
	foreach (new DatePeriod($jourP1date, new DateInterval('P7D') /* pas de sept jours */, $jourP2date) as $dt) {
		$week = $dt->format('oW');
		$date = $dt->format('Y-m-d');
		$datetoend = strtotime(date("Y-m-d", strtotime($date)) . " +6 day"); // ajouter 6 jours
		$dateend = date('Y-m-d',$datetoend);
		array_push($tabWeeks, $week);
		$nbeleves_limit = mysqli_num_rows(mysqli_query($bdd,"SELECT limit_id FROM ".$prefix."_limits WHERE date_debut >= '".$dt->format('Y-m-d')."' AND date_debut <= '".$dateend."'"));
		array_push($tabNbPerWeek,$nbeleves_limit);
	}
	$tabLimitsNom[$i] = array();
	foreach($limit_types as $type) {
		$tabLimitsNom[$i] = $type['limits_txt'];
		$tab[$i] = array();
		$tabColors[$i] = array();
		foreach (new DatePeriod($jourP1date, new DateInterval('P7D') /* pas de sept jours */, $jourP2date) as $dt) {
			$date = $dt->format('Y-m-d');
			$week = $dt->format('oW');
			$datetoend = strtotime(date("Y-m-d", strtotime($date)) . " +6 day"); // ajouter 6 jours
			$dateend = date('Y-m-d',$datetoend);
			$nbeleves_limit = mysqli_num_rows(mysqli_query($bdd,"SELECT limit_id FROM ".$prefix."_limits WHERE date_debut >= '".$dt->format('Y-m-d')."' AND date_debut <= '".$dateend."' AND limittxt_id = '".$type['limittxt_id']."'"));
			array_push($tab[$i],$nbeleves_limit);
			array_push($tabColors[$i],$basicColors[$i-1]);
		}
		$i++;$count_limit++;
	}
	$bctab7 = '<table style="text-align:right;">
	<thead><tr><td colspan="'.($i+1).'" style="text-align:center;">'.FSTATS_EXC8.'<br>'.FROM2.' '.$affday1.' '.TO2.' '.$affday2.'</td></tr><tr><th></th>';
	$nivi=1;
	foreach($limit_types as $type) {
		$bctab7 .= '<th>'.$tabLimitsNom[$nivi].'</th>';
		$nivi++;
	}
	$bctab7 .= '<th>'.TOTAL.'</th></tr></thead><tbody>';
	$w=0;
	$tot=0;
	foreach($tabWeeks as $weekname) {
		$bctab7 .= '<tr><td>'.$weekname.'</td>';
		$m=1;
		foreach($limit_types as $type) {
			$bctab7 .= '<td>'.$tab[$m][$w].'</td>';
			$m++;
		}
		$bctab7 .= '<td>'.$tabNbPerWeek[$w].'</td></tr>';
		$tot+=$tabNbPerWeek[$w];
		$w++;
	}	
	$bctab7 .= '<tr><td>'.TOTAL.'</td><td colspan="'.($i-1).'"></td><td>'.$tot.'</td></tr></tbody></table>';
	?>
	<div id="wrapper" class="statcadre">
	<canvas id="chart_limitperweek" class="charts" width="400" height="200"></canvas>
	</div>
	<script>
	var ctx = document.getElementById("chart_limitperweek");
	var myChart = new Chart(ctx, {
	    type: 'bar',
	    data: {
	        labels: <?php echo json_encode($tabWeeks); ?>,
	        datasets: [ 
	        <?php $i=1;$j=1;
	        foreach($limit_types as $type) { 
	        	if($i>0) { // on vérifie qu'elle n'est pas décochée ?>
	        {
	            label: <?php echo json_encode($tabLimitsNom[$i]); ?>,
	            data: <?php echo json_encode($tab[$i]); ?>,
	            backgroundColor: <?php echo json_encode($tabColors[$i]); ?>,
	            borderColor: <?php echo json_encode($tabColors[$i]); ?>,
	            borderWidth: 1
	        } <?php if($j<$count_limit) { echo ','; } $i++; $j++;} ?> <?php } ?> ]
	    },
	    options: {
	       title: {
				display: true,
				text: "<?php echo FSTATS_EXC8; ?>"
			},
			tooltips: {
				mode: 'index',
				intersect: false
			},
			responsive: true,
			scales: {
				xAxes: [{
					stacked: true,
					ticks: {
						beginAtZero:true
					}
				}],
				yAxes: [{
					stacked: true,
					ticks: {
						beginAtZero:true
					}
				}]
			}
	    }
	});
	</script>
<?php 
	echo '<br> <br>'.$bctab7;	
	$_SESSION['bctabs'] .= '<table></table>'.$bctab7;
} 
?>