<?php
$i=1;$count_activ=1;
$tabWeeks = array();
foreach (new DatePeriod($jourP1date, new DateInterval('P7D') /* pas de sept jours */, $jourP2date) as $dt) {
	$week = $dt->format('oW');
	array_push($tabWeeks, $week);
}
$tabEspNom[$i] = array();
if(isset($_SESSION['espace0'])||$filtre_espaces=="") {
	$tabEspNom[$i] = $esp0['valeur'];
	$tab[$i] = array();
	$tabNb[$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_actglob = mysqli_num_rows(mysqli_query($bdd,"SELECT freq.freq_id FROM ".$prefix."_freq freq WHERE freq.date_freq >= '".$dt->format('Y-m-d')."' AND freq.date_freq <= '".$dateend."' ".$filtre_activs.""));
		$nbeleves_act = mysqli_num_rows(mysqli_query($bdd,"SELECT freq.freq_id FROM ".$prefix."_freq freq WHERE freq.date_freq >= '".$dt->format('Y-m-d')."' AND freq.date_freq <= '".$dateend."' AND (espace_id = '0' OR espace_id IS NULL) ".$filtre_activsonly.""));
		if($grappes_check==1) {
			$elegrap_nbglob = mysqli_query($bdd,"SELECT nombre FROM ".$prefix."_freqgrappes WHERE date_freq >= '".$dt->format('Y-m-d')."' AND date_freq <= '".$dateend."' AND passage = '0' ".$filtre_activs."");
			$elegrap_nb = mysqli_query($bdd,"SELECT nombre FROM ".$prefix."_freqgrappes WHERE date_freq >= '".$dt->format('Y-m-d')."' AND date_freq <= '".$dateend."' AND passage = '0' AND (espace_id = '0' OR espace_id IS NULL) ".$filtre_activsonly."");
			foreach($elegrap_nbglob as $elegrap1) {
				$nbeleves_actglob += $elegrap1['nombre'];
			}
			foreach($elegrap_nb as $elegrap2) {
				$nbeleves_act += $elegrap2['nombre'];
			}
		}
		if($nbeleves_actglob!=0) {
			$percent_act = round(($nbeleves_act * 100 / $nbeleves_actglob),2);
			array_push($tab[$i],$percent_act);
			array_push($tabNb[$i],$nbeleves_act);
			array_push($tabColors[$i],$basicColors[$i-1]);
		}
		else { 
			array_push($tab[$i],0);
			array_push($tabNb[$i],0);
			array_push($tabColors[$i],$basicColors[$i-1]);
		}
	}
	$i++;$count_activ++;
}
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
		$tabEspNom[$i] = $espacs_info['espace_nom'];
		$tab[$i] = array();
		$tabNb[$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_actglob = mysqli_num_rows(mysqli_query($bdd,"SELECT freq.freq_id FROM ".$prefix."_freq freq WHERE freq.date_freq >= '".$dt->format('Y-m-d')."' AND freq.date_freq <= '".$dateend."' ".$filtre_activs.""));
			$nbeleves_act = mysqli_num_rows(mysqli_query($bdd,"SELECT freq.freq_id FROM ".$prefix."_freq freq WHERE freq.date_freq >= '".$dt->format('Y-m-d')."' AND freq.date_freq <= '".$dateend."' AND espace_id = '".$esp_id."' ".$filtre_activsonly.""));
			if($grappes_check==1) {
				$elegrap_nbglob = mysqli_query($bdd,"SELECT nombre FROM ".$prefix."_freqgrappes WHERE date_freq >= '".$dt->format('Y-m-d')."' AND date_freq <= '".$dateend."' AND passage = '0' ".$filtre_activs."");
				$elegrap_nb = mysqli_query($bdd,"SELECT nombre FROM ".$prefix."_freqgrappes WHERE date_freq >= '".$dt->format('Y-m-d')."' AND date_freq <= '".$dateend."' AND passage = '0' AND espace_id = '".$esp_id."' ".$filtre_activsonly."");
				foreach($elegrap_nbglob as $elegrap1) {
					$nbeleves_actglob += $elegrap1['nombre'];
				}
				foreach($elegrap_nb as $elegrap2) {
					$nbeleves_act += $elegrap2['nombre'];
				}
			}
			if($nbeleves_actglob!=0) {
				$percent_act = round(($nbeleves_act * 100 / $nbeleves_actglob),2);
				array_push($tab[$i],$percent_act);
				array_push($tabNb[$i],$nbeleves_act);
				array_push($tabColors[$i],$basicColors[$i-1]);
			}
			else { 
				array_push($tab[$i],0);
				array_push($tabNb[$i],0);
				array_push($tabColors[$i],$basicColors[$i-1]);
			}
		}
		$i++;$count_activ++;
	}
}
$bctab6 = '<table style="text-align:right;">
<thead><tr><td colspan="'.($count_activ+2).'" style="text-align:center;">'.FDIR_STATS_INF12.'<br>'.FROM2.' '.$affday1.' '.TO2.' '.$affday2.'</td></tr><tr><th></th>';
$bctab6 .= '<th>'.$esp0['valeur'].'</th>';
foreach($espacs as $espacs_info) {
	$bctab6 .= '<th>'.$espacs_info['espace_nom'].'</th>';
}
$bctab6 .= '<th>'.TOTAL.'</th></tr></thead><tbody>';
$w=0;
foreach($tabWeeks as $weekname) {
	$bctab6 .= '<tr><td>'.$weekname.'</td>';
	$m=1;
	$tot = 0;
	$bctab6 .= '<td>'.$tabNb[$m][$w].'</td>';
	$tot += $tabNb[$m][$w];
	$m++;
	foreach($espacs as $espacs_info) {
		$bctab6 .= '<td>'.$tabNb[$m][$w].'</td>';
		$tot += $tabNb[$m][$w];
		$m++;		
	}
	$bctab6 .= '<td>'.$tot.'</td></tr>';
	$w++;
}	
$bctab6 .= '</tbody></table>';
$bctab7 = '<table style="text-align:right;">
<thead><tr><td colspan="'.($count_activ+2).'" style="text-align:center;">'.FDIR_STATS_INF13.'<br>'.FROM2.' '.$affday1.' '.TO2.' '.$affday2.'</td></tr><tr><th></th>';
$bctab7 .= '<th>'.$esp0['valeur'].'</th>';
foreach($espacs as $espacs_info) {
	$bctab7 .= '<th>'.$espacs_info['espace_nom'].'</th>';
}
$bctab7 .= '<th>'.TOTAL.'</th></tr></thead><tbody>';
$w=0;
foreach($tabWeeks as $weekname) {
	$bctab7 .= '<tr><td>'.$weekname.'</td>';
	$m=1;
	$bctab7 .= '<td>'.number_format((float)$tab[$m][$w],2,'.','').'</td>';
	$m++;
	foreach($espacs as $espacs_info) {
		$bctab7 .= '<td>'.number_format((float)$tab[$m][$w],2,'.','').'</td>';
		$m++;
	}
	$bctab7 .= '<td>100.00</td></tr>';
	$w++;
}	
$bctab7 .= '</tbody></table>';
?>
<div id="wrapper" class="statcadre">
<canvas id="chart_espperweek" 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($espacs as $espacs_info) {
        	$esp_id = $espacs_info['espace_id']; 
        	if(($filtre_espaces==""||isset($_SESSION['espace0'])||isset($_SESSION['espace'.$esp_id]))) { // on vérifie qu'elle n'est pas décochée ?>
        {
            label: <?php echo json_encode($tabEspNom[$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_activ) { echo ','; } $i++; $j++;} ?> <?php } ?> ]
    };
new Chart(
    document.getElementById('chart_espperweek'),
    {
    type: 'bar',
    data: data,
    options: {
        plugins: {
            title: {
                display: true,
                text: "<?php echo FDIR_STATS_INF14; ?>"
            },
            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 false; // N'affiche pas si la valeur est égale à 0
                },
            },
        },
        responsive: true,
        maintainAspectRatio: false,
        scales: {
            y: {
                stacked: true, // Empiler les barres sur l'axe Y
                ticks: {
                    beginAtZero: true
                },
                max: 100
            },
            x: {
                stacked: true // Empiler les barres sur l'axe X
            }
        }
      }
    }
);
})();
</script>
<?php
echo '<br> <br>'.$bctab6;
$_SESSION['bctabs'] .= '<table></table>'.$bctab6; 
echo '<br> <br>'.$bctab7;
$_SESSION['bctabs'] .= '<table></table>'.$bctab7;  
?>