<?php
	defined('BASEPATH') OR exit('No direct script access allowed'); 
	if(isset($_SERVER['WINDIR'])) define('DIR_SEPARATOR','\\');
	else define('DIR_SEPARATOR','/');
	uses_class('curl');

	//Globales functions
	uses_functions('ip','phone');

	function uses_class()
	{
		$nb = func_num_args();
		for($i=0;$i<$nb;$i++)
		{
			$file = CLASS_PATH.func_get_arg($i).'.php';
			if(is_file($file)) require_once($file);
			else
			{
				echo "<p><font color=red>la classe <b>'".func_get_arg($i)."'</b> n'existe pas</font></p>";
			}
		}
		return true;
    	
	}
	function getMatricule($number,$table,$champ,$generic='')
	{
		global $sgbd;
		$generic = strtoupper($generic);
		uses_functions('random');
		$serie = $generic;
		$last = $elt=$sgbd->query("select $champ from $table where $champ like '$serie%'")->row_array();
		if(empty($last)) $code = $generic.random_number($number);
		else
		{
			$glen = strlen($generic);
			$code = $generic.random_number($number);
			while($elt=$sgbd->query("select $champ from $table where $champ='$code'")->row_array())
			{
				$code = $generic.random_number($number);
				if($cpt>100) break;
			}
			
		}

		return $code;
		
	
	}
	function urlExist($url) {
		$file_headers = @get_headers($url);
		if($file_headers[0] == 'HTTP/1.1 404 Not Found')
		   return false;
	 
		return true;
	}
	function loadTransaction($current)
	{
		global $sgbd;
		$new = array();
		if(!is_array($current))
		{
			return array();
		} 
		$order_id = array('transaction_id','order_id','operator','phone_number','amount','taxes','fees','fees_taxes_ttc','amount_total','currency','status','country','lang','reference_id','provider_id');
		
		if(empty($current['infos'])) $current['infos'] = $current['Infos'];
		if(empty($current['infos']))
		{
			$infos = $sgbd->query("select transactions.* from transactions where transaction_id = '".$current['transaction_id']."'")->row_array();
			$current['infos']=$infos['infos'];
		}
		if(!empty($current['infos']))
		{
			$data = json_decode($current['infos'],true);
			
			
			foreach($data as $k=>$v)
			{
				$new[$k]=$v;
			}
			if(empty($new['order_id']) and !empty($current['order_id'])) $new['order_id']=$current['order_id'];
			if(empty($new['amount_total']) and !empty($current['total'])) $new['amount_total']=$current['total'];
		}
		unset($new['account_number']);
		unset($new['agent_id']);
		unset($new['servicecode']);
		unset($new['merchant_key']);
		unset($new['infos']);
		
		foreach($order_id as $ord)
		{
			if(isset($new[$ord]))
			{
				$reponse[$ord]= $new[$ord];
				unset($new[$ord]);
			}
		}
		if(is_array($reponse)) $reponse = array_merge($reponse,$new);
		

		
		return $reponse;
		
	}
	
	// Example with PHP
	function sign($json, $secret) {
		$hash = hash_hmac('sha256', $json, $secret);
		return $hash;
	}

	function setError($msg)
	{
		$return['error']   = 1;
		$return['message'] = mb_encode($msg);
		echo (json_encode($return,JSON_FORCE_OBJECT|JSON_UNESCAPED_UNICODE));
		exit();
	}
	function apiError($number,$msg="")
	{
		$return['code']   = $number;
		$return['status']   ="Failed";
		
		$return['message'] = mb_encode($msg);
		
		return $return;
		
	}
	function GetParameter($code)
	{
		global $sgbd;	
		$elt = $sgbd->query("select valeur from parametres where variable = '$code' and status=1 limit 1")->row_array();
		if(!empty($elt)) return $elt['valeur'];
	}
	function GetParameters($code)
	{
		global $sgbd;	
		$elt = $sgbd->liste("select valeur from parametres where variable = '$code' and status=1 limit 1");
		if(!empty($elt)) return $elt['valeur'];
	}
	function display($text)
	{
		return $text;	
	}
	function request_unset($var) 
	{
		unset($_POST[$var],$_GET[$var],$_REQUEST[$var]);
	}
	function getphone($number,$country)
	{
		global $sgbd;
		$query = "select code,numerotation,indicatif from pays where lower(code)='".strtolower($country)."'";
		
		$number = str_replace(' ','',$number);
		$number = str_replace('-','',$number);
		$number = str_replace(',','',$number);
		$number = str_replace('.','',$number);
		$phone['valide']=0;
		$phone['msisdn']="";
		$phone['local']=$number;
		$phone['indicatif']="";
		$p = $sgbd->query($query)->row_array();
		$deb = strlen($number)-$p['numerotation'];
		if($deb<0)
		{
			$phone['valide']=0;
			$phone['msisdn']="";
			$phone['local']=$number;
			$phone['indicatif']="";
		}
		elseif($deb>0)
		{
			$nind = substr($number,0,$deb);
			
			if($p['indicatif']!=$nind)
			{

			}
			else
			{
				$phone['indicatif']=$p['indicatif'];
				$phone['msisdn']= $number;
				$phone['valide']=1;
			}
			
		} 
		else
		{
			$phone['indicatif']=$p['indicatif'];
			$phone['msisdn']= $p['indicatif'].$number;
			$phone['valide']=1;
		}
		
		return $phone;
		
	}
	function msisdn($number,$country)
	{
		$phone = getphone($number,$country);
		return $phone['msisdn'];
		
	}
	function isWhatApps($number)
	{
		
	}
	function smsWhatApps($number,$message)
	{
		
		return 0;
	}
	function uses_functions()
	{
		$nb = func_num_args();
		for($i=0;$i<$nb;$i++)
		{
			$file = FUNCTIONS_PATH.func_get_arg($i).'.php';
			if(is_file($file)) require_once($file);
			else
			{
				echo "<p><font color=red>la librairie <b>'".func_get_arg($i)."'</b> n'existe pas</font></p>";
			}
		}
		return true;
	}
	function encode($texte)
	{
		if(!is_array($texte)) return utf8_encode($texte);
		else
		{
			foreach($texte as $k=>$v)
			{
				$texte[$k] = encode($v);
			}
			return $texte;
		}
	}
	function decode($texte)
	{
		if(!is_array($texte)) return utf8_decode($texte);
		else
		{
			foreach($texte as $k=>$v)
			{
				$texte[$k] = decode($v);
			}
			return $texte;
		}
	}
	function mb_encode($texte)
	{
		if(is_object($texte))
		{
			$val = @get_class ($texte);
			if(!empty($val))
			{
				$vars = get_object_vars ($texte);
				foreach($vars as $k=>$v)
				{
					$texte->$k = encode($v);
				}
				return $texte;
			}
		}
		elseif(!is_array($texte))
		{
			 $ancien = $texte;
			$enc = mb_detect_encoding($texte);
			$k = 0;
			while($enc!='ASCII')
			{
				$ancien = $texte;
				$texte = utf8_decode($texte);
				$enc = mb_detect_encoding($texte);
			}
			return utf8_encode($ancien);
		}
		else
		{
			foreach($texte as $k=>$v)
			{
				$texte[$k] = encode($v);
			}
			return $texte;
		}
	}
	function mb_decode($texte)
	{
		$val =@ get_class ($texte);
		
		if(!empty($val))
		{
			$vars = get_object_vars ($texte);
			foreach($vars as $k=>$v)
			{
				$texte->$k = mb_decode($v);
			}
			return $texte;
		}
		elseif(!is_array($texte)) 
		{
			$texte = mb_encode($texte);
			return utf8_decode($texte);
		}
		else
		{
			foreach($texte as $k=>$v)
			{
				$texte[$k] = mb_decode($v);
			}
			return $texte;
		}
	}
	function getOS() 
	{ 	
		global $user_agent;
		$user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
	
		//$os_platform  = "Unknown OS Platform";
	
		$os_array     = array(
							  '/windows nt 10/i'      =>  'Windows 10',
							  '/windows nt 6.3/i'     =>  'Windows 8.1',
							  '/windows nt 6.2/i'     =>  'Windows 8',
							  '/windows nt 6.1/i'     =>  'Windows 7',
							  '/windows nt 6.0/i'     =>  'Windows Vista',
							  '/windows nt 5.2/i'     =>  'Windows Server 2003/XP x64',
							  '/windows nt 5.1/i'     =>  'Windows XP',
							  '/windows xp/i'         =>  'Windows XP',
							  '/windows nt 5.0/i'     =>  'Windows 2000',
							  '/windows me/i'         =>  'Windows ME',
							  '/win98/i'              =>  'Windows 98',
							  '/win95/i'              =>  'Windows 95',
							  '/win16/i'              =>  'Windows 3.11',
							  '/macintosh|mac os x/i' =>  'Mac OS X',
							  '/mac_powerpc/i'        =>  'Mac OS 9',
							  '/linux/i'              =>  'Linux',
							  '/ubuntu/i'             =>  'Ubuntu',
							  '/iphone/i'             =>  'iPhone',
							  '/ipod/i'               =>  'iPod',
							  '/ipad/i'               =>  'iPad',
							  '/android/i'            =>  'Android',
							  '/postman/i'         =>  'Postman runtime',
							  '/blackberry/i'         =>  'BlackBerry',
							  '/webos/i'              =>  'Mobile'
						);
	
		foreach ($os_array as $regex => $value)
			if (preg_match($regex, $user_agent))
				$os_platform = $value;
		if(empty($os_platform))
		{
			$os_platform  =$user_agent;
		}
		return $os_platform;
	}

	function getBrowser() 
	{

		global $user_agent;
		$user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
	 	
		$browser_array = array(
								'/msie/i'      => 'Internet Explorer',
								
								'/firefox/i'   => 'Firefox',
								'/safari/i'    => 'Safari',
								'/chrome/i'    => 'Chrome',
								'/opr/i'     => 'Opera',
								'/edge/i'      => 'Edge',
								'/opera/i'     => 'Opera',
								'/netscape/i'  => 'Netscape',
								'/maxthon/i'   => 'Maxthon',
								'/konqueror/i' => 'Konqueror',
								'/postman/i'         =>  'Postman runtime',
								'/mobile/i'    => 'Handheld Browser'
						 );
	
		foreach ($browser_array as $regex => $value)
			if (preg_match($regex, $user_agent))
				$browser = $value;
		if(empty($browser))
		{
			$browser  = "Unknown Browser";
		}
		
		return $browser;
	}
	// ajouter les slashes
	function addslashes_array($var) 
	{
		return is_array($var)? array_map("addslashes_array", $var):addslashes($var);
	}
	/*$_POST = addslashes_array($_POST);
	$_SESSION = addslashes_array($_SESSION);
	$_GET = addslashes_array($_GET);
	$_REQUEST = addslashes_array($_REQUEST);*/
	
	function getSMSTocken($code)
	{
		global $sgbd;
		$info = $sgbd->query("select * from tockens where code = '$code' and dateexpiration>'".datetime(20)."'")->row();
		if(empty($info)) return "";
		else return $info->Tocken;
	}
	function setSMSTocken($code,$tocken,$date)
	{
		global $sgbd;
		$info = $sgbd->query("update tockens set Tocken ='$tocken',dateexpiration='$date'  where code = '$code' ");
		if(empty($info)) return "";
		else return $info->Tocken;
	}
	function getIDTransaction()
	{
		global $sgbd;
		$size = 9;
		$min  = "2230000010";
		$elt=$sgbd->query("select max(transaction_id) as max from transactions limit 1")->row_array();

		if($elt['max']>$min) $code = $elt['max'];
		else $code = $min;
		$code = intval($code);
		$code++;
		while($elt=$sgbd->query("select transaction_id from transactions where transaction_id='$code'")->row_array())
		{
			$code++;
			if($code%10==0) $code++;
			$cpt++;
			if($cpt>pow(10,10)) break;
		}
		return $code;
	}
	function haveTransactionID($table='commandes')
	{
		global $sgbd;
		$size = 9;
		$min  = "2230000010";
		$elt=$sgbd->query("select max(transaction_id) as max from $table limit 1")->row_array();

		if($elt['max']>$min) $code = $elt['max'];
		else $code = $min;
		$code = intval($code);
		$code++;
		while($elt=$sgbd->query("select transaction_id from $table where transaction_id='$code'")->row_array())
		{
			$code++;
			if($code%10==0) $code++;
			$cpt++;
			if($cpt>pow(10,10)) break;
		}
		return $code;
	}
	function numbertosolde($montant)
	{
		return $montant.' SMS';
	}
	function json_html($text)
	{
		$array = json_decode($text,true);
		global $json_html_in;
		if(empty($json_html_in)) $json_html_in=1;
		else $json_html_in++;
		for($i=1;$i<=$json_html_in;$i++)
		{
			$decal.= '&nbsp;&nbsp;&nbsp;';
		}
		for($i=1;$i<$json_html_in;$i++)
		{
			$ddecal.= '&nbsp;&nbsp;&nbsp;';
		}
		$html = '<br>';
		$html.=$ddecal.'{';
		$size = count($array);
		$cpt = 1;
		$sep = '';
		foreach($array as $k=>$v)
		{
			if($cpt<$size) $sep = ',';
			else $sep ='';
			if(is_array($v)) $html.= '<br>'.$decal.'<span class=text-info>"'.$k.'"</span>:'.json_html(json_encode($v)).$sep;
			else 
			$html.='<br>'.$decal.'<span class=text-info>"'.$k.'"</span>:<span class=text-warning>"'.addcslashes($v,'"').'"</span>'.$sep;
			$cpt++;
		}
		$html.='<br>'.$ddecal.'}';
		$json_html_in--;
		return $html;		
	}

	function getUUID() {
		return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
			// 32 bits for "time_low"
			mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
	
			// 16 bits for "time_mid"
			mt_rand( 0, 0xffff ),
	
			// 16 bits for "time_hi_and_version",
			// four most significant bits holds version number 4
			mt_rand( 0, 0x0fff ) | 0x4000,
	
			// 16 bits, 8 bits for "clk_seq_hi_res",
			// 8 bits for "clk_seq_low",
			// two most significant bits holds zero and one for variant DCE1.1
			mt_rand( 0, 0x3fff ) | 0x8000,
	
			// 48 bits for "node"
			mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
		);
	}
	function getUID($text=1)
	{
		global $sgbd;
		//$file = file_get_contents(, true);
		$url = "https://www.uuidgenerator.net/api/version4";
		
		uses_functions('random');
		if($text==1)
		{
			$ch = curl_init();
	
			// Configuration de l'URL et d'autres options
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
			
			// Récupération de l'URL et affichage sur le navigateur
			$file = curl_exec($ch);
			
			// Fermeture de la session cURL
			curl_close($ch);
			if(!empty($file)) return trim($file);
			else 
			{
				$file = @file_get_contents($url);
				$file = trim($file);
				if(!empty($file)) return trim($file);
				else
				{
					
					return getUUID();
				}
				
				
			}
		}
		else
		{
					$rand =haveIDTransaction();
					return $rand;
		}
		
		
	}
	
	
	
	function traceError($erreur,$type='warning',$details='')
	{
		global $log_sgdb;
		if(empty($erreur)) return false;
		$erreur = str_replace(chr(10),"",$erreur);
		$erreur = str_replace(chr(13),"",$erreur);
		$query = "INSERT INTO `logs`( `Libelle`, `Service`, `Url`, `DateLog`, `Details`, `Origine`, `ip_address`,`alerte`) 
VALUES ('".addslashes(strip_tags($erreur))."','$auteur','".$_GET['_ajx']."','".datetime()."','".addslashes($details)."','".strval($_SERVER['HTTP_ORIGIN'])."','".strval(get_ip())."','$type')";
		$log_sgdb->query($query);

	}
	function warningError($erreur)
	{
		traceError($erreur,'danger');
	}
	function iso_encode($texte)
	{
		global $nombre ;
		if(is_object($texte))
		{
			$val = @get_class ($texte);
			if(!empty($val))
			{
				$vars = get_object_vars ($texte);
				foreach($vars as $k=>$v)
				{
					$texte->$k = iso_encode($v);
				}
				return $texte;
			}
		}
		elseif(!is_array($texte))
		{
			 $ancien = $texte;
			$enc1 = mb_detect_encoding($texte);
			$enc2 = mb_detect_encoding(utf8_encode($texte));
			$enc3 = mb_detect_encoding(utf8_decode($texte));
			
			$enc4 = mb_detect_encoding(utf8_decode(utf8_decode($texte)));
			$k = 0;
			
			
			if($enc1=='UTF-8' and $enc2=='UTF-8' and $enc3=='ASCII')
			{
				$test = utf8_decode(utf8_decode(sans_accents($texte)));

				if (substr_count($test,'?')<1) {
					$texte = utf8_encode($texte);
				  } 
				
			}
			return $texte;
		}
		else
		{
			foreach($texte as $k=>$v)
			{
				$texte[$k] = iso_encode($v);
			}
			return $texte;
		}
	}
	function sans_accents($str, $encoding='utf-8')
	{
		// transformer les caractères accentués en entités HTML
		
		$str = mb_encode($str);
		$str = htmlentities($str, ENT_NOQUOTES, $encoding);
		
	 
		// remplacer les entités HTML pour avoir juste le premier caractères non accentués
		// Exemple : "&ecute;" => "e", "&Ecute;" => "E", "Ã " => "a" ...
		$str = preg_replace('#&([A-za-z])(?:acute|grave|cedil|circ|orn|ring|slash|th|tilde|uml);#', '\1', $str);
	 
		// Remplacer les ligatures tel que : Œ, Æ ...
		// Exemple "Å“" => "oe"
		$str = preg_replace('#&([A-za-z]{2})(?:lig);#', '\1', $str);
		// Supprimer tout le reste
		$str = preg_replace('#&[^;]+;#', '', $str);
	 
		return $str;
	}
	function url_code_header($url)
	{
		$error = 404;
		$inf = get_headers($url);
		$infos = explode(' ',$inf[0]);
		
		if(is_numeric($infos[1])) $error = intval($infos[1]);
		return $error;
	} 
	function xml2array ( $xmlObject, $out = array () )
	{
		foreach ( (array) $xmlObject as $index => $node )
			$out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

		return $out;
	}
	function local_json($return,$agent_id="")
	{
		global $sgbd,$gprovider,$log_sgdb;
		
		header("Content-Type:application/json");
		uses_functions('random');
		$add['request_id']=random_number(30);
		$add['request_time']=microtime(true);
		$add['request_ip']= get_ip();
		//$add['request_provider']= $gprovider;
		$input = file_get_contents('php://input');
		$error= 0;
		if(!empty($return['error']))
		{
			if(!empty($return['error']['message']))
			{
				$return['error']['reason']=$return['error']['message'];
				unset($return['error']['message']);
			} 
			//if(!isset($return['error']['reason'])) $return['error']['reason']="Undefined reason";
			$request_code = $return['error']['code'];
			if(empty($request_code)) $request_code = 999;
			$error = 1;
			if(!empty($return['error']['reason'])) saveError($return['error']['reason'],$return['error']['provider_error'],$agent_id);
			unset($return['error']['provider_error']);
			//$return = $return['error'];
		}
		
		$query = "INSERT INTO `requests_logs`( `request_id`,  `request_url`, `request_time`, `request_ip`, `request_get`, `request_post`, `request_input`, `request_reponse`, `request_error`, `request_iserror`) VALUES ('".$add['request_id']."','".$_SERVER['REQUEST_URI']."','".$add['request_time']."','".$add['request_ip']."','".addslashes(json_encode($_GET))."','".addslashes(json_encode($_POST))."','".addslashes($input)."','".addslashes(json_encode($return))."','$request_code','$error')";
		
		$log_sgdb->query($query);

		$return = array_merge($add,$return);
		$return = iso_encode($return);
		echo (json_encode($return,JSON_FORCE_OBJECT|JSON_UNESCAPED_UNICODE));
		exit();
	}
	


	function saveError($msg,$provider_msg,$agent_id="")
	{
		global $log_sgdb,$session,$sgbd;
		if(empty($msg)) return false;
		
		$query = "INSERT INTO `errors_logs`( `user_id`,`agent_id`,  `label`, `message`, `alert`, `url`, `origin`, `ip_address`, `date_log`, `details`) VALUES 
		('".$_SESSION['id']."','$agent_id','".addslashes($msg)."','".addslashes($provider_msg)."','danger','".$_SERVER['REQUEST_URI']."','".get_ip()."','".get_ip()."','".datetime()."','')";
		
		$log_sgdb->query($query);
	}
	
	