<?php
defined('ABSPATH') or die('NO!! or yes!! :3');
Class Madness_main{
	function __construct(){
		add_action('plugins_loaded',array($this,"loading_set_lang"));
		add_action('init',array($this,"loading_set_lang"));
		add_action("wp_ajax_load_madness", array($this,"load_madness"));
		add_action("wp_ajax_nopriv_load_madness", array($this,"load_madness") );
	}
	static public $clang='';
	function loading_set_lang(){
		if(isset($_COOKIE['lang'])){
			$this->madness_set_lang($_COOKIE['lang']);
		}
	}
	function load_madness(){
		if ( !wp_verify_nonce( $_REQUEST['nonce'], "load_madness")) {
			/* nonce not provided */
			exit($this->madness_error('mad_001'));
		}
		if( !isset( $_REQUEST['type'])){
			/* type of request not provided... */
			exit($this->madness_error('mad_002'));
		}
		if( !isset( $_REQUEST['value'])){
			/* value of request not provided... */
			exit($this->madness_error('mad_003'));
		}
		if( !isset( $_REQUEST['curl'])){
			/* value of request not provided... */
			exit($this->madness_error('mad_005'));
		}
		switch($_REQUEST['type']){
			case 'language':
				$this->madness_lang();
			break;
			case 'cookie':
				$this->madness_cookie();
			break;
			case 'pre':
				$this->madness_preloader();
			break;
			case 'page':
				try{
				$this->madness_render();
				}catch(Exception $e){
					print_r($e);
				}
			break;
		}
		die();
	}
	function madness_preloader(){
		if(is_object($_REQUEST['value'])){
			$_REQUEST['value']=(array) $_REQUEST['value'];
		}
		if(is_array($_REQUEST['value'])){
			switch($_REQUEST['value']['type']){
				case 'lang':
					if($this->madness_set_lang($_REQUEST['value']['language'])!=true){
						$this->madness_set_lang('en');
					}
					ob_start();
					require_once(get_template_directory().'/inc/Header/menus.php');
					$menu=ob_get_clean();
					$link=$_REQUEST['curl'];
					$link=str_replace(site_url().'/', '', $link);
					$olink='';
					$nlink='';
					$oslug='';
					$pg='';
					$iclid='';
					if($this->madness_lang_url_check($_REQUEST['curl'])==true){
						/* check for repeatness */
						$olink=explode('/',rtrim($link, '/'));
						$nlink=explode('/',str_replace(site_url().'/', '', get_site_url()));
						if($olink[0]!=$nlink[0]){
							/*remake link plz....*/
							$olink[0]=null;
							$oslug=implode('/',$olink);
							if($oslug===''){
								$pg=get_page(get_option('page_on_front'));
								$icl_id=icl_object_id($pg->ID, 'page', false,self::$clang);
								$link=get_the_permalink($icl_id);
							}else{
								$pg=get_page_by_path($oslug);
								$icl_id=icl_object_id($pg->ID, 'page', false,self::$clang);
								$link=get_the_permalink($icl_id);
							}
						}
					}else{
						
						if($link==''){
							$pg=get_page(get_option('page_on_front'));
							$icl_id=icl_object_id($pg->ID, 'page', false,self::$clang);
							$link=get_the_permalink($icl_id);
						}else{
							/* ok.... it apears that is the default lang... */
							
							$olink=explode('/',rtrim($link, '/'));
							$nlink=explode('/',str_replace(site_url(), '', get_site_url()));
							if($olink[0]!=$nlink[0]){
								/*remake link plz....*/
								$nlink[0]=null;
								$oslug=implode('/',$olink);
								$pg=get_page_by_path($oslug);
								$icl_id=icl_object_id($pg->ID, 'page', false,self::$clang);
								$link=get_the_permalink($icl_id);
							}
						}
					}
					define('mad_pos_lag',true,true);
					ob_start();
					require_once(get_template_directory().'/inc/Header/preloader.php');
					$preloader=ob_get_clean();
					exit(json_encode(array(
						'm'=>$menu,
						'pre'=>$preloader,
						'c'=>true,
						'curl'=>$link,
						'h'=>$pg,
						'n'=>wp_create_nonce("load_madness"),
						't'=>get_the_title($pg->ID).' - '.get_bloginfo('name'),
						'olink'=>$olink,
						'nlink'=>$nlink,
						'lang'=>$_COOKIE['lang'],
						'pg'=>$pg,
						'oslug'=>$oslug,
						'iclid'=>$iclid,
						'chos'=>$this->madness_lang_url_check(),
						''
					),true));
				break;
				case 'cookie':
					$this->madness_cookie();
				break;
			}
		}
		return false;
	}
	function madness_error($e){
		switch($e){
			case 'mad_001':
				/* nonce not provided */
				return json_encode(array(
					'e'=>'mad_001',
					'm'=>__("I'm not mad.... are you?",tdomain),
					'n'=>wp_create_nonce("load_madness")
				),true);
			break;
			case 'mad_002':
				/* type of request not provided... */
				return json_encode(array(
					'e'=>'mad_002',
					'm'=>__("ok.... stop it please",tdomain),
					'n'=>wp_create_nonce("load_madness")
				),true);
			break;
			case 'mad_003':
				/* value of request not provided... */
				return json_encode(array(
					'e'=>'mad_003',
					'm'=>__("What are you trying to do?",tdomain),
					'n'=>wp_create_nonce("load_madness")
				),true);
			break;
			case 'mad_004':
				/* value of request not provided... */
				return json_encode(array(
					'e'=>'mad_004',
					'm'=>__("Ok.... proceding to your next destination",tdomain),
					'redirect'=>'https://www.google.com/',
					'n'=>wp_create_nonce("load_madness")
				),true);
			break;
			case 'mad_005':
				/* value of request not provided... */
				return json_encode(array(
					'e'=>'mad_005',
					'm'=>__("Ok.... this may be a glich... or NOT!",tdomain),
					'redirect'=>'https://www.google.com/',
					'n'=>wp_create_nonce("load_madness")
				),true);
			break;
		}
	}
	function madness_render(){
		//get_page_by_path($page_path)
		if($_REQUEST['value']!=='')
		{
			if($this->madness_lang_url_check()===false){
				$page = get_page_by_path( $_REQUEST['value'] );
				$template=get_page_template_slug( $page->ID );
			}else{
				$urlsplit=explode('/',$_REQUEST['value']);
				if(count($urlsplit)>1){
					$lang=$urlsplit[0];
					$this->madness_set_lang($lang);
					$urlsplit[0]=null;
					$nurl=implode('/',$urlsplit);
					$page = get_page_by_path( $nurl );
					$template=get_page_template_slug( $page->ID );
				}else{
					$pid=get_option( 'page_on_front' );
					$page=get_post($pid);
					$template=get_page_template_slug( $pid );
				}
			}
		}else{
			$pid=get_option( 'page_on_front' );
			$page=get_post($pid);
			$template=get_page_template_slug( $pid );
		}
		if($template===''){
			$template='/templates/'.'Default.php';
		}
		;
		//var_dump(is_page($page)); 
		//var_dump(is_single($page));
		//var_dump(is_404($page));
		//var_dump();
		//die();
		if(is_string($template) && ($page instanceof WP_Post)){
			define('ajax_call',true,true);
			ob_start();
			global $post;
			$post=$page;
			require_once(get_template_directory().'/'.$template);
			$pg=ob_get_clean();
			$response=array(
				'm'=>'ok',
				'c'=>true,
				'curl'=>get_the_permalink($page->ID),
				'h'=>$pg,
				'n'=>wp_create_nonce("load_madness"),
				't'=>get_the_title($page->ID).' - '.get_bloginfo('name'),
				'content'=>get_extended($page->post_content),
				'page'=>$page,
				'also'=>get_the_content($page->ID)
			);
			exit(json_encode($response));
		}else{
			define('ajax_call',true,true);
			ob_start();
			require_once(get_template_directory().'/404.php');
			$pg=ob_get_clean();
			$response=array(
				'm'=>'ok',
				'c'=>true,
				'curl'=>get_the_permalink($page->ID),
				'h'=>$pg,
				'n'=>wp_create_nonce("load_madness"),
				't'=>get_the_title()
			);
			exit(json_encode($response));
		}
	}
	function madness_cookie(){
		switch($_REQUEST['value']['cookie']){
			case '1':
			case true:
			case "true":
				
					ob_start();
					require_once(get_template_directory().'/inc/Header/menus.php');
					$preloader=ob_get_clean();
				$response=array(
					'm'=>$preloader,
					'c'=>true,
					'curl'=>$_REQUEST['curl'],
					'n'=>wp_create_nonce("load_madness")
				);
				$this->set_cookie_policy();
				exit(json_encode($response,true));
			break;
			case '0':
			case false:
			case "false":
			default:
				$response=$this->madness_error('mad_004');
				exit(json_encode($response,true));
			break;
		}
	}
	function madness_lang_url_check(){
		$langs=icl_get_languages('skip_missing=N&orderby=KEY&order=DIR&link_empty_to=str');
		if(is_array($langs) && isset($langs[$_REQUEST['value']])){
			return true;
		}elseif(isset($_REQUEST['value']['language'])){
			$link=(str_replace(site_url().'/', '', $_REQUEST['curl']));
			$lang=explode('/',$link);
			$lang=$lang[0];
			if(is_array($langs) && isset($langs[$lang])){
				return true;
			}
		}
		$lang=explode('/',$_REQUEST['value']);
		$lang=$lang[0];
		if(is_array($langs) && isset($langs[$lang])){
			return true;
		}
		return false;
	}
	function get_cookie_policy(){
		if(isset($_COOKIE['__cp'])){
			return $_COOKIE['__cp'];
		}
		return false;
	}
	function set_cookie_policy(){
		if(!isset($_COOKIE['__cp'])){
			setcookie('__cp','30/07/2017',time() + (60*60*24*365*2),'/',$_SERVER['SERVER_NAME'],TRUE,false); // 2 years
		}
		return false;
	}
	function get_lang(){
		if(isset($_COOKIE['lang'])){
			return $_COOKIE['lang'];
		}
		return false;
	}
	function madness_set_lang($lang){
		global $sitepress;
		$langs=icl_get_languages('skip_missing=N&orderby=KEY&order=DIR&link_empty_to=str');
		if(isset($langs[$lang])){
			$sitepress->switch_lang($lang, true);
			self::$clang=$lang;
			setcookie('lang',$lang,time() + (60*60*24*365*2),'/',$_SERVER['SERVER_NAME'],TRUE,false); // 2 years
			return true;
		}
		return false;
	}
	function madness_lang(){
		global $sitepress;
		$browser_lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
		$langs=icl_get_languages('skip_missing=N&orderby=KEY&order=DIR&link_empty_to=str');
		$response=array(
			'm'=>'ok',
			'r'=>'',
			'curl'=>site_url().'/',
			'n'=>wp_create_nonce("load_madness")
		);
		if(is_array($langs) && isset($langs[$_REQUEST['value']])){
			$this->madness_set_lang($_REQUEST['value']);
			$response['curl'].=$_REQUEST['value'].'/';
		}elseif(is_array($langs) && isset($langs[$_REQUEST['value'].'-'.$_REQUEST['value']])){
			$this->madness_set_lang($_REQUEST['value'].'-'.$_REQUEST['value']);
			$response['curl'].=$_REQUEST['value'].'-'.$_REQUEST['value'].'/';
		}elseif(is_array($langs) && isset($langs[$browser_lang])){
			$this->madness_set_lang($browser_lang);
			$response['curl'].=$browser_lang.'/';
		}elseif(is_array($langs) && isset($langs[$browser_lang.'-'.$browser_lang])){
			$this->madness_set_lang($browser_lang.'-'.$browser_lang);
			$response['curl'].=$browser_lang.'/';
		}else{
			$this->madness_set_lang('en');
			$response['curl'].='en/';
		}
		exit(json_encode($response,true));
	}
}
global $mad;
$Madness_main=new Madness_main();
$mad=$Madness_main;