<?php
/**
 * Template pour les statistiques HC (Hors Champs / calculés)
 * Ex: nombre_nuitees
 * 
 * Variables disponibles:
 * - $idChamp : ID du champ (ex: 'HC_nombre_nuitees')
 * - $libelleChamp : Libellé du champ HC (ex: 'Nombre de nuitées')
 * - $libelleChampVentilation : Libellé du champ de ventilation (ex: 'Nationalité')
 * - $valeursPossibles : Valeurs possibles pour la ventilation + 'Total'
 * - $titleGraph : Titre du graphique
 * - $typeGraph : Type de graphique ('bar', 'line', 'pie')
 * - $valeursStats : Données par valeur de ventilation
 * - $dataGraph : Données pour le graphique (camembert ou barres)
 * - $totalNuitees : Total global des nuitées
 * - $isHC : true
 * - $TOparLogesOuPlaces : 'parLogements' ou 'parPlaces'
 */

// Sécurité : initialiser les variables si non définies
$libelleChampVentilation = isset($libelleChampVentilation) ? $libelleChampVentilation : '';
$valeursStats = isset($valeursStats) ? $valeursStats : array();
$dataGraph = isset($dataGraph) ? $dataGraph : array();
$totalNuitees = isset($totalNuitees) ? $totalNuitees : 0;
$hasVentilation = !empty($libelleChampVentilation);
?>

<style>
/* Styles pour tableaux responsives */
.table-responsive-wrapper {
	width: 100%;
	overflow-x: auto;
	-webkit-overflow-scrolling: touch;
}
.table-responsive-wrapper table {
	width: 100%;
	min-width: 400px;
	table-layout: auto;
}
.table-responsive-wrapper th,
.table-responsive-wrapper td {
	white-space: nowrap;
	padding: 8px 10px;
}
.table-responsive-wrapper th:first-child,
.table-responsive-wrapper td:first-child {
	position: sticky;
	left: 0;
	background-color: #fff;
	z-index: 1;
	box-shadow: 2px 0 5px -2px rgba(0,0,0,0.1);
}
.table-responsive-wrapper thead th:first-child {
	background-color: #f8f8f8;
	z-index: 2;
}
.table-responsive-wrapper tbody tr:nth-child(odd) td:first-child {
	background-color: #f9f9f9;
}
.table-responsive-wrapper tbody tr:hover td:first-child {
	background-color: #f5f5f5;
}
@media screen and (max-width: 768px) {
	.table-responsive-wrapper table {
		font-size: 12px;
	}
	.table-responsive-wrapper th,
	.table-responsive-wrapper td {
		padding: 6px 8px;
	}
}
</style>

<!-- ===== SECTION 1 : Graphique principal ===== -->
<div class="col-sm-12">
	<div id="chart_div_<?php echo $idChamp; ?>" style="width: 100%; height: 400px;"></div>
</div>

<!-- ===== SECTION 2 : Tableau par valeur de ventilation ===== -->
<div class="col-sm-12" style="margin-top: 20px;">
	<div class="table-responsive-wrapper">
		<table class="display dataTable table table-striped table-bordered">
			<thead>
				<tr>
					<th style="text-align: left;"><?php echo $libelleChampVentilation ? $libelleChampVentilation : 'Valeur'; ?></th>
					<th style="text-align: center; min-width: 100px;"><?php echo $libelleChamp; ?></th>
					<th style="text-align: center; min-width: 80px;">%</th>
				</tr>
			</thead>
			<tbody>
				<?php foreach($valeursStats as $nomValeur => $stats): 
					$isTotal = ($nomValeur === 'Total');
					$rowStyle = $isTotal ? 'background-color: #e9e9e9; font-weight: bold;' : '';
				?>
					<tr style="<?php echo $rowStyle; ?>">
						<td style="text-align: left; vertical-align: middle;">
							<?php echo $nomValeur; ?>
						</td>
						<td style="text-align: center; vertical-align: middle;">
							<b><?php echo $stats->nbValeurs; ?></b>
						</td>
						<td style="text-align: center; vertical-align: middle;">
							<?php echo $stats->TO; ?> %
						</td>
					</tr>
				<?php endforeach; ?>
			</tbody>
		</table>
	</div>
</div>

<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChartsHC);

function drawChartsHC() {
	console.log('GRAPH stats/mystatv2_hc.phtml');
	
	var typeGraph = <?php echo $typeGraph; ?>;
	
	// ===== Graphique principal ===== 
	<?php if (!empty($dataGraph) && count($dataGraph) > 1): ?>
		var dataGraph = <?php echo json_encode($dataGraph); ?>;
		console.log('dataGraph', dataGraph);
		
		// Vérifier qu'il y a au moins 2 colonnes pour le graphique
		if (dataGraph.length > 1 && dataGraph[0].length >= 2) {
			
			// Détecter si les écarts sont très importants (ratio > 100)
			var values = [];
			for (var i = 1; i < dataGraph.length; i++) {
				values.push(dataGraph[i][1]);
			}
			var maxVal = Math.max.apply(null, values);
			var minVal = Math.min.apply(null, values);
			var hasLargeGap = (minVal > 0 && maxVal / minVal > 100);
			
			// Graphique principal : barres horizontales avec annotations
			var data = new google.visualization.DataTable();
			data.addColumn('string', dataGraph[0][0]);
			data.addColumn('number', dataGraph[0][1]);
			data.addColumn({type: 'string', role: 'annotation'});
			
			for (var i = 1; i < dataGraph.length; i++) {
				var val = dataGraph[i][1];
				var annotation = val.toLocaleString('fr-FR');
				data.addRow([dataGraph[i][0], val, annotation]);
			}
			
			var chartDiv = document.getElementById('chart_div_<?php echo $idChamp; ?>');
			
			var options = {
				title: <?php echo json_encode($titleGraph); ?>,
				chartArea: {width: '60%', height: '80%'},
				legend: {position: 'none'},
				hAxis: {
					minValue: 0,
					logScale: hasLargeGap // Échelle logarithmique si grands écarts
				},
				vAxis: {
					textStyle: {fontSize: 12}
				},
				annotations: {
					textStyle: {fontSize: 11, bold: true},
					alwaysOutside: true
				},
				bar: {groupWidth: '70%'},
				colors: ['#3366cc']
			};
			
			var chart = new google.visualization.BarChart(chartDiv);
			chart.draw(data, options);
			
			// Si grands écarts : créer un graphique zoom sans la valeur max
			// if (hasLargeGap && values.length > 2) {
			// 	// Trouver l'index de la valeur max
			// 	var maxIndex = values.indexOf(maxVal);
				
			// 	// Créer les données sans la valeur max
			// 	var dataZoom = new google.visualization.DataTable();
			// 	dataZoom.addColumn('string', dataGraph[0][0]);
			// 	dataZoom.addColumn('number', dataGraph[0][1]);
			// 	dataZoom.addColumn({type: 'string', role: 'annotation'});
				
			// 	var excludedLabel = '';
			// 	for (var i = 1; i < dataGraph.length; i++) {
			// 		if (i - 1 === maxIndex) {
			// 			excludedLabel = dataGraph[i][0];
			// 			continue; // Skip la valeur max
			// 		}
			// 		var val = dataGraph[i][1];
			// 		var annotation = val.toLocaleString('fr-FR');
			// 		dataZoom.addRow([dataGraph[i][0], val, annotation]);
			// 	}
				
				// Créer le div pour le graphique zoom s'il n'existe pas
				// var zoomDivId = 'chart_div_zoom_< ?php echo $idChamp; ?>';
				// var zoomDiv = document.getElementById(zoomDivId);
				// if (!zoomDiv) {
				// 	zoomDiv = document.createElement('div');
				// 	zoomDiv.id = zoomDivId;
				// 	zoomDiv.style.width = '100%';
				// 	zoomDiv.style.height = '300px';
				// 	zoomDiv.style.marginTop = '20px';
					
				// 	// Ajouter un titre
				// 	var titleDiv = document.createElement('h5');
				// 	titleDiv.innerHTML = '<i class="fa fa-search-plus"></i> Zoom sur les autres valeurs (hors "' + excludedLabel + '")';
				// 	titleDiv.style.marginTop = '30px';
				// 	titleDiv.style.marginBottom = '10px';
					
				// 	chartDiv.parentNode.appendChild(titleDiv);
				// 	chartDiv.parentNode.appendChild(zoomDiv);
				// }
				
				// var optionsZoom = {
				// 	title: 'Détail des valeurs (hors ' + excludedLabel + ')',
				// 	chartArea: {width: '60%', height: '80%'},
				// 	legend: {position: 'none'},
				// 	hAxis: {minValue: 0},
				// 	vAxis: {textStyle: {fontSize: 12}},
				// 	annotations: {
				// 		textStyle: {fontSize: 11, bold: true},
				// 		alwaysOutside: true
				// 	},
				// 	bar: {groupWidth: '70%'},
				// 	colors: ['#dc3912']
				// };
				
				// var chartZoom = new google.visualization.BarChart(zoomDiv);
				// chartZoom.draw(dataZoom, optionsZoom);
			// }
			
		} else {
			document.getElementById('chart_div_<?php echo $idChamp; ?>').innerHTML = 
				'<div class="alert alert-info" style="margin: 20px;">Pas assez de données pour afficher le graphique.</div>';
		}
	<?php else: ?>
		document.getElementById('chart_div_<?php echo $idChamp; ?>').innerHTML = 
			'<div class="alert alert-info" style="margin: 20px;">Aucune donnée à afficher pour le graphique.</div>';
	<?php endif; ?>
}
</script>
