<?php

	//-----------------------------------------------------
	$flag_debug = true ;
	$flag_debug = false ;
	
	//-----------------------------------------------------
	// initialisation générales
	//-----------------------------------------------------
	date_default_timezone_set("Europe/Paris");

	$Nb_mesures_ok 		= [] ;
	$BIQUO_code_erreur 	= [] ;
	$BIQUO_message 		= [] ;
	
	$week_offset = 0;
	
	$temps_start		= mktime( 0, 0, 0, $_SESSION['aqcm_MOIS'], $_SESSION['aqcm_JOUR'] + 7 * ( $week_offset ),		$_SESSION['aqcm_ANNEE'] );
	$week_start 		= "&nbsp;- " . date('d/m/Y', $temps_start) ;

	$NB_hald_day = 2 ;
	
	for ($half_day = 0; $half_day < $NB_hald_day; $half_day++) {
		
		//-----------------------------------------------------
		$BIQUO_code_erreur[$half_day] = 0 ;
		$BIQUO_message[$half_day] 		= "#0" ;

		//-----------------------------------------------------
		// initialisation des variables temporelles
		//-----------------------------------------------------
		if ( $BIQUO_code_erreur[$half_day] == 0 ) {
			
			//-----------------------------------------------------
			if ( $half_day % 2 == 0 ){
				$temps_start	= mktime(  0, 0, 0, 
					$_SESSION['aqcm_MOIS'], 
					$_SESSION['aqcm_JOUR'] + 7 * ( $week_offset ) + intdiv($half_day,2),   
					$_SESSION['aqcm_ANNEE'] 
				);
				$temps_stop	= mktime( 12, 0, 0, 
					$_SESSION['aqcm_MOIS'], 
					$_SESSION['aqcm_JOUR'] + 7 * ( $week_offset ) + intdiv($half_day,2), 
					$_SESSION['aqcm_ANNEE'] 
				);
			}
			else{
				$temps_start	= mktime( 12, 0, 0, 
					$_SESSION['aqcm_MOIS'], 
					$_SESSION['aqcm_JOUR'] + 7 * ( $week_offset ) + intdiv($half_day,2),   
					$_SESSION['aqcm_ANNEE'] 
				);
				$temps_stop	= mktime(  0, 0, 0, 
					$_SESSION['aqcm_MOIS'], 
					$_SESSION['aqcm_JOUR'] + 7 * ( $week_offset ) + 1 + intdiv($half_day,2), 
					$_SESSION['aqcm_ANNEE'] 
				);
			}			
			
			//-----------------------------------------------------
			$annee = date('Y', $temps_start);
			$mois  = date('m', $temps_start);
			$jour  = date('d', $temps_start);
			$heure = date('H:i:s', $temps_start);
			
		}

		//-----------------------------------------------------
		// initialisation des variables logicielles
		//-----------------------------------------------------
		if ( $BIQUO_code_erreur[$half_day] == 0 ) {
			
			$CO2_mmm		      = "400.00|400.00|400.00" ;
			
			$mesures_chaines				= array();
			$mesures_chaines_ok			= array();
			$mesures_chaines_splitted	= array();

			$T_min        = array();
			$T_moy        = array();
			$T_max        = array();
			
			$HR_min       = array();
			$HR_moy       = array();
			$HR_max       = array();
			
			$CO2_min      = array();
			$CO2_moy      = array();
			$CO2_max      = array();

			$COV_min  	  = array();
			$COV_moy      = array();
			$COV_max      = array();

			$PM25_min     = array();
			$PM25_moy     = array();
			$PM25_max     = array();
			
			$PM25_min     = array();
			$PM25_moy     = array();
			$PM25_max     = array();
			
			$HCHO_min     = array();
			$HCHO_moy     = array();
			$HCHO_max     = array();
			
			$LUX_min      = array();
			$LUX_moy      = array();
			$LUX_max      = array();
			
			$SPL_min      = array();
			$SPL_moy      = array();
			$SPL_max      = array();
			
			$NOX_min  	  = array();
			$NOX_moy      = array();
			$NOX_max      = array();
			
		}


		//-----------------------------------------------------
		// requête initiale en base de données                  
		//-----------------------------------------------------
		if ( $BIQUO_code_erreur[$half_day] == 0 ) {
			
			$mesures_names = ["temps","T","HR","CO2","COV_IAQ","PM25","PM10","HCHO","LUX","SPL","NOX_IAQ"];

			$chaine_requete = "";
			for ($j = 0; $j < sizeof($mesures_names); $j++) {
				$chaine_requete = $chaine_requete . $mesures_names[$j];
				if ( $j<(sizeof($mesures_names)-1) ) {
					$chaine_requete = $chaine_requete . ",";
				}
			}

			$query = "
				SELECT " . $chaine_requete . " FROM " . $p_MAC_SONDE . "_mesures 
				WHERE ( (periode='10_MN') AND (temps >= " . $temps_start . ") AND (temps < " . $temps_stop . ") )
				ORDER BY temps
				";
				
			//echo "requête locale (SELECT) : ";  echo ("</br> \r\n");
			//echo $query;  echo ("</br> \r\n");

			$result = mysqli_query($lien, $query) ;
			
			if ( ! $result ) {
				
				$BIQUO_code_erreur[$half_day]	= 1;
				$BIQUO_message[$half_day]		= "#1" ;
				
			}
			else {
				
				$Nb_mesures = mysqli_num_rows($result) ;
				
				if ( $Nb_mesures == 0 ) {
					
					$BIQUO_code_erreur[$half_day]	= 2;
					$BIQUO_message[$half_day]		= "#2" ;
					
				}
				else {
					
					if ( $flag_debug ) {
						echo("Nb_mesures = "); echo($Nb_mesures);  echo (" / 72");  echo ("<br>");//
					}
					
				}
				
			}
			
		}

		//-----------------------------------------------------------------------------------------------------------------
		// extraction des mesures de la période concernée
		//-----------------------------------------------------------------------------------------------------------------
		if ( $BIQUO_code_erreur[$half_day] == 0 ) {
			
			$i=0;
			
			while ( $row = mysqli_fetch_array($result, MYSQLI_BOTH) ) {
				
				for ($j = 0; $j < sizeof($mesures_names); $j++) {
					
					$mesures_chaines[$i][$j]          = $row[$mesures_names[$j]];
					$mesures_chaines_splitted[$i][$j] = explode("|", $mesures_chaines[$i][$j]);
					//echo($mesures_chaines[$i][$j]) ; echo ("</br> \r\n");
					
				}
				//echo ("</br> \r\n");
				$i++ ;
			}
			
			$Nb_mesures_fetched = $i ;
			
			if ($Nb_mesures_fetched > 0 ) {
				
				if ( $flag_debug ) {
					echo("Nb_mesures_fetched = "); echo($Nb_mesures_fetched);  echo (" / 72");echo ("<br>");
				}
				
			}
			else {
				
				$BIQUO_code_erreur[$half_day]	= 3; 
				$BIQUO_message[$half_day]		= "#3" ;
				
			}

		} 

		//-------------------------------------------------------------------------------------------------
		// sélection des mesures en fonction des plages horaires de présence / détection sonore
		//-------------------------------------------------------------------------------------------------
		if ( $BIQUO_code_erreur[$half_day] == 0 ) {
			
			$Nb_mesures_ok[$half_day] = 0 ;
			
			for ($i = 0; $i < $Nb_mesures_fetched; $i++) {

				//---------------------------------------------------------------------------------------------
				// calculs des fractions temporelles
				//---------------------------------------------------------------------------------------------
				$temps_mesure 		= intval($mesures_chaines_splitted[$i][0][0]) ;
				$jour_de_la_semaine	= intval(date("w", $temps_mesure) - 1 ) ;
				if ( $jour_de_la_semaine == -1 ) $jour_de_la_semaine = 6 ;
				
				$marqueur_temps_0 = mktime(0, 0, 0, date("m", $temps_mesure)  , date("d", $temps_mesure), date("Y", $temps_mesure));
				
				$temps_du_jour    = $temps_mesure - $marqueur_temps_0 ;
				$fraction_du_jour = floor($temps_du_jour/(600)) ;
				$index_scheduler  = 24 * 6 * $jour_de_la_semaine + $fraction_du_jour ;

				$schedule_enabled = substr($p_aqcm_SCHEDULER, $index_scheduler, 1) ;
				
				//-------------------------------------------------------------------------
				// plages horaires de présence uniquement
				//-------------------------------------------------------------------------
				if     ( $p_aqcm_SPL_TRIG_MODE_BIQUO == "PHP_ONLY" ) {

					if ( $schedule_enabled == "1" ) {
						$FLAG_mesure_OK = true ;
					} else {
						$FLAG_mesure_OK = false ;
					}

				}
				//-------------------------------------------------------------------------
				// détection sonore sans tenir compte des plages de présence
				//-------------------------------------------------------------------------
				elseif ( $p_aqcm_SPL_TRIG_MODE_BIQUO == "SPL_ONLY" ) {
					
					if 	(		( floatval($mesures_chaines_splitted[$i][9][1] ) >= $p_aqcm_SPL_TRIG_MOY ) 
							or	( floatval($mesures_chaines_splitted[$i][9][2] ) >= $p_aqcm_SPL_TRIG_MAX )		) {
						
						$FLAG_mesure_OK = true ;
					} else {
						$FLAG_mesure_OK = false ;
					}
						
				}

				//-------------------------------------------------------------------------
				// détection sonore active  +  plages de présence
				//-------------------------------------------------------------------------
				elseif ( $p_aqcm_SPL_TRIG_MODE_BIQUO == "SPL+PHP" ) {
					
					if 	(		( $schedule_enabled == "1" ) 
						  or	( floatval($mesures_chaines_splitted[$i][9][1] ) >= $p_aqcm_SPL_TRIG_MOY ) 
						  or	( floatval($mesures_chaines_splitted[$i][9][2] ) >= $p_aqcm_SPL_TRIG_MAX )
						) {
						
						$FLAG_mesure_OK = true ;
						
					} else {
						$FLAG_mesure_OK = false ;
					}
						
				}
				
				//-------------------------------------------------------------------------
				// détection sonore active, uniquement dans les plages de présence
				//-------------------------------------------------------------------------
				elseif ( $p_aqcm_SPL_TRIG_MODE_BIQUO == "SPL(PHP)" ) {
					
					if 	(		( $schedule_enabled == "1" ) 
						  and	(		( floatval($mesures_chaines_splitted[$i][9][1] ) >= $p_aqcm_SPL_TRIG_MOY ) 
								  or	( floatval($mesures_chaines_splitted[$i][9][2] ) >= $p_aqcm_SPL_TRIG_MAX )		)
						) {
						
						$FLAG_mesure_OK = true ;
						
					} else {
						$FLAG_mesure_OK = false ;
					}
						
				}
				//-------------------------------------------------------------------------
				// anomalie dans la configuration
				//-------------------------------------------------------------------------
				else {
					$FLAG_mesure_OK = false ;
				}

				
				//-------------------------------------------------------------------------
				// recensement des mesures valides
				//-------------------------------------------------------------------------
				if ( $FLAG_mesure_OK ) {
					
					$mesures_chaines_ok[$Nb_mesures_ok[$half_day]]				= $mesures_chaines[$i] ;
					$mesures_chaines_splitted_ok[$Nb_mesures_ok[$half_day]]	= $mesures_chaines_splitted[$i] ;

					$Nb_mesures_ok[$half_day]++ ;
					
				}

			}

			if ( $Nb_mesures_ok[$half_day] > 0 ) {
				
				if ( $flag_debug ) {
					echo("Nb_mesures_fetched = "); echo($Nb_mesures_fetched);  echo (" / 72");echo ("<br>");
				}
				
			}
			else {
				
				$BIQUO_code_erreur[$half_day]	= 4;
				$BIQUO_message[$half_day]		= "#4" ;
				
			}

		}

		//-------------------------------------------------------------------------------------------------
		// extraction des mesures valides
		//-------------------------------------------------------------------------------------------------
		if ( $BIQUO_code_erreur[$half_day] == 0 ) {
			
			for ($i = 0; $i < $Nb_mesures_ok[$half_day]; $i++) {
				
				$T_min[$i]        = floatval($mesures_chaines_splitted_ok[$i][1][0]);
				$T_moy[$i]        = floatval($mesures_chaines_splitted_ok[$i][1][1]);
				$T_max[$i]        = floatval($mesures_chaines_splitted_ok[$i][1][2]);

				$HR_min[$i]       = floatval($mesures_chaines_splitted_ok[$i][2][0]);
				$HR_moy[$i]       = floatval($mesures_chaines_splitted_ok[$i][2][1]);
				$HR_max[$i]       = floatval($mesures_chaines_splitted_ok[$i][2][2]);

				$CO2_min[$i]      = floatval($mesures_chaines_splitted_ok[$i][3][0]);
				$CO2_moy[$i]      = floatval($mesures_chaines_splitted_ok[$i][3][1]);
				$CO2_max[$i]      = floatval($mesures_chaines_splitted_ok[$i][3][2]);
				
				$COV_min[$i]  	  = floatval($mesures_chaines_splitted_ok[$i][4][0]);
				$COV_moy[$i]  	  = floatval($mesures_chaines_splitted_ok[$i][4][1]);
				$COV_max[$i]  	  = floatval($mesures_chaines_splitted_ok[$i][4][2]);

				$PM25_min[$i]     = floatval($mesures_chaines_splitted_ok[$i][5][0]);
				$PM25_moy[$i]     = floatval($mesures_chaines_splitted_ok[$i][5][1]);
				$PM25_max[$i]     = floatval($mesures_chaines_splitted_ok[$i][5][2]);

				$PM10_min[$i]     = floatval($mesures_chaines_splitted_ok[$i][6][0]);
				$PM10_moy[$i]     = floatval($mesures_chaines_splitted_ok[$i][6][1]);
				$PM10_max[$i]     = floatval($mesures_chaines_splitted_ok[$i][6][2]);

				$HCHO_min[$i]     = floatval($mesures_chaines_splitted_ok[$i][7][0]);
				$HCHO_moy[$i]     = floatval($mesures_chaines_splitted_ok[$i][7][1]);
				$HCHO_max[$i]     = floatval($mesures_chaines_splitted_ok[$i][7][2]);

				$LUX_min[$i]      = floatval($mesures_chaines_splitted_ok[$i][8][0]);
				$LUX_moy[$i]      = floatval($mesures_chaines_splitted_ok[$i][8][1]);
				$LUX_max[$i]      = floatval($mesures_chaines_splitted_ok[$i][8][2]);

				$SPL_min[$i]      = floatval($mesures_chaines_splitted_ok[$i][9][0]);
				$SPL_moy[$i]      = floatval($mesures_chaines_splitted_ok[$i][9][1]);
				$SPL_max[$i]      = floatval($mesures_chaines_splitted_ok[$i][9][2]);

				$NOX_min[$i]  	  = floatval($mesures_chaines_splitted_ok[$i][10][0]);
				$NOX_moy[$i]  	  = floatval($mesures_chaines_splitted_ok[$i][10][1]);
				$NOX_max[$i]  	  = floatval($mesures_chaines_splitted_ok[$i][10][2]);

			}
			
			$Nb_mesures_extracted = $i ;
			
			if ( $Nb_mesures_extracted > 0 ) {
				
				if ( $flag_debug ) {
					echo("Nb_mesures_extracted = "); echo($Nb_mesures_extracted);  echo (" ...<br>");
				}
				
			}
			else {
				
				$BIQUO_code_erreur[$half_day] = 5; 
				$BIQUO_message[$half_day]		= "#5" ;
				
			}
		}
			
		//-----------------------------------------------------------------------------------------------------------------
		// calcul des moyennes, minima et maxima
		//-----------------------------------------------------------------------------------------------------------------
		if ( $BIQUO_code_erreur[$half_day] == 0 ) {
			
			if ( $Nb_mesures_extracted < 2 ) {
				
				$BIQUO_code_erreur[$half_day]	= 6;
				$BIQUO_message[$half_day]		= "#6" ;
				
			}
			else {
				
				$T_mini        = sprintf( "%.2f",           min($T_min) );
				$T_maxi        = sprintf( "%.2f",          max($T_max) );
				$T_moye        = sprintf( "%.2f",  ((array_sum($T_moy))/$Nb_mesures_extracted) );
				$T_mmm         = $T_mini . "|" . $T_moye . "|" . $T_maxi ;
				
				$HR_mini       = sprintf( "%.2f",          min($HR_min) );
				$HR_maxi       = sprintf( "%.2f",          max($HR_max) );
				$HR_moye       = sprintf( "%.2f",  ((array_sum($HR_moy))/$Nb_mesures_extracted) );
				$HR_mmm        = $HR_mini . "|" . $HR_moye . "|" . $HR_maxi ;
				
				$CO2_mini      = sprintf( "%.2f",         min($CO2_min) );
				$CO2_maxi      = sprintf( "%.2f",         max($CO2_max) );
				$CO2_moye		= sprintf( "%.2f", ((array_sum($CO2_moy))/$Nb_mesures_extracted) );
				$CO2_mmm		= $CO2_mini . "|" . $CO2_moye . "|" . $CO2_maxi ;

				$COV_mini  		= sprintf( "%.2f",         min($COV_min) );
				$COV_maxi		= sprintf( "%.2f",         max($COV_max) );
				$COV_moye		= sprintf( "%.2f", ((array_sum($COV_moy))/$Nb_mesures_extracted) );
				$COV_mmm		= $COV_mini . "|" . $COV_moye . "|" . $COV_maxi ;
				
				$PM25_mini     = sprintf( "%.2f",         min($PM25_min) );
				$PM25_maxi     = sprintf( "%.2f",         max($PM25_max) );
				$PM25_moye     = sprintf( "%.2f", ((array_sum($PM25_moy))/$Nb_mesures_extracted) );
				$PM25_mmm      = $PM25_mini . "|" . $PM25_moye . "|" . $PM25_maxi ;
				
				$PM10_mini     = sprintf( "%.2f",         min($PM10_min) );
				$PM10_maxi     = sprintf( "%.2f",         max($PM10_max) );
				$PM10_moye     = sprintf( "%.2f", ((array_sum($PM10_moy))/$Nb_mesures_extracted) );
				$PM10_mmm      = $PM10_mini . "|" . $PM10_moye . "|" . $PM10_maxi ;
				
				$HCHO_mini     = sprintf( "%.2f",         min($HCHO_min) );
				$HCHO_maxi     = sprintf( "%.2f",         max($HCHO_max) );
				$HCHO_moye     = sprintf( "%.2f", ((array_sum($HCHO_moy))/$Nb_mesures_extracted) );
				$HCHO_mmm      = $HCHO_mini . "|" . $HCHO_moye . "|" . $HCHO_maxi ;
				
				$LUX_mini      = sprintf( "%.1f",         min($LUX_min) );
				$LUX_maxi      = sprintf( "%.1f",         max($LUX_max) );
				$LUX_moye      = sprintf( "%.1f", ((array_sum($LUX_moy))/$Nb_mesures_extracted) );
				$LUX_mmm       = $LUX_mini . "|" . $LUX_moye . "|" . $LUX_maxi ;
				
				$SPL_mini      = sprintf( "%.1f",         min($SPL_min) );
				$SPL_maxi      = sprintf( "%.1f",         max($SPL_max) );
				$SPL_moye      = sprintf( "%.1f", ((array_sum($SPL_moy))/$Nb_mesures_extracted) );
				$SPL_mmm       = $SPL_mini . "|" . $SPL_moye . "|" . $SPL_maxi ;
				
				$NOX_mini  		= sprintf( "%.2f",         min($NOX_min) );
				$NOX_maxi		= sprintf( "%.2f",         max($NOX_max) );
				$NOX_moye		= sprintf( "%.2f", ((array_sum($NOX_moy))/$Nb_mesures_extracted) );
				$NOX_mmm		= $NOX_mini . "|" . $NOX_moye . "|" . $NOX_maxi ;

			}
		}

		//-------------------------------------------------------------------------------
		// si la mesure existe déjà pour ce timestamp, elle est supprimée
		//-------------------------------------------------------------------------------
		$query = "
			DELETE IGNORE FROM " . $p_MAC_SONDE . "_mesures 
			WHERE ( ( periode = 'SCHED' ) AND ( temps = '" . $temps_start . "' ) )
			";
			
		$result = mysqli_query($lien, $query);

		if ( ! $result ) {
			
			echo "- suppression des doublons dans la base locale : échec !!!" ; echo ("</br>");
			
		}
		else {
			
			if ( $flag_debug ) {
				echo "- suppression des doublons dans la base locale : succès..." ; echo ("</br>");
			}
			
		}

		//-----------------------------------------------------------------------------------------------------------------
		// sauvegarde dans la base locale
		//-----------------------------------------------------------------------------------------------------------------
		if ( $BIQUO_code_erreur[$half_day] == 0 ) {
			
			$query = "
			INSERT INTO " . $p_MAC_SONDE . "_mesures 
				(
					periode,temps, annee, mois, jour, heure, Nb,
					T, HR, CO2, COV_IAQ, PM25, PM10, HCHO, LUX, SPL, NOX_IAQ
				) 
				VALUES 
				(
					'SCHED', '".$temps_start."', '".$annee."', '".$mois."', '".$jour."', '00:00:00', '".$Nb_mesures_extracted."',
					'".$T_mmm."','".$HR_mmm."','".$CO2_mmm."','".$COV_mmm."','".$PM25_mmm."','".$PM10_mmm."','".$HCHO_mmm."','".$LUX_mmm."','".$SPL_mmm."','".$NOX_mmm."'
				)";

			if ( $flag_debug ) {
				echo "requête locale (INSERT) : ";  echo ("</br>");
				echo $query;  echo ("</br>");
			}
			
			$result = mysqli_query($lien, $query);

			if ( ! $result ) {
				
				$BIQUO_code_erreur[$half_day] = 7; 
				$BIQUO_message[$half_day]		= "#7" ;
				
			}
			else {
				
				if ( $flag_debug ) {
					echo "- sauvegarde dans la base locale : succès..." ; echo ("<br>");
				}
				
			}

		}

	}
	

	$BIQUO_bilan = hoursandmins( array_sum($Nb_mesures_ok) * 10, '%02dh%02d');
	$koko = "";
	for ($i = 0; $i < $NB_hald_day; $i++) {
		$koko = $koko . $BIQUO_message[$i] ;
	}
	echo( $week_start . " ; " . $BIQUO_bilan ); echo( " ; " . $koko ); echo("<br>"); ob_flush();
	if ( array_sum($BIQUO_code_erreur) > 0 ) {
	}
	
	
		
?>
