<?php
/***************************************************************************
*                                                                          *
* Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
*                                                                          *
* This  is  commercial  software,  only  users  who have purchased a valid *
* license  and  accept  to the terms of the  License Agreement can install *
* and use this program.                                                    *
*                                                                          *
****************************************************************************
* PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
* "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
****************************************************************************/

//
//$Id: router.engine.php,v 1.0 2011/06/14 20:52:11
//Router - Router Engine for Oorjit Deal System
//
class Router {
	protected $ObjModel;
  	protected $_controller;
  	protected $_controllerDIR;
  	protected $_controllerAction;
  	protected $_model;
  	protected $_sub_section;
  	public static $controllerInstance;
        public static $langID;
        	
	//Constructor of Router class
  	public function __construct () 
  	{		
		$this->_modelDIR  		=       __CORE_MODELS_PATH;
                $this->_seoModules              =       __SYSTEM_SEO_MODULES;
		$this->init();	
  	}
  
  	//To inistialize objects
  	private function init()
  	{
               
		$ObjRewrite	  				= Registry::getInstance('Rewrite');
		$ObjConfig	  				= Registry::getInstance('Config');
		$this->_sub_section			= isset($ObjRewrite->_sub_section) ? $ObjRewrite->_sub_section : '';
		$this->_controller  	 	= ((empty($ObjRewrite->_controller))?"Index":ucfirst($ObjRewrite->_controller))."Controller";
		$this->_controllerAction 	= ((empty($ObjRewrite->_controllerAction))?"Index":ucfirst(trim($ObjRewrite->_controllerAction)));
		if($ObjRewrite->_section == $ObjRewrite->_manageURLBase)
			$this->_controllerDIR  	= __CORE_MANAGE_CONTROLLERS_PATH;
		else if($ObjRewrite->_section == $ObjRewrite->_businessURLBase)
		    $this->_controllerDIR  	= __CORE_BUSINESS_CONTROLLERS_PATH;
		else if($ObjRewrite->_section == $ObjRewrite->_affiliateURLBase)
		    $this->_controllerDIR  	= __CORE_AFFILIATE_CONTROLLERS_PATH;
		else if($ObjRewrite->_section == $ObjRewrite->_mobilappURLBase)
		    $this->_controllerDIR  	= __CORE_MOBILAPP_CONTROLLERS_PATH;
		else
		  	 $this->_controllerDIR  = __CORE_FRONTEND_CONTROLLERS_PATH;
		$this->registerModelAutoLoader(); 
        //echo $_SERVER['QUERY_STRING'].strpos($_SERVER['QUERY_STRING'],$ObjRewrite->_htaccessVariable);
        if(strpos($ObjRewrite->_requestUrl,$ObjRewrite->_htaccessVariable)!== false){
             if($this->_controllerDIR==__CORE_FRONTEND_CONTROLLERS_PATH || $this->_controllerDIR==__CORE_MOBILE_CONTROLLERS_PATH){                
                     $this->sefRouter($ObjRewrite);           
                 } 
        }
                //URL REWITE PATH
               
        $this->setSettings($ObjRewrite);        
		$this->registerControllerAutoLoader();

//		if($this->_controllerDIR  == __CORE_FRONTEND_CONTROLLERS_PATH)
//			new BootStrapController();
//		$this->_controller  	 	= ((empty($ObjRewrite->_controller))?"Index":ucfirst($ObjRewrite->_controller));
//		$this->_controllerAction 	= ((empty($ObjRewrite->_controllerAction))?"Index":ucfirst(trim($ObjRewrite->_controllerAction)));
//		$this->setControllerAction();
//  	} 

		$this->setControllerAction($ObjRewrite);
		
  	}
	// //To load settings 
	// public function setSettings()  
	// {
		// $ObjConfig = new SettingsModel();
		// $settingsArray = $ObjConfig->listSettingsByGroup();                 
		// Registry::setInstance('_settings',$settingsArray);  
		// //echo "<pre>"; print_r($settingsArray);exit;
	// }
	//Get Settings details
	public function getSettings($keyGroupID,$keyID = "")  
	{
		$_settings	= Registry::getInstance('_settings');
		$_settings[$keyGroupID][$keyID] = isset($_settings[$keyGroupID][$keyID]) ? $_settings[$keyGroupID][$keyID]  : '';
		return $_settings[$keyGroupID][$keyID];	  
	}
     public function sefRouter($ObjRewrite)
    {
        $ObjLanguage        =   new LanguageModel();
        $ObjCook 	=   Registry::getInstance('Cookie'); 
        
        $cookie_langauge_lcid  = $ObjCook->getCookie($ObjRewrite->_section.'_LanguageLCIDstring');//LANGUAGE IN COOKIE
        $lcid_string = $ObjRewrite->_languageString;//LANGUAGE IN URL
        $current_langauge_id = $ObjCook->getCookie($ObjRewrite->_section.'_CurrentLanguageID'); // CURRENT LANGUAGE ID
        $shift = ($lcid_string!='' && $lcid_string!=$cookie_langauge_lcid)?1:0; // IF 
        //IF NO COOKIE LANGUAGE AND NO LANGUAGE IN URL ----FIRST PAGE LOAD
        if($cookie_langauge_lcid=='' && $lcid_string==''){
           $cookie_langauge_lcid =  $lcid_string = $ObjLanguage->currentLanguageLCIDstring();
        }else if($cookie_langauge_lcid=='' && $lcid_string!=''){ // LOAD PAGE with NO COOKIE AND LANGUAGE IN URL
            $cookie_langauge_lcid = $lcid_string;
        }else if($cookie_langauge_lcid!='' && $lcid_string==''){ // LOAD PAGE with COOKIE AND NO LANGUAGE IN URL
            $lcid_string = $cookie_langauge_lcid;            
        }else { // WITH COKIE & LANGUGE IN URL
            $cookie_langauge_lcid = $lcid_string;
        }
        
        $current_langauge_id  =  $ObjLanguage->setLanguageFromURL($cookie_langauge_lcid);
        if($current_langauge_id>0){
            $lcid_string = $cookie_langauge_lcid;
        } else {
            $lcid_string = $ObjLanguage->currentLanguageLCIDstring();
        }
      //  $ObjRewrite->_languageString = $lcid_string;
        if(isset($shift) && $shift>0 && $ObjRewrite->_languageString==$lcid_string){
                array_shift($ObjRewrite->_queryString);                   
                $ObjRewrite->_requestPage  	=	ltrim(substr($ObjRewrite->_requestPage,strlen($ObjRewrite->_languageString)), '/');
                $this->_controller		=((empty($ObjRewrite->_queryString[0]))?"Index": ucfirst($ObjRewrite->_queryString[0]))."Controller";;
                $this->_controllerAction		= isset($ObjRewrite->_queryString[1])?$ObjRewrite->_queryString[1]:'';                  
                
        }
        $ObjRewrite->_languageString = $lcid_string;
        $keySections = explode(',', SYSTEM_DIR_KEYS);  
        $this->langID = ($current_langauge_id=='')? $ObjLanguage->getDefaultLanguageID():$current_langauge_id; 
        
        if(!@in_array($this->_controller, $keySections) && (substr_count(strtolower($this->_controllerAction), "ajax")==0)){
            if($ObjRewrite->_requestPage!='')   {
			/* START : Brand Codes */
			$_requestPages = explode("/",$ObjRewrite->_requestPage);
			if($_requestPages[0] == 'brand' && count($_requestPages) > 2 ){
				$ObjRewrite->_requestPage = implode("/",array_slice($_requestPages, 2));
			}
			
			if($_requestPages[0] == 'store' && count($_requestPages) > 2 ){
				$ObjRewrite->_requestPage = implode("/",array_slice($_requestPages, 2));
			}
			
			/* END : Brand Codes */
			$ObjURLRewrite 	=   new UrlrewriteModel();           
			$current_langauge_id  =  ($current_langauge_id=='')? $ObjLanguage->getDefaultLanguageID():$current_langauge_id;    //CHECk FOR     
			$requestCases        =   $this->rewritePath($ObjRewrite->_requestPage);                   
			$addQryStrng         =   rtrim($requestCases[0],"/").'/';
			array_shift($requestCases);
			
			$languageIDs = array("Current"=>$this->langID);
			$paramsBrand            = array(
					'languageIDs' => $languageIDs,
					'brandName'   => FRANCHISEE
				);
			$ObjBrand  = new BrandModel();
			$brandDet  = $ObjBrand->getBrand($paramsBrand);
			$brandID   = !empty($brandDet) ? $brandDet['brandID']:1;  
			
			$pathResult      =   $ObjURLRewrite->getTargetPath($requestCases,$current_langauge_id,$brandID);    
			$TargetPathRes     =   $pathResult['target'];
                        $this->set_vars($TargetPathRes);
			if($pathResult['Redirect']=='RP'){
				//$location_url 			=  @rtrim($ObjRewrite->_requestHost,"/").'/'.$ObjRewrite->_languageString.'/'.$TargetPathRes;
				$location_url 			=  @rtrim($ObjRewrite->_requestHost,"/").'/'.$TargetPathRes;
                                header("Location:$location_url");
                                exit;
			}
			if($TargetPathRes!='')
			{
				$res= explode("/",$TargetPathRes);
				if(strtolower($res[0])==$ObjRewrite->_affiliateURLBase  || strtolower($res[0])==$ObjRewrite->_businessURLBase){
					$location_url 			=  @rtrim($ObjRewrite->_requestHost,"/").'/'.strtolower($res[0]).'/';
					header("Location:$location_url");
                                        exit;
				}else {
					$this->_controller=ucfirst($res[0])."Controller";
					$this->_controllerAction=ucfirst($res[1]);
					$TargetPathRes  .=$addQryStrng;
					/* START : Brand Codes */
					if($_requestPages[0] == 'brand' && count($_requestPages) > 2){
						$TargetPathRes  .= $_requestPages[0]."/".$_requestPages[1]."/";
					}
					if($_requestPages[0] == 'store' && count($_requestPages) > 2){
						$TargetPathRes  .= $_requestPages[0]."/".$_requestPages[1]."/";
					}
					/* END : Brand Codes */
					$ObjRewrite->_queryString  	= explode($ObjRewrite->_queryDelimiter,$TargetPathRes);
					$ObjRewrite->_targetPath  	= isset($resTargetPath['targetPath'])?$resTargetPath['targetPath']:'';
					$ObjRewrite->_targetPathType= isset($resTargetPath['type'])?$resTargetPath['type']:'';
				}
			}
			/* START : Brand Codes */
			else if($_requestPages[0] == 'brand' && count($_requestPages) > 1){
				$this->_controller	="CatalogController";
				$this->_controllerAction='Index';
				$TargetPathRes  .= 'catalog/'.$_requestPages[0]."/".$_requestPages[1]."/";
				$ObjRewrite->_queryString  	= explode($ObjRewrite->_queryDelimiter,$TargetPathRes);
			}
			/* END : Brand Codes */
            /* START : Brand Codes */
			else if($_requestPages[0] == 'store' && count($_requestPages) > 1){
				$this->_controller	="CatalogController";
				$this->_controllerAction='Index';
				$TargetPathRes  .= 'catalog/'.$_requestPages[0]."/".$_requestPages[1]."/";
				$ObjRewrite->_queryString  	= explode($ObjRewrite->_queryDelimiter,$TargetPathRes);
			}
			/* END : Brand Codes */
            $ObjRewrite->_controller = str_replace("Controller", "", $this->_controller);
            $ObjRewrite->_controllerAction = $this->_controllerAction;
        }
         }
    }
    public function set_vars($target_path){
        if(strpos($target_path, "?") !== false){
            $target_path = explode("?", $target_path);
            $addQryStrng = htmlspecialchars_decode($target_path[1]);
                if($addQryStrng!='/'){
                    $get_array = explode("&",rtrim($addQryStrng,'?'));
                    foreach($get_array as $full_param){
                        $params = explode("=", $full_param);
                        $_GET[$params[0]] = (!empty($params[1])) ? $params[1] : '';
                    }
                }
        }
    }
    //To load settings xml
    public function setSettings($ObjRewrite)   
    {
      
        $languageIDs = array("Current"=>$this->langID);
        $paramsBrand            = array(
                'languageIDs' => $languageIDs,
                'brandName'   => FRANCHISEE
            );
        $ObjBrand  = new BrandModel();
        $brandDet  = $ObjBrand->getBrand($paramsBrand);
        $brandID   = !empty($brandDet) ? $brandDet['brandID']:1;         
        //$ObjRewrite->_selBrandID = $brandID;       
        $ObjConfig = new SettingsModel();       
        $settingsArray = $ObjConfig->getcacheConfig($brandID);    
        $settingsArray['brand']['brandID'] = $brandID;
        Registry::setInstance('_settings',$settingsArray);    
       
    }
    public function rewritePath($pathInfo)
    {
            /**
         * We have two cases of incoming paths - with and without slashes at the end ("/somepath/" and "/somepath").
         * Each of them matches two url rewrite request paths - with and without slashes at the end ("/somepath/" and "/somepath").
         * Choose any matched rewrite, but in priority order that depends on same presence of slash and query params.
         */
        $pathInfo = addslashes($pathInfo);
        $requestCases = array();       
        $origSlash = (substr($pathInfo, -1) == '/') ? '/' : '';
        $orgPath = $requestPath = trim($pathInfo, '/');
        $requestpathArr =   explode("&",$pathInfo);              
        // If there were final slash - add nothing to less priority paths. And vice versa.
        $altSlash = $origSlash ? '' : '/';
        $requestPath  = $requestpathArr[0];
        array_shift($requestpathArr);
        $result = $this->_getQueryString($requestpathArr); // Query params in request, matching "path + query" has more priority
        $queryString = $result[0];
        $requestCases[] = $result[1];
        if($origSlash=='/'){
             $requestCases[] = "'".$orgPath ."'";
        }
        if ($queryString) {
            $requestCases[] = "'".$requestPath . $origSlash . '?' . $queryString."'";
            $requestCases[] = "'".$requestPath . $altSlash . '?' . $queryString."'";           
        }
        $requestCases[] = "'".$requestPath . $origSlash."'";
        $requestCases[] ="'". $requestPath . $altSlash."'";        
        return $requestCases;
    }
    public function _getQueryString($requestpath)
    {       
        if (!empty($requestpath)) {
            $queryParams = array();             
            $requestpath=implode("&",$requestpath);          
            parse_str($requestpath, $queryParams);
            $hasChanges = false;
            $qryStrng=  '';
            foreach ($queryParams as $key=>$value) {               
                if (substr($key, 0, 3) === '___') {
                    unset($queryParams[$key]);
                    $hasChanges = true;
                }
                $qryStrng  .= $key.'/'.$value.'/';
            } 
            $result=Array(http_build_query($queryParams),$qryStrng);
            
             return $result;
        }
        return false;
    }
   
  	// To register Model autoload function
  	private function registerModelAutoLoader()
  	{
		spl_autoload_register(array($this,'setModelClass'));
  	}
 
  	// To register Controller autoload function
  	private function registerControllerAutoLoader()
  	{
		spl_autoload_register(array($this,'setControllerClass'));
  	}
    
  	// Callback function To Autoload Model class
  	private function setModelClass($class)
  	{
        $autoload_include_path 	= $this->_modelDIR."/";
        $autoload_extension   	= '.php' ;
        $autoload_class_file	= $autoload_include_path.$class.$autoload_extension;
		if (trim($autoload_class_file)!="" && (substr_count($class,"Model")>0)){
		    if(file_exists($autoload_class_file))
				include_once($autoload_class_file);
			else
				return false;
		} 
		else
			return false;
  	}

  	//To set autoloading of the controller class
  	private function setControllerClass($class)
  	{  
  		if($this->_sub_section)
        	$autoload_include_path 	= $this->_controllerDIR."/".$this->_sub_section."/";
		else
			$autoload_include_path 	= $this->_controllerDIR."/";
        $autoload_extension   	= '.php' ;
        $autoload_class_file	= $autoload_include_path.$class.$autoload_extension;   
		if (trim($autoload_class_file)!="" && (substr_count($class,"Controller")>0)){
		    if(file_exists($autoload_class_file)){				
                                include_once($autoload_class_file);
			}else{                           
			  	$autoload_class_file	= $autoload_include_path."NotFoundController".$autoload_extension;
			  	include_once($autoload_class_file);
			}
		} 
		else
			return false;
  	}
  	//To set controller class
  	private function setControllerAction($ObjRewrite)
  	{
		$protocolseo = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "https://";
		$currentUrlseo = $protocolseo . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
		// 
		if(($currentUrlseo=='https://www.findyourbmw.ae/') || ($currentUrlseo=='https://findyourmini.ae/')){
			header("Location: ".$currentUrlseo."en/", true, 301);
		}
		
		$controllerClassName 	= $this->_controller ;
		if (class_exists($controllerClassName)) {              
			$ObjControllerClass = new $controllerClassName();
		} else {
			$ObjControllerClass = new NotFoundController();
			$this->_controller  ="NotFoundController";
		}
		
		// added for utm source
		if($this->_controller  == "NotFoundController" && isset($_GET["utm_source"]) && $_GET["utm_source"]!=''){ 
			$ObjControllerClass = new IndexController();
			$this->_controller  ="IndexController";
		}
		// added for utm source
		
		self::$controllerInstance = $ObjControllerClass;
		$controllerAction   		= ((trim($this->_controllerAction)=="")?"index":(trim($this->_controllerAction)))."Action";      
		if((method_exists($ObjControllerClass, $controllerAction))) {
			$ObjControllerClass->$controllerAction();
		} else {			
			//Access Restriction in Manage Section : Required not prevent access if action is not present
			if(strtolower($ObjRewrite->_section)==strtolower($ObjRewrite->_manageURLBase))
			{
				$location_url 			=  @rtrim($ObjRewrite->_requestHost,"/").'/'.strtolower($ObjRewrite->_manageURLBase).'/'.$ObjRewrite->_controller.'/index/';
				header("Location:$location_url");
				exit;
			}
			$ObjControllerClass->IndexAction();
			//$exception_error_message = "<br /><b>Application Error 451 </b>: Error found in <b>".$this->_controller."</b> Controler . ";
	   	  	//$exception_error_message .= "function <b>".$controllerAction."</b> not defined in this Controler.<br />";
			//echo $exception_error_message;
			//throw new ExceptionHandler($exception_error_message);
	   }
  	}

  	public static function getControllerInstance()
  	{
    	return self::$controllerInstance;	
  	}   
}
