<?php

function view($viewName){

	return dir . '/mp-content/view/' . SITE_THEME . '/' . $viewName . '.php';

}

function controller($controllerName){

	$controllerName = strtolower($controllerName);
	return dir . '/mp-content/controller/' . $controllerName . '.php';

}

function theme($path) {

	return site.'mp-content/view/' . SITE_THEME . '/'. $path;

}

function site($path = null) {
	return site.$path;
}

function title($string = null, $title = true) {
	if($title) {
		if($string) {
			return $string ." | ". TITLE;
		}
		return TITLE;
	}
	return $string;
}

function route($index){

	global $route;
	return isset($route[$index]) ? $route[$index] : false;

} 

function public_url($url = false){


	return site . 'mp-public/' . $url;

}

function admin_controller($controllerName){

	$controllerName = strtolower($controllerName);
	return dir . '/mp-admin/controller/' . $controllerName . '.php';

}

function admin_view($viewName){

	return dir . '/mp-admin/view/' . $viewName . '.php';

}


function admin_url($url = false){

	return site . 'admin/' . $url;

}

function admin_public_url($url = false){

	return site . 'mp-admin/public/' . $url;

}

function permission($url, $action){
	$permissions = json_decode(session('user_permissions'), true);
	if (isset($permissions[$url][$action]))
		return true;
	return false;
}

function file_download($_GETLINK){

		$url = $_GETLINK; // URL of what you wan to download
		$zipFile = "update.zip"; // Rename .zip file
		$extractDir = "extracted"; // Name of the directory where files are extracted
		$zipResource = fopen($zipFile, "w");

		// Get The Zip File From Server
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_FAILONERROR, true);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_AUTOREFERER, true);
		curl_setopt($ch, CURLOPT_BINARYTRANSFER,true);
		curl_setopt($ch, CURLOPT_TIMEOUT, 10);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
		curl_setopt($ch, CURLOPT_FILE, $zipResource);

		$page = curl_exec($ch);

		if(!$page) {
			return false;
		}

		curl_close($ch);

		return "OK";
	}

	function setting($name){

		global $settings;
		return isset($settings[$name]) ? $settings[$name] : false;

	}

	function backupDatabaseTables($dbHost,$dbUsername,$dbPassword,$dbName,$tables = '*'){
	    //veritabanı bağlantısı
		$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); 

	    //tüm tabloları alalım
		if($tables == '*'){
			$tables = array();
			$result = $db->query("SHOW TABLES");
			while($row = $result->fetch_row()){
				$tables[] = $row[0];
			}
		}else{
			$tables = is_array($tables)?$tables:explode(',',$tables);
		}

	    //tablolar içerisinde dönelim
		foreach($tables as $table){
			$result = $db->query("SELECT * FROM ".$table."");
			$numColumns = $result->field_count;

			$return = "DROP TABLE ".$table.";";

			$result2 = $db->query("SHOW CREATE TABLE ".$table."");
			$row2 = $result2->fetch_row();

			$return .= "\n\n".$row2[1].";\n\n";

			for($i = 0; $i < $numColumns; $i++){
				while($row = $result->fetch_row()){
					$return .= "INSERT INTO ".$table." VALUES(";
					for($j=0; $j < $numColumns; $j++){
						$row[$j] = addslashes($row[$j]);
						$row[$j] = preg_replace("\n","\\n",$row[$j]);
						if (isset($row[$j])) { $return .= '"'.$row[$j].'"' ; } else { $return .= '""'; }
						if ($j < ($numColumns-1)) { $return.= ','; }
					}
					$return .= ");\n";
				}
			}

			$return .= "\n\n\n";
		}

	    //dosyayı kaydedelim
		$handle = fopen('db-backup-'.time().'.sql','w+');
		fwrite($handle,$return);
		fclose($handle);
	}

	function str_date($date, $delimiter = "-", $input = "y-m-d", $output = "d-m-y") {

		$date = explode(" ", $date);

		$time = "";

		if(isset($date[1])) {

			$time = " ".$date[1];

		}

		$date = $date[0];

		$months = array(

			"1" => "Ocak", "2" => "Şubat", "3" => "Mart", "4" => "Nisan", "5" => "Mayıs", "6" => "Haziran", "7" => "Temmuz", "8" => "Ağustos", "9" => "Eylül", "10" => "Ekim", "11" => "Kasım", "12" => "Aralık"

		);

		$date = explode($delimiter, $date);

		$type = explode("-", $input);

		if(strlen($date[array_search("d",$type)]) > 1) {

			if($date[array_search("d",$type)][0] == 0) {

				$date[array_search("d",$type)] = $date[array_search("d",$type)][1];

			}

		}

		if(strlen($date[array_search("m",$type)]) > 1) {

			if($date[array_search("m",$type)][0] == 0) {

				$date[array_search("m",$type)] = $date[array_search("m",$type)][1];

			}

		}

		$output_type = explode("-", $output);

		$mm = $date[array_search("m",$type)];

		foreach($months as $key => $val) {

			if($key == $mm) {

				$month = $val;

			}

		}

		$date[array_search("m",$type)] = $month;

		$output_str = $date[array_search($output_type[0],$type)]." ".$date[array_search($output_type[1],$type)]." ".$date[array_search($output_type[2],$type)].$time;

		return $output_str;

		

	}


	function import_sql($file){

		global $db;

		$query = '';
		$sqlScript = file($file);
		foreach ($sqlScript as $line)	{

			$startWith = substr(trim($line), 0 ,2);
			$endWith = substr(trim($line), -1 ,1);

			if (empty($line) || $startWith == '--' || $startWith == '/*' || $startWith == '//') {
				continue;
			}

			$query = $query . $line;
			if ($endWith == ';') {

				$islem = $db->query($query);
				
				if($islem){
					$result = "OK";
				}else{
					$result = "FAIL";
				}

				$query= '';		
			}
		}

	}

	function discord_api($type, $message){

		global $db, $settings;

		if($type == 1){

			$dcq = $db->from('integrations')->where('app_id', 2)->first();
			$dc = json_decode($dcq['app_data'], true);
			$webhookurl = $dc['discord_apiNotify_url'];

			$json_data = array (
				'content'=> $message, 
				'username'=>"MoonPanel Sağlayıcı Bildirimi"
			);

			$make_json = json_encode($json_data);
			$ch = curl_init( $webhookurl );
			curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
			curl_setopt( $ch, CURLOPT_POST, 1);
			curl_setopt( $ch, CURLOPT_POSTFIELDS, $make_json);
			curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
			curl_setopt( $ch, CURLOPT_HEADER, 0);
			curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
			$response = curl_exec( $ch );

			if($response){
				$result = true;
			}else{
				$result = false;
			}

		}elseif($type == 2){

			$dcq = $db->from('integrations')->where('app_id', 2)->first();
			$dc = json_decode($dcq['app_data'], true);
			$webhookurl = $dc['discord_notify_url'];

			$json_data = array (
				'content'=> $message, 
				'username'=>"MoonPanel Panel Bildirimi"
			);

			$make_json = json_encode($json_data);
			$ch = curl_init( $webhookurl );
			curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
			curl_setopt( $ch, CURLOPT_POST, 1);
			curl_setopt( $ch, CURLOPT_POSTFIELDS, $make_json);
			curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
			curl_setopt( $ch, CURLOPT_HEADER, 0);
			curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
			$response = curl_exec( $ch );

			if($response){
				$result = true;
			}else{
				$result = false;
			}
			

		}else{

			$result = false;

		}

		return $result;

	}

	function array_group_by(array $arr, $key) { 
		if (!is_string($key) && !is_int($key) && !is_float($key) && !is_callable($key)) {
			trigger_error('array_group_by(): The key should be a string, an integer, a float, or a function', E_USER_ERROR);
		}
		$isFunction = !is_string($key) && is_callable($key);
		$grouped = [];
		foreach ($arr as $value) {
			$groupKey = null;
			if ($isFunction) {
				$groupKey = $key($value);
			} else if (is_object($value)) {
				$groupKey = $value->{$key};
			} else {
				$groupKey = $value[$key];
			}
			$grouped[$groupKey][] = $value;
		}
		if (func_num_args() > 2) {
			$args = func_get_args();
			foreach ($grouped as $groupKey => $value) {
				$params = array_merge([$value], array_slice($args, 2, func_num_args()));
				$grouped[$groupKey] = call_user_func_array('array_group_by', $params);
			}
		}
		return $grouped;
	
	}

	function priceFormat($price){
		$priceExplode = explode(".",$price);
		if( $priceExplode[1] )
		{
			if( strlen($priceExplode[1]) == 1 )
			{
				return $price."0";
			}else
			{
				return $price;
			}
		}else{
			return $price."";
		}
	}

	function serviceTypeGetList($type){

		switch ($type) {

			case "Default":
			$service_type = 1;
			break;
			case "Package":
			$service_type = 2;
			break;
			case "Custom Comments":
			$service_type = 3;
			break;
			case "Custom Comments Package":
			$service_type = 4;
			break;
			case "Mentions":
			$service_type = 5;
			break;
			case "Mentions with hashtags":
			$service_type = 6;
			break;
			case "Mentions custom list":
			$service_type = 7;
			break;
			case "Mentions custom list":
			$service_type = "8";
			break;
			case "Mentions user followers":
			$service_type = 9;
			break;
			case "Mentions media likers":
			$service_type = 10;
			break;
			case "Subscriptions":
			$service_type = 11;
			break;

			default:
			$service_type = 1;
			break;

		}

		return $service_type;
	}

	function surehesapla(array $tarih){
		$toplam = 0;
		foreach($tarih as $t){
			$bol = explode('/',$t);
			$olusturma = strtotime($bol[0]);
			$tamamlanma = strtotime($bol[1]);
			$fark = $olusturma-$tamamlanma;
			$gecendakika = floor($fark / (60));
			$toplam += $gecendakika;
		}
		$toplam = $toplam/count($tarih);
		$dakika = $toplam % 60;
		$saat = ceil($toplam / 60)-1;
		if($saat<0){
			$saat=0;
		}
		if($dakika<=0){
			$dakika=1;
		}
		return $saat." Saat ".$dakika." Dakika";

	}

	function getservicetime($service_id){

		global $db;

		if($service_id){

			$order = $db->from('orders')->where('service_id', $service_id)->where('order_status', 'Completed')->limit(0, 10)->all();

			if($order){

				$totalRecord = $db->from('orders')->where('service_id', $service_id)->where('order_status', 'Completed')->select('count(service_id) as total')->total();

				if($totalRecord <= 9){

					$return = "Yeterli Veri Yok";

				}else{

					$siparisler = array();

					foreach($order as $row):
						$siparisler[] =  date('y-m-d h:m:s', $row['update_date'])."/".date('y-m-d h:m:s', $row['order_date']);
					endforeach;

					$return = surehesapla($siparisler);

				}

			}else{

				$return = "Yeterli Veri Yok";

			}
			

		}else{

			$return = "Yeterli Veri Yok";

		}

		return $return;

	}

	function generate_shopier_form($data){
		$api_key  = $data->apikey;
		$secret  = $data->apisecret;
		$user_registered = date("Y.m.d");
		$time_elapsed = time() - strtotime($user_registered);
		$buyer_account_age = (int)($time_elapsed/86400);
		$currency = 0;
		$dataArray = $data;

		$productinfo = $data->item_name;
		$producttype = 1;


		$productinfo = str_replace('"','',$productinfo);
		$productinfo = str_replace('"','',$productinfo);
		$current_language=0;
		$current_lan=0;
		$modul_version=('1.0.4');
		@srand(time(NULL));
		$random_number=rand(1000000,9999999);
		$args = array(
			'API_key' => $api_key,
			'website_index' => $data->website_index,
			'platform_order_id' => $data->order_id,
			'product_name' => $productinfo,
			'product_type' => $producttype,
			'buyer_name' => $data->buyer_name,
			'buyer_surname' => $data->buyer_surname,
			'buyer_email' => $data->buyer_email,
			'buyer_account_age' => $buyer_account_age,
			'buyer_id_nr' => 0,
			'buyer_phone' => $data->buyer_phone,
			'billing_address' => $data->billing_address,
			'billing_city' => $data->city,
			'billing_country' => "TR",
			'billing_postcode' => "",
			'shipping_address' => $data->billing_address,
			'shipping_city' => $data->city,
			'shipping_country' => "TR",
			'shipping_postcode' => "",
			'total_order_value' => $data->ucret,
			'currency' => $currency,
			'platform' => 0,
			'is_in_frame' => 1,
			'current_language'=>$current_lan,
			'modul_version'=>$modul_version,
			'random_nr' => $random_number
		);

		$data = $args["random_nr"].$args["platform_order_id"].$args["total_order_value"].$args["currency"];
		$signature = hash_hmac("SHA256",$data,$secret,true);
		$signature = base64_encode($signature);
		$args['signature'] = $signature;

		$args_array = array();
		foreach($args as $key => $value){
			$args_array[] = "<input type='hidden' name='$key' value='$value'/>";
		}
		if( !empty($dataArray->apikey) && !empty($dataArray->apisecret) && !empty($dataArray->website_index) ){
			$_SESSION["data"]["payment_shopier"]  = true;

			return '<html> <!doctype html><head> <meta charset="UTF-8"> <meta content="True" name="HandheldFriendly"> <meta http-equiv="X-UA-Compatible" content="IE=edge">
			<meta name="robots" content="noindex, nofollow, noarchive" />
			<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0" /> <title lang="tr">Güvenli Ödeme Sayfası</title><body><head>
			<form action="https://www.shopier.com/ShowProduct/api_pay4.php" method="post" id="shopier_payment_form" style="display: none">' . implode('', $args_array) .
			'<script>setInterval(function(){document.getElementById("shopier_payment_form").submit();},2000)</script></form></body></html>';
		}

	}

	function dizinicek($dizin) {

		$sonuc = array();
		$cdir = scandir($dizin);

		foreach ($cdir as $anahtar => $deger){
			if (!in_array($deger,array(".",".."))){
				if (is_dir($dizin . DIRECTORY_SEPARATOR . $deger)){
					$sonuc['folder'][$deger] = $anahtar;
				}else{
					$sonuc[$anahtar] = $deger;
				}
			}
		}

		return $sonuc;

	}


	function CheckColumn($table, $column){

		global $db;

		if(count($db->query("SHOW COLUMNS FROM `".$table."` LIKE '".$column."'")->fetchAll())){
		    return true;
		}else{
		    return false;
		}

	}

	function CreateColumn($table, $columnName, $column){

		global $db;

		$html = "ALTER TABLE `".$table."` ADD `".$columnName."`";

		if($column['int'] !== false){
			$html .= ' int('.$column['int'].')';
		}

		if($column['varchar'] !== false){
			$html .= ' varchar('.$column['varchar'].')';
		}

		if($column['timestamp'] !== false){
			$html .= ' TIMESTAMP';
		}

		if($column['mediumtext'] !== false){
			$html .= ' MEDIUMTEXT';
		}

		if($column['text'] !== false){
			$html .= ' TEXT';
		}

		if($column['tinyint'] !== false){
			$html .= ' TINYINT('.$column['tinyint'].')';
		}

		if($column['double'] !== false){
			$html .= ' DOUBLE';
		}

		if($column['datetime'] !== false){
			$html .= ' DATETIME';
		}

		if($column['default'] !== false){

			if($column['default'] == null){
				$html .= ' NULL DEFAULT NULL';
			}else{
				$html .= ' DEFAULT '.$column['default'].'';
			}
						
		}

		if($column['PRIMARY_KEY'] == true):
			$html .= 'AUTO_INCREMENT , PRIMARY KEY(`'.$columnName.'`))';
		endif;

		try{
	        $result = $db->query("".$html."");
	        return true;
	    }catch (Exception $e){
	        return false;
	    }

	}

	function TableExists($table){

		global $db;

		try{
	        $result = $db->query("SELECT 1 FROM ".$table." LIMIT 1");
	        return true;
	    }catch (Exception $e){
	        return false;
	    }

	}

	function CreateBulkTable($tableName, array $arr){

		global $db;

		foreach($arr as $key => $deger){

			if($tableName == $key){

				$columns = array_keys($deger);
				$veri = [];

				$html = 'CREATE TABLE IF NOT EXISTS `'.$key.'` (';

				foreach($columns as $num => $title){

					$html .= '`'.$title.'`';

					if($deger[$title]['int'] !== false){
						$html .= ' int('.$deger[$title]['int'].')';
					}

					if($deger[$title]['varchar'] !== false){
						$html .= ' varchar('.$deger[$title]['varchar'].')';
					}

					if($deger[$title]['timestamp'] !== false){
						$html .= ' TIMESTAMP';
					}

					if($deger[$title]['mediumtext'] !== false){
						$html .= ' MEDIUMTEXT';
					}

					if($deger[$title]['text'] !== false){
						$html .= ' TEXT';
					}

					if($deger[$title]['tinyint'] !== false){
						$html .= ' TINYINT('.$deger[$title]['tinyint'].')';
					}

					if($deger[$title]['double'] !== false){
						$html .= ' DOUBLE';
					}

					if($deger[$title]['datetime'] !== false){
						$html .= ' DATETIME';
					}

					if($deger[$title]['default'] !== false){

						if($deger[$title]['default'] == null){
							$html .= ' NULL DEFAULT NULL';
						}else{
							$html .= ' DEFAULT '.$deger[$title]['default'].'';
						}
						
					}

					if($deger[$title]['PRIMARY_KEY'] == true):
						$veri['primary_status'] = true;
						$veri['column_title'] = $title;
						$html .= ' AUTO_INCREMENT';
					endif;

					$html .= ', ';

					

				}

				$primaryStatus = $veri;

				if($primaryStatus['primary_status'] == true){
					$html .= ' PRIMARY KEY(`'.$primaryStatus['column_title'].'`))';
				}

				try {
					$query = $db->prepare("".$html."");
					$query->execute();
					return true;
				}
				catch (PDOException $e) {
				  	return $e->getMessage();
				}

			}

		}

	}