<?php

echo FSTATS_TIT14;

if($grappes_check==1) {
	echo FSTATS_AVERT1;
}

include('freq_stats_form.php');

echo '<h2>'.FROM21.' '.$affday1.' '.TO2.' '.$affday2.'</h2>';

echo '<p>'.FSTATS_TIT21.' ';
$totalfreq_nb = mysqli_num_rows(mysqli_query($bdd,"SELECT freq.freq_id FROM ".$prefix."_freq freq WHERE freq.date_freq >= '".$day1."' AND freq.date_freq <= '".$day2."'  AND user_id != '' ".$filtre_activs.""));
if($grappes_check==1) {
	$elegrap_nb = mysqli_query($bdd,"SELECT nombre FROM ".$prefix."_freqgrappes WHERE date_freq >= '".$day1."' AND date_freq <= '".$day2."' AND passage = '0'  AND user_id != '' ".$filtre_activs."");
	while($elegrap = mysqli_fetch_assoc($elegrap_nb)) {
		$totalfreq_nb += $elegrap['nombre'];
	}
}
$_SESSION['bctabs']='';
if($totalfreq_nb==0) {
	echo FSTATS_INF1;
}
else {
echo $totalfreq_nb;
echo ' '.ELEVS1.'.</p>';

//récupération des niveaux et couleurs par niveau
include('freq_stats_nivcolors.php'); 
require_once('./include/basiccolors.php');

$users = mysqli_query($bdd,"SELECT * FROM ".$prefix."_user");
$tabUsers = array();
$tabUsersName = array();
$tabNbByUser = array();
$tabPercentByUser = array();
$i=0;
foreach($users as $user_id) {
	$bctab1 = '<table style="text-align:right;">
		<thead><tr><td colspan="3" style="text-align:center;">'.FSTATS_INF4.'<br>'.FROM2.' '.$affday1.' '.TO2.' '.$affday2.'</td></tr><tr><th>'.USER.'</th><th>'.NUMBER.'</th><th>%</th></tr></thead><tbody>';
	$nb_by_user = mysqli_num_rows(mysqli_query($bdd,"SELECT * FROM ".$prefix."_freq freq WHERE freq.date_freq >= '".$day1."' AND freq.date_freq <= '".$day2."' AND user_id = '".$user_id['id']."' ".$filtre_activs.""));
	if($nb_by_user>0) {
		array_push($tabUsers,$user_id['id']);
		if($user_id['prenom']!=''&&$user_id['nom']!='') {
			array_push($tabUsersName, $user_id['prenom'].' '.$user_id['nom']);
			$user_name = $user_id['prenom'].' '.$user_id['nom'];
		}
		else if($user_id['nom']!='') {
			array_push($tabUsersName, $user_id['nom']);
			$user_name = $user_id['nom'];
		}
		else if($user_id['prenom']!='') {
			array_push($tabUsersName, $user_id['prenom']);
			$user_name = $user_id['prenom'];
		}
		else {
			array_push($tabUsersName, $user_id['login']);
			$user_name = $user_id['login'];
		}
		array_push($tabNbByUser, $nb_by_user);
		$percent = round(($nb_by_user * 100 / $totalfreq_nb),2);
		array_push($tabPercentByUser, $percent);
		
		$i++;
	}
	
}
echo '<h3>'.FSTATS_USER1.'</h3>';
$j=0;
foreach($tabNbByUser as $eachUser) {
	echo '<p>'.$tabUsersName[$j].' : '.$tabNbByUser[$j].' visites.</p>';
	$bctab1 .= '<tr><td>'.$tabUsersName[$j].'</td><td>'.$tabNbByUser[$j].'</td><td>'.number_format((float)$tabPercentByUser[$j],2,'.','').'</td></tr>';
	$j++;
}
$bctab1 .= '<tr><td>'.TOTAL.'</td><td>'.$totalfreq_nb.'</td><td>100.00</td></tr></tbody></table>';

echo '</article><article id="artleft" class="freqsep">';?>
<div id="wrapper" class="statcadre">
<canvas id="chart_percentperuser" class="charts" width="400" height="400"></canvas>
</div>
<script type="text/javascript">
(async function() {
    
    Chart.register(ChartDataLabels);
    const labels = <?php echo json_encode($tabUsersName); ?>;
    const data = {
      labels: labels,
      datasets: [{
            data: <?php echo json_encode($tabPercentByUser); ?>,
            backgroundColor: <?php echo json_encode($basicColors); ?>,
            borderColor: <?php echo json_encode($basicColors); ?>,
        }]
    };
new Chart(
    document.getElementById('chart_percentperuser'),
    {
    type: 'pie',
    data : data,
    options: {
        plugins: {
            title: {
                display: true,
                text: "<?php echo FSTATS_USER2; ?>"
            },
            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,
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        },
      }
    }
);
})();
</script>

<?php
echo '<br> <br>'.$bctab1;
$_SESSION['bctabs'] .= $bctab1;
//fréquentation par utilisateur par niveau :
$i=1;$count_activ=0;
foreach($tabUsers as $usersb) {
	$tabNbPerNiveau[$i] = array();
	$tabPercentPerNiveau[$i] = array();
	$tabColors[$i] = array();
	foreach($tabDebniveau as $divdeb) {
		$total_niv = 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 '".$divdeb."%'  AND user_id != '' ".$filtre_activs.""));
		$nbeleves_niv = mysqli_query($bdd,"SELECT freq.freq_id FROM ".$prefix."_freq freq WHERE date_freq >= '".$day1."' AND date_freq <= '".$day2."' AND division LIKE '".$divdeb."%'  AND user_id = '".$usersb."' ".$filtre_activs."");
		$nbeleves = mysqli_num_rows($nbeleves_niv);
		if($grappes_check==1) {
			$elegrap_nb = mysqli_query($bdd,"SELECT nombre FROM ".$prefix."_freqgrappes WHERE date_freq >= '".$day1."' AND date_freq <= '".$day2."' AND niveau = '".$divdeb."' AND passage = '0' AND user_id = '".$usersb."' ".$filtre_activs."");
			while($elegrap = mysqli_fetch_assoc($elegrap_nb)) {
				$nbeleves += $elegrap['nombre'];
			}
		}
		array_push($tabNbPerNiveau[$i], $nbeleves);
		if($total_niv>0) {
			$percent = round(($nbeleves * 100 / $total_niv),2);
		}
		else { $percent = '0.00'; }
		array_push($tabPercentPerNiveau[$i], $percent);
		array_push($tabColors[$i],$basicColors[$i-1]);
	}
	$i++;$count_activ++;
}
$bctab2 = '<table style="text-align:right;">
<thead><tr><td colspan="'.($i+2).'" style="text-align:center;">'.FSTATS_USER3.'<br>'.FROM2.' '.$affday1.' '.TO2.' '.$affday2.'</td></tr><tr><th></th>';
$nivi=0;
foreach($tabDebniveau as $divdeb) {
	$bctab2 .= '<th>'.$tabNiveau[$nivi].'</th>';
	$nivi++;
}
$bctab2 .= '</tr></thead><tbody>';
$w=1;
foreach($tabUsers as $usersb) {
	$bctab2 .= '<tr><td>'.$tabUsersName[($w-1)].'</td>';
	$m=0;$tot=0;
	foreach($tabDebniveau as $divdeb) {
		$bctab2 .= '<td>'.number_format((float)$tabPercentPerNiveau[$w][$m],2,'.','').'</td>';
		$m++;
	}
	$bctab2 .= '</tr>';
	$w++;
}	
$bctab2 .= '</tbody></table>';
$bctab3 = '<table style="text-align:right;">
<thead><tr><td colspan="'.($i+2).'" style="text-align:center;">'.FSTATS_USER4.'<br>'.FROM2.' '.$affday1.' '.TO2.' '.$affday2.'</td></tr><tr><th></th>';
$nivi=0;
foreach($tabDebniveau as $divdeb) {
	$bctab3 .= '<th>'.$tabNiveau[$nivi].'</th>';
	$nivi++;
}
$bctab3 .= '<th>'.TOTAL.'</th></tr></thead><tbody>';
$w=1;
foreach($tabUsers as $usersb) {
	$bctab3 .= '<tr><td>'.$tabUsersName[($w-1)].'</td>';
	$m=0;$tot=0;
	foreach($tabDebniveau as $divdeb) {
		$bctab3 .= '<td>'.$tabNbPerNiveau[$w][$m].'</td>';
		$tot += $tabNbPerNiveau[$w][$m];
		$m++;
	}
	$bctab3 .= '<td>'.$tot.'</td></tr>';
	$w++;
}	
$bctab3 .= '<tr><td>'.TOTAL.'</td><td colspan="'.$nivi.'"></td><td>'.$totalfreq_nb.'</td></tr></tbody></table>';
?>
<div id="wrapper" class="statcadre">
<canvas id="chart_pcpernivperuser" class="charts" width="600" height="300"></canvas>
</div>
<script type="text/javascript">
(async function() {
    
    Chart.register(ChartDataLabels);
    const labels = <?php echo json_encode($tabNiveau); ?>;
    const data = {
      labels: labels,
      datasets: [ 
        <?php $i=1;$j=1;
        foreach($tabUsers as $usersb) { ?>
        {
            label: <?php echo json_encode($tabUsersName[$i-1]); ?>,
            data: <?php echo json_encode($tabPercentPerNiveau[$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++;} ?> ]
    };
new Chart(
    document.getElementById('chart_pcpernivperuser'),
    {
    type: 'bar',
    data: data,
    options: {
        plugins: {
            title: {
                display: true,
                text: "<?php echo FSTATS_USER5; ?>"
            },
            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>'.$bctab2;
$_SESSION['bctabs'] .= '<table></table>'.$bctab2;
?>

<div id="wrapper" class="statcadre">
<canvas id="chart_nbpernivperuser" class="charts" width="600" height="300"></canvas>
</div>
<script type="text/javascript">
(async function() {
    
    Chart.register(ChartDataLabels);
    const labels = <?php echo json_encode($tabNiveau); ?>;
    const data = {
      labels: labels,
      datasets: [ 
        <?php $i=1;$j=1;
        foreach($tabUsers as $usersb) { ?>
        {
            label: <?php echo json_encode($tabUsersName[$i-1]); ?>,
            data: <?php echo json_encode($tabNbPerNiveau[$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++;} ?> ]
    };
new Chart(
    document.getElementById('chart_nbpernivperuser'),
    {
    type: 'bar',
    data: data,
    options: {
        plugins: {
            title: {
                display: true,
                text: "<?php echo FSTATS_USER6; ?>"
            },
            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,
        maintainAspectRatio: false,
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        },
      }
    }
);
})();
</script>

<?php 
} 
echo '<br> <br>';
if(isset($bctab3)) { echo $bctab3; }
$_SESSION['bctabs'] .= '<table></table>';
if(isset($bctab3)) { $_SESSION['bctabs'] .= $bctab3; }
echo '<br> <a onclick="submitods();" id="preview-ods"><i class="fa-solid fa-file-export" style="font-size:1.5em;"></i> '.STATS_DL1.'</a>';
if(isset($_POST['haveods'])) {
	include('stats_ods_loader.php');
}
echo '<form id="loadods" action="db/proc/stats/stats_ods_loader.php" method="post"><input type="hidden" name="haveods" value="1" /></form>';

echo '<script type="text/javascript">
function submitods(){
	$("#loadods").submit()
}
</script>';
?>