<?php

	//-----------------------------------------------------------------------------------------------------------------
	// requêtes pour WIREGUARD
	//-----------------------------------------------------------------------------------------------------------------
	if ( $code_erreur == 0 ) {

		$query_peers = [];
		
		for( $i = 0; $i < $NB_sites; $i++ ) {
			
			$query_peers[$i] = "
				SELECT aqcm_WG_MAC,aqcm_WG_NAME,aqcm_WG_SITE_ID 
				FROM AQCM05_SITE_".$aqcm_SITES_ID[$i].".AQCM05_SONDES_WG 
				WHERE ( aqcm_WG_SITE_ID != '00001_001' )
			";
			//echo( $query_peers[$i] . "</br>" ) ;
		}
		
		$query_all_peers = $query_peers[0] ;
		
		for( $i = 1; $i < $NB_sites; $i++ ) {
			$query_all_peers = $query_all_peers . " UNION ALL " . $query_peers[$i] ;
		}
		$query_all_peers = $query_all_peers . " ORDER BY aqcm_WG_MAC ASC,aqcm_WG_SITE_ID ASC,aqcm_WG_NAME ASC" ;
		
		//echo( $query_all_peers . "</br>" ) ;
		
	}

	if ( $code_erreur == 0 ) {

		$result = mysqli_query($link, $query_all_peers); 
		
		if ( ! $result ) {
			
			$code_erreur = 3 ;
			
		}
		else {
			
			if ( mysqli_num_rows($result) == 0 ) {
				
				$code_erreur = 4 ;
				
			}
			else {

				$Nb_peers = 0 ;

				$aqcm_WG_SITE_ID 	= [];
				$aqcm_WG_MAC 			= [];
				$aqcm_WG_NAME 		= [];
				
				while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
					
					$aqcm_WG_SITE_ID[$Nb_peers]	= $row["aqcm_WG_SITE_ID"] ;
					$aqcm_WG_MAC[$Nb_peers]			= $row["aqcm_WG_MAC"] ;
					$aqcm_WG_NAME[$Nb_peers]		= $row["aqcm_WG_NAME"] ;

					//echo($aqcm_WG_MAC[$Nb_peers]	 . "</br>");
					
					$Nb_peers++ ;
					
					
				}
			}
		}
	}
	
	//print_r($aqcm_WG_MAC);

	if ( ( $code_erreur == 0 ) && ( $Nb_peers > 0 ) ) {

		$MAC_occurences_wireguard = array_count_values($aqcm_WG_MAC) ;
		
		for( $i = 0; $i < $Nb_peers; $i++) {
			
			if ( $aqcm_MAC == $aqcm_WG_MAC[$i] ) {

				$Nb_occurences = $MAC_occurences_wireguard[$aqcm_WG_MAC[$i]] ;
				
				if ( $Nb_occurences == 1 ) {
					
					if ( $aqcm_SITE_ID != $aqcm_WG_SITE_ID[$i] ) {
						
						$Flag_MAC_is_OK = false ;
						
					}
					
				}
				elseif ( $Nb_occurences > 1 ) {
					
					$Flag_MAC_is_OK = false ;
					
				}
				
			}

		}
		
	}
	else {
		
		$code_erreur = 5 ;
		
	}

?>