<?php 
session_start();
if(app::isAdmin()){
	error_reporting(E_ALL & ~E_NOTICE);
	ini_set('display_errors', 1);
}
ob_start();

/*
if (isset($_GET["copy"])) {
	$f = file_put_contents("./datafiles.zip", fopen("http://erp.mosaique-auto.com/?getzip=all", 'r'), LOCK_EX);
	if(FALSE === $f){
		echo "Erreur de téléchargement";
	}else{
		$zip = new ZipArchive;
		$res = $zip->open('./datafiles.zip');
		if ($res === TRUE) {
		  $zip->extractTo('./');
		  $zip->close();
		  echo "OK";
		} else {
			echo "Erreur de Zip";
		}
	}
}
*/
$dd = explode(".", $_SERVER["SERVER_NAME"]);
app::$dom = strtolower($dd[count($dd)-2].".".$dd[count($dd)-1]);
app::$sdom = "";
for ($i=0; $i < count($dd)-2 ; $i++) { 
  if(!empty(app::$sdom)) app::$sdom .=".";
  app::$sdom .= $dd[$i];
}
/* $listbn = ["uad", "dev", "kpa", "kpag", "rh", "ca", "cap", "beta", "dev", "ha", "ll", "sca", "erp", "demo", "mt"];
if (!in_array(app::$sdom, $listbn)) {
	exit;
} */
include "helper.php";
include "view.php";
include "Route.php";
include "db.php";
include "Event.php";
include "app-js.php";
include "avs.php";
include "user.php";
include "Droit.php";
include "config-modules.php";
include "setting.php";
include "db_table.php";

app::event("init");

if (isset($_GET["getzip"])) {
	switch ($_GET["getzip"]) {
		case 'src':
			app::zip("./","./public/site.zip","/\/(Com|kernel|mdl)\//i");
		break;
		case 'all':
			app::zip("./","./public/site.zip");
		break;
		case 'xall':
			app::zip("./","./public/site.zip","/./i","/public\/(upload|tmpupfile|slides|img|albume|icon)|store-db|.zip/i");
		break;
		case 'yall':
			app::zip("./","./public/site.zip","/./i",".zip/i");
		break;
		case 'php':
			app::zip("./","./public/site.zip","/\.php$/i");
		break;
		case 'src-public':
			app::zip("./","./public/site.zip","/\/(Com|kernel|mdl|public)\//i");
		break;
		case 'src-view':
			app::zip("./","./public/site.zip","/\/(Com|kernel|mdl|Views)\//i");
		break;
		case 'src-view-public':
			app::zip("./","./public/site.zip","/\/(Com|kernel|mdl|Views|public)\//i");
		break;
		case 'config':
			$row = db::row("SELECT data FROM `¤STOREDATA` where name='config'");
			exit(json_encode($row["data"]));
		break;
	}
	header("location:/public/site.zip");
	exit();
}
api::updatesrc(function($data){
	if ($data["update"] == "config") {
		$data = file_get_contents("http://erp.mosaique-auto.com/?getzip=".$data["update"]);
		if (!empty($data)) {
			$data = json_decode($data,true);
			if ($data) {
				db::save("¤STOREDATA",["name"=>"config","data"=>$data]);
			}
		}
		return;
	}
	$f = file_put_contents("./public/datafiles.zip", fopen("http://erp.mosaique-auto.com/?getzip=".$data["update"], 'r'), LOCK_EX);
	if(FALSE === $f){
		app::apiRep("alert","Erreur de téléchargement");
	}else{
		$zip = new ZipArchive;
		$res = $zip->open('./public/datafiles.zip');
		if ($res === TRUE) {
		  $zip->extractTo('./');
		  $zip->close();
		} else {
			app::apiRep("alert","Erreur de Zip");
		}
	}
});


if (isset($_GET["delzip"])) {
	header("location:/");
	unlink("./public/site.zip");
	exit();
}


class app {
	static $isopen = true;
	static $installmode = false;
	static $dom = "";
	static $sdom = "";

	static $_on = [];
	static function on($event,$callback){
		if(empty(self::$_on[$event])) self::$_on[$event] = [];
		self::$_on[$event][] = $callback;
	}
	static function event($event,$data = null){
		if(empty(self::$_on[$event])) return $data;
		foreach (self::$_on[$event] as $fn) {
			$v = $fn($data);
			if(!is_null($v)){
				$data = $v;
			}
		}
		return $data;
	}

	static function isopen(){
		return self::$isopen || self::isAdmin() || !empty($_SESSION[user::$varName]);
	}
	static function isAdmin(){
		return $_SERVER["HTTP_REMOTE_IP"] == "41.226.255.80";
	}
	static function iso(){
		return $_SERVER["GEOIP_COUNTRY_CODE"];
	}
	static function paye(){
		return $_SERVER["GEOIP_COUNTRY_NAME"];
	}
	static function ip(){
		return $_SERVER["HTTP_REMOTE_IP"];
	}
	static function root(){
		return $_SERVER["DOCUMENT_ROOT"];
	}
	static function encrypt($data, $key = "wassim") {
		if(!function_exists("mcrypt_get_block_size")) return "";
		if (empty($key)) {$key = "wassim"; }
		if (strlen($key)>24) {
			$key = substr($key, 0, 24);
		}elseif(strlen($key)<24){
			$i = 0;
			while (strlen($key)<24) {
				if ($i >= strlen($key)) {
					$i = 0;
				}
				$key .= $key[$i];
				$i = $i + 1;
			}
		}
		$block = mcrypt_get_block_size(MCRYPT_TRIPLEDES, MCRYPT_MODE_ECB);
		$pad = $block - (strlen($data) % $block);
		$data .= str_repeat(chr($pad), $pad);
		$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_TRIPLEDES, MCRYPT_MODE_ECB), MCRYPT_RAND);
		$encrypted = mcrypt_encrypt(MCRYPT_TRIPLEDES, $key, $data, MCRYPT_MODE_ECB, $iv);
		return base64_encode($encrypted);
	}
	static function decrypt($data, $key = "wassim") {
		if(!function_exists("mcrypt_get_block_size")) return "";
		if (empty($key)) {$key = "wassim"; }
		if (strlen($key)>24) {
			$key = substr($key, 0, 24);
		}elseif(strlen($key)<24){
			$i = 0;
			while (strlen($key)<24) {
				if ($i >= strlen($key)) {
					$i = 0;
				}
				$key .= $key[$i];
				$i = $i + 1;
			}
		}
		$data = base64_decode($data);
		$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_TRIPLEDES, MCRYPT_MODE_ECB), MCRYPT_RAND);
		$data = mcrypt_decrypt(MCRYPT_TRIPLEDES, $key, $data, MCRYPT_MODE_ECB, $iv);
		$block = mcrypt_get_block_size(MCRYPT_TRIPLEDES, MCRYPT_MODE_ECB);
		$pad = ord($data[($len = strlen($data)) - 1]);
		$decrypted = substr($data, 0, strlen($data) - $pad);
		return rtrim($decrypted);
	}
	static function location($url = null){
		if (is_null($url)) {
			if (isset($_SERVER["HTTP_REFERER"])) {
				$url = $_SERVER["HTTP_REFERER"];
			}else{
				$url = "/";
			}
		}
		if (!empty($_GET["api"])) {
			self::apiRep("eval",'window.location = "'.$url.'";');
		}else{
			$c = ob_get_clean();
			header("Status: 301 Moved Permanently", false, 301);
			header("location:$url");
			exit();
		}
	}
	static function zip($dir,$dist,$regex="/./i",$exclude = "/store-db/i"){
		if(file_exists($dist)){
			@unlink($dist);
		}
		$rootPath = realpath($dir);
		$zip = new ZipArchive();
		$zip->open($dist, ZipArchive::CREATE | ZipArchive::OVERWRITE);
		$files = new RecursiveIteratorIterator(
		    new RecursiveDirectoryIterator($rootPath),
		    RecursiveIteratorIterator::LEAVES_ONLY
		);
		foreach ($files as $name => $file){
		    if (!$file->isDir()){
		        $filePath = $file->getRealPath();
		        if (preg_match($regex, $filePath) && !preg_match($exclude, $filePath)) {
			        $relativePath = substr($filePath, strlen($rootPath) + 1);
			        $zip->addFile($filePath, $relativePath);
		        }
		    }
		}
		$zip->close();
	}
	static function glob($path,$regex="/.*/i"){
		$path = realpath($path);
		$Iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
		$Regex = new RegexIterator($Iterator, $regex, RecursiveRegexIterator::GET_MATCH);
		$rep = [];
		foreach ($Regex as $key => $value) {
			if (is_file($value[0])) {
				$rep[] = $value[0];
			}
		}
		return $rep;
	}
	static function getListFile($path=null,$ext="fn,inc,view,css,js,api"){
		$rep = array();
		$parent = is_null($path)?__DIR__."/app":$path;
		$exts = explode(",", $ext);
		foreach ($exts as $kext) {
			$List = glob("$parent/*.$kext.php");
			foreach ($List as $key => $value) {
			  $rep[] = $value;
			}
		}
		$listDir = glob("$parent/*.pak");
		foreach ($listDir as $childPath) {
			$rep = array_merge($rep,self::getListFile($childPath,$ext));
		}
		return $rep;
	}
	static function includeDir($path = "app"){
		$list = app::getListFile($path);
		$order = [];
		foreach ($list as $filename) {
			if (preg_match("/\.fn\.php$/i", $filename)) {
				$order[] = $filename;
			}
		}
		foreach ($list as $filename) {
			if (!preg_match("/\.fn\.php$/i", $filename)) {
				$order[] = $filename;
			}
		}
		foreach ($order as $filename) {
			self::includeFile($filename);
		}
	}
	static function includeFile($filename){
		if (preg_match("/\.view\.php$/i",$filename)) {
			$name = basename($filename,".view.php");
			View::create($name,$filename);
		}elseif (preg_match("/\.js\.php$/i",$filename)) {
			Route::isJs(function($data) use($filename){
				include $filename;
			});
		}elseif (preg_match("/\.css\.php$/i",$filename)) {
			Route::isCss(function($data) use($filename){
				include $filename;
			});
		}else{
			include $filename;
		}
	}
	static function run(){
		app::event("before-run");
		Route::exe();
		echo view::html();
		self::runApi();
		app::event("after-run");
	}
 	static $apiList = [];
	static $apiListRep = [];
	static $apiMasterReponce = [];
	static function api($apinames,$fn){
		if(is_string($apinames)) $apinames = explode(",",$apinames);
		foreach ($apinames as $apiname) {
			if ($apiname == "install" && app::$installmode) {
				$fn();
			}
			self::$apiList[] = [
				"name"=>$apiname,
				"fn"=>$fn
			];
		}
	}
	static function remove_accent($str){
	  $a = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č', 'Ď', 'ď', 'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě', 'ě', 'Ĝ', 'ĝ', 'Ğ', 'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', 'Ĥ', 'ĥ', 'Ħ', 'ħ', 'Ĩ', 'ĩ', 'Ī', 'ī', 'Ĭ', 'ĭ', 'Į', 'į', 'İ', 'ı', 'Ĳ', 'ĳ', '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', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o'); 
	  return str_replace($a, $b, $str);
	}
	static function Slug($str,$str2 = null,$sep="-",$ss=""){
		if ($str == "-") {
			return "";
		}
		if (empty($str) && !empty($str2)) {
			$str = $str2;
		}
	  $v = mb_strtolower(preg_replace(array('/[^أ-يa-zA-Z0-9 \'-\.'.$ss.']/', '/[ -\']+/', '/^-|-$/'),array('', $sep, ''), self::remove_accent($str)));
	  return empty($v)?str_replace(" ",$sep, $str):$v;
	}
	static function apiRep($apiname,$data, $delay = 0){
		self::$apiListRep[] = [
			"event"=>$apiname,
			"data"=>$data,
			"delay" => $delay,
		];
	}
	static function startsWith($haystack, $needle) {
	     $length = strlen($needle);
	     return (substr($haystack, 0, $length) === $needle);
	}
	static function endsWith($haystack, $needle) {
	    $length = strlen($needle);
	    if ($length == 0) {
	        return true;
	    }
	    return (substr($haystack, -$length) === $needle);
	}
	static function ClearObjNg ($table){
		if(is_string($table)) return $table;
		if(is_array($table)){
			foreach ($table as $key => $value) {
				if (is_string($key)) {
					if (self::startsWith($key,'$')) {
						unset($table[$key]);
					}else{
						$table[$key] = self::ClearObjNg($value);
					}
				}else{
					$table[$key] = self::ClearObjNg($value);
				}
			}
		}
		return $table;
	}

	static function emitApiEvent($apiname,$data = []){
		foreach (self::$apiList as $api) {
			if ($api["name"] == $apiname) {
				$fn = $api["fn"];
				ob_start();
					$vv = [];
					foreach ($_REQUEST as $key => $value) {
						if (!is_array($value) && !in_array($key,["PHPSESSID","api"])) {
							if (strlen($value."")<50) {
								$vv[] = "$key=".$value;
							}
						}
					}
					$vv = join(", ",$vv);
					try {
						$fn($_REQUEST);
					} catch (Exception $e) {
						$msg = "[Erreur API $apiname] : ".$e->getMessage()."";
						self::apiRep("alert",$msg);		
					}
				$log = ob_get_clean();
				if(!empty($log)){
					self::apiRep("log",$log);
				}
			}
		}
	}

	static function runApi(){
		if (empty($_GET["api"])) {
			return;
		}
		if ($_SERVER["REQUEST_METHOD"] == "OPTIONS") {
			return true;
		}
		$c = ob_get_clean();
		$apiname = $_GET["api"];
		if (isset($_REQUEST["jsonDataApiTransfert"])) {
			$jsonDataApiTransfert = json_decode($_REQUEST["jsonDataApiTransfert"],true);
			unset($_REQUEST["jsonDataApiTransfert"]);
			$_REQUEST = array_merge($_REQUEST,$jsonDataApiTransfert);
		}


		$apiData = file_get_contents("php://input");
		if (!empty($apiData)) {
			$apiData = json_decode($apiData,true);
			if($apiData && is_array($apiData))
			foreach ($apiData as $key => $value) {
				$_REQUEST[$key] = $value;
			}
		}

		$_REQUEST = self::ClearObjNg($_REQUEST);
		unset($_REQUEST["enticacheapi"]);
		self::$apiMasterReponce = null;

		self::emitApiEvent("api:start");
		self::emitApiEvent("before:$apiname");

		foreach (self::$apiList as $api) {
			if ($api["name"] == $apiname) {
				$fn = $api["fn"];
				ob_start();
					$vv = [];
					foreach ($_REQUEST as $key => $value) {
						if (!is_array($value) && !in_array($key,["PHPSESSID","api"])) {
							if (strlen($value."")<50) {
								$vv[] = "$key=".$value;
							}
						}
					}
					$vv = join(", ",$vv);
					echo "api :: $apiname {  $vv }\n---------------------\n";
					try {
						$apiMasterReponce = $fn($_REQUEST);
						if (!is_null($apiMasterReponce) && !empty($apiMasterReponce)) {
							self::$apiMasterReponce = $apiMasterReponce;
						}
					} catch (Exception $e) {
						$msg = "[Erreur API $apiname] : ".$e->getMessage()."";
						echo "\n-----------------------\n$msg\n-----------------------\n";
						self::apiRep("alert",$msg);		
					}
				$log = ob_get_clean();
				if(!empty($log)){
					self::apiRep("log",$log);
				}
			}
		}
		self::emitApiEvent("after:$apiname");
		self::emitApiEvent("api:end");

		avs::run();
		$r = json_encode([
			"master"=>self::$apiMasterReponce,
			"slave"=>self::$apiListRep,
			]);
		if (!$r) {
			self::apiRep("log","Erreur json_encode MASTER api reponce !!!");
			$r = json_encode([
			"master"=>[],
			"slave"=>self::$apiListRep,
			]);
			if (!$r) {
				self::$apiListRep = [];
				self::apiRep("log","Erreur json_encode SLAVE api reponce !!!");
				$r = json_encode([
				"master"=>self::$apiMasterReponce,
				"slave"=>self::$apiListRep,
				]);
			}
		}
		echo $r;
		db::close();
		exit;
	}
	/* static function sendMail($to,$sujet,$content){
		$config = storge("config");
		ob_start();
		?>
			<div>
				<div style="width:100%;display: flex;padding: 20px;background: <?= $config["bgmenu"] ?>;">
					<img style="height: 50px;" src="https://<?= $_SERVER["HTTP_HOST"].$config["logo"] ?>">
				</div>
				<div style="min-height: 200px;padding: 20px;">
					<?= $content ?>
				</div>
				<div style="width:100%;display: flex;padding: 20px;background: <?= $config["bgmenu"] ?>;">
					<img style="height: 50px;" src="https://<?= $_SERVER["HTTP_HOST"].$config["logo"] ?>">
				</div>
			</div>
		<?php
		$code=ob_get_clean();
		$headers  = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
		$headers .= 'To: '.$to.' <'.$to.'>'. "\r\n";
		$headers .= 'From: '.app::$dom.' <contact@'.app::$dom.'>' . "\r\n";
		$msg ="<html><head><title>$sujet</title></head><body>$code</body></html>";
		mail($to,$sujet,$msg, $headers);
	} */
 }