<?php

namespace App\Services;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
/**
 * Description of APPURIParserManage
 *
 * @author Phattharaphon
 */
class APPURIParserManage {

    function APP_URIParsing(){        
        // define variable from config
        $_APP_SITE_NAME = config('site.config._APP_SITE_NAME');
        $pathCommon = Cache::get('pathCommon');
        
        /// Setting url parser
        $urlParser = $this->APP_URLParsing()['url'];

        //$memberPage = $maincore->GetTemplatePage(rawurldecode($urlParser[1]));
        $memberPage=""; //Waiting to support
        if($urlParser!=""){
            $dir = count($urlParser);
            $dirx = "";
            for($i=0;$i<$dir;$i++){
                $dirx .= "../";
            }
            //$_ACTION_VARsl['pathCommon'] = $dirx;
            Cache::forever('pathCommon', $dirx);//update pathCommon to $dirx
                if($_APP_SITE_NAME !== ""){
                    //$_ACTION_VARsl['pathCommon'] = $dirx.$_APP_SITE_NAME."/";
                    Cache::forever('pathCommon', $dirx);//update pathCommon to $dirx
                }

            //$_ACTION_VARsl['_WEBSERVICE'] = rawurldecode(APP_URLParserManage()['Template']);
            Cache::forever('_WEBSERVICE', rawurldecode($this->APP_URLParserManage()['Template']));//update _WEBSERVICE       
            $_WEBSERVICE = Cache::get('_WEBSERVICE');

            if(strpos($_WEBSERVICE , "-")){$_WEBSERVICE=rawurldecode($this->APP_URLParsing_WebService($_WEBSERVICE)['webservice']);}
            // _PAGE is application type
            //$_ACTION_VARsl['_PAGE'] = rawurldecode(APP_URLParserManage()['FileTemplate']);
            Cache::forever('_PAGE', rawurldecode($this->APP_URLParserManage()['FileTemplate']));//update _pathCommon_PAGE
            $_PAGE = Cache::get('_PAGE');            

            if($_PAGE==='' || $_PAGE==='index') { 
                //$_ACTION_VARsl['_PAGE']='home'; 
                Cache::forever('_PAGE', 'home');
                $_PAGE = Cache::get('_PAGE');
            }
            elseif(strpos($_PAGE , "-") && $_WEBSERVICE !== "goto"){
                $defaultPage = config('site.config.site.defaultPage');
                if( in_array( $_PAGE, $defaultPage) ){
                    //APP_URLParserManage()
                    //$_ACTION_VARsl['_PAGE']=rawurldecode(APP_URLParserManage()['FileTemplate']);
                    Cache::forever('_PAGE', rawurldecode($this->APP_URLParserManage()['FileTemplate']));
                }else{
                    //$_ACTION_VARsl['_PAGE']=rawurldecode(APP_URLParsing_WebService($_ACTION_VARsl['_PAGE'])['webservice']).'view';
                    Cache::forever('_PAGE', rawurldecode($this->APP_URLParsing_WebService($_ACTION_VARsl['_PAGE'])['webservice']).'view');                    
                }
            }
            elseif($memberPage){
                //$_ACTION_VARsl['_PAGE']='myaccount'; 
                Cache::forever('_PAGE', 'myaccount');            
            }

            //$_ACTION_VARsl['module'] = rawurldecode($module);
            //$_ACTION_VARsl['_CATEGORY'] = rawurldecode(APP_URLParserManage()['Category']);
            Cache::forever('_CATEGORY', rawurldecode($this->APP_URLParserManage()['Category']));
            if(isset($this->APP_URLParserManage()['CategoryID']) && $this->APP_URLParserManage()['CategoryID']!=""){
                //$_ACTION_VARsl['_CATEGORY_ID'] = rawurldecode(APP_URLParserManage()['CategoryID']);
                Cache::forever('_CATEGORY_ID',rawurldecode($this->APP_URLParserManage()['CategoryID']));
            }
            if(isset($this->APP_URLParserManage()['ContentType']) && $this->APP_URLParserManage()['ContentType']!=""){
                //$_ACTION_VARsl['_CONTENT_TYPE'] = rawurldecode(APP_URLParserManage()['ContentType']);
                Cache::forever('_CONTENT_TYPE', rawurldecode($this->APP_URLParserManage()['ContentType']));
            }
            if(isset($this->APP_URLParserManage()['ContentSubject'])){
                //$_ACTION_VARsl['_CONTENT'] = rawurldecode(APP_URLParserManage()['ContentSubject']);
                Cache::forever('_CONTENT', rawurldecode($this->APP_URLParserManage()['ContentSubject']));
            }
            if(isset($this->APP_URLParserManage()['ContentID']) && $this->APP_URLParserManage()['ContentID']!=""){
                //$_ACTION_VARsl['_CONTENT_ID'] = rawurldecode(APP_URLParserManage()['ContentID']);
                Cache::forever('_CONTENT_ID', rawurldecode($this->APP_URLParserManage()['ContentID']));
            }
            if(isset($this->APP_URLParserManage()['ContentTitle']) && $this->APP_URLParserManage()['ContentTitle']!=""){
                //$_ACTION_VARsl['_CONTENT_TITLE'] = rawurldecode(APP_URLParserManage()['ContentTitle']);
                Cache::forever('_CONTENT_TITLE', rawurldecode($this->APP_URLParserManage()['ContentTitle']));
            }
            if(isset($this->APP_URLParserManage()['ContentMetaKeyword']) && $this->APP_URLParserManage()['ContentMetaKeyword']!=""){
                //$_ACTION_VARsl['_CONTENT_KEYWORD'] = rawurldecode(APP_URLParserManage()['ContentMetaKeyword']);
                Cache::forever('_CONTENT_KEYWORD', rawurldecode($this->APP_URLParserManage()['ContentMetaKeyword']));
            }
            if(isset($this->APP_URLParserManage()['ContentMetaDesc']) && $this->APP_URLParserManage()['ContentMetaDesc']!=""){
                //$_ACTION_VARsl['_CONTENT_DESC'] = rawurldecode(APP_URLParserManage()['ContentMetaDesc']);
                Cache::forever('_CONTENT_DESC', rawurldecode($this->APP_URLParserManage()['ContentMetaDesc']));
            }
            //$_ACTION_VARsl['pageNumber'] = rawurldecode(APP_URLPageNumber());
            Cache::forever('pageNumber', rawurldecode($this->APP_URLParserManage()['APP_URLPageNumber']));

            $parameter = $this->APP_URLParsing()['parameter'];
            if($parameter) {
                //$_ACTION_VARsl['parameter'] = $parameter;
                Cache::forever('parameter', $parameter);
            }
        }else{
                //$_ACTION_VARsl[channel] = "renewable-energy.html";
        }
        execSpeedCheck("Complete");
        return TRUE;	
    }  /// End APP_URIParsing
        
    function APP_URLParsing(Request $request){      //// Manage url parser
        $urlParser = array();
        $urlParser['url'] = array();
        $urlParser['parameter'] = array();
        /// Cut url to array
        $urlParserURI = $request->getRequestUri();
        $urlCut = explodeNoEmpty($urlParserURI[0], "/");

        $stUriCnt = 0;
        for($i=$stUriCnt;$i<count($urlCut);$i++){
            if( !empty($urlCut[$i]) || $urlCut[$i]!==""){
                    array_push($urlParser['url'], $urlCut[$i]);
            }
        }

        if( count($urlParserURI) > 1 ){
            $urlParam = explode("&" , $urlParserURI[1] );
            for($i=0;$i<count($urlParam);$i++){
                if( !empty($urlParam[$i]) || $urlParam[$i] !== ""){
                    $paramVar = explode("=" , $urlParam[$i] );
                    if(isset($paramVar[0])){
                        $urlParser['parameter'][$paramVar[0]]=$paramVar[1];
                    }
                }
            }
        }

        $postParam = $_param;
        foreach($postParam as $key=>$value){
                $urlParser['parameter'][$key] = $value;
        }
        return $urlParser;
    } // End    
    
    /*
     * Function APP_URLParsing_WebService
     * Return Webservice and page as webserviceType
     */
    function APP_URLParsing_WebService($urlPath){
        $urlCut = explode("/" , $urlPath );
        if($urlCut[0]==="index"){
            $ret['webservice']="default"; // Set template file as default.php when url call to index.php or index.html
        }elseif(in_array ($urlCut[0], $conf['site']['seo']) ){
            $ret['webservice']="service"; // Set template for seo-rank
    //    }elseif($urlCut[0] === "seo-search-console" || $urlCut[0] === "seo-pagespeed"){ //  || $urlCut[0] === "seo-analytics"
    //        $ret['webservice']="seo-report"; // Set template for seo-rank
        }elseif(in_array($urlCut[0], $conf['site']['defaultPage'])){
            $ret['webservice']="default"; // Set template file as default.php when url call to index.php or index.html
        }else{
            $ret['webservice']=$urlCut[0];
        }
        //
        if(isset($urlCut[1])){
            $ret['webserviceType']=$urlCut[1];
        }
        return $ret;
    } // End

    //**** Manage template ****/        
    // if template is logon, register or logout, template is auth.
    // else template is as design
    //**** End Manage template ****/
    function APP_URLParserManage(){   /// 
        $_APP_SITE_NAME = config('site.config._APP_SITE_NAME');    
        $modules = array();
        /// Cut url to array
        $urlParser = $this->APP_URLParsing()['url'];
        ///
        $urlParserCnt = count($urlParser);
        if($_APP_SITE_NAME  !== ""){ // support code in sub root directory.
            array_shift($urlParser);
            $urlParserCnt = count($urlParser);
        }
        ///
        $sitePage = "";
        if( $urlParserCnt > 0 ){
            $sitePage = $urlParser[0];
            $modules = explode('.' , $urlParser[$urlParserCnt-1]);
        }
        ////////
        if( $urlParserCnt>0 && $urlParser[0] === $_APP_SITE_NAME){
            if(isset($urlParser[1])){
                $sitePage = $urlParser[1];
            }else{
                $retPage['Template'] = "home";
                $retPage['FileTemplate'] = "index";
                $retPage['Category'] = "";
                $retPage['ContentSubject'] = "";
                $retPage['ContentID'] = "";
                return $retPage;
            }
        }
        ////////
        /* Setting for template is default*/
        $retPage['Template'] = "";
        $retPage['FileTemplate'] = "";
        $retPage['Category'] = "";
        $retPage['ContentSubject'] = "";
        $retPage['ContentID'] = "";
        if( ($urlParserCnt>0 && $sitePage!=="get_ajax") && ((isset($modules[0]) && in_array($sitePage, config('site.config.fr_appconfig.front-end-search'))) || (isset($modules[0]) && in_array($modules[0], config('site.config.fr_appconfig.front-end-search')))) ){
            $retPage['Template'] = "auth";
            $retPage['FileTemplate'] = $sitePage;
            $retPage['Category'] = "";
            $retPage['ContentSubject'] = "";
            $retPage['ContentID'] = "";
        }
        else{
            if($urlParserCnt===0){
                $retPage['Template'] = "home";
                $retPage['FileTemplate'] = "index";
                $retPage['Category'] = "";
                $retPage['ContentSubject'] = "";
                $retPage['ContentID'] = "";
                return $retPage;
            }
            //////////////////////
            // check common template file and then assign to FileTemplate
            //////////////////////
            for($i=0;$i<count($urlParser);$i++){
                if($urlParser[$i]!='' || !empty($urlParser[$i])){
                    if( $urlParserCnt === 1 ){
    //                    $retPage['Template'] = $sitePage;
    //                    $retPage['Template'] = "blog";
                        if( strpos($urlParser[$i], "html") || strpos($urlParser[$i], "php") || $urlParser[$i]==="index"){
                            if( strpos($urlParser[$i], "html") || strpos($urlParser[$i], "php") ){
                                $parserArr = explode('.', $sitePage);
                                //// Set template
                                if($parserArr[0] === "index"){//|| in_array($urlCut[0], $conf['site']['defaultPage'])
                                    $retPage['Template'] = "default";
                                    $retPage['FileTemplate'] = "index";
                                }else{
                                    $retPage['Template'] = "home";
                                    $retPage['FileTemplate'] = "content-";
                                }
                                //////////////
    //                            $retPage['FileTemplate'] = getFileTemplate(APP_URLParsing_WebService($parserArr[0])['webservice']);
                            }else{
                                //// Set template
                                if($urlParser[$i] === "index"){
                                    $retPage['Template'] = "home";
                                }
                            }
                        }else{
                            $retPage['FileTemplate'] = $this->getFileTemplate(APP_URLParsing_WebService($urlParser[$i])['webservice']);
                            if(in_array($urlParser[$i], config('site.config.defaultPage'))){
                                $retPage['Template'] = "default";
                            }else{
                                $retPage['Template'] = $urlParser[$i];                            
                            }
                        }
                        $retPage['Category'] = "";
                        ////
                        $urlParserID = explode('-', explode('.', $sitePage)[0]);
                        if(isset($urlParserID[0])){$retPage['ContentType'] = $urlParserID[0];}
                        //
                        $retPage['ContentSubject'] = str_replace("_"," ",$sitePage);
                        ///////////////////////////////
                        //require_once _DAO_SERVICE_PATH.'class.g_content.php';
                        $contentObj = new GContent();
                        $content_title_eng = "";
                        if(isset($parserArr)){
                            $content_title_eng = str_replace("_"," ",$parserArr[0]);
                        }
                        $contentID=$contentObj->GetContentIDByTitleEng($content_title_eng);
                        if(isset($contentID)){$retPage['ContentID'] = $contentID;}
                        //
                        $contentType = $contentObj->GetContentType($retPage['ContentID']);
                        if(count($contentType)>0){$retPage['ContentType']=$contentType[0]['type_name_eng'];}
                        //
                        if(count($contentType)>0){$retPage['Template'] = $contentType[0]['type_name_eng'];}
                    }else if( $urlParserCnt === 2 ){ // for view page
                        $retPage['Template'] = $sitePage;
                        if( (in_array_multi(strtolower($retPage['Template']), array_values(config('site.config.fr_appconfig.front-end-search'))) ? TRUE : FALSE) === TRUE ){
                            $retPage['Template'] = array_keys(config('site.config.fr_appconfig.front-end-search'))[0];
                        }
                        //$retPage['FileTemplate'] = $sitePage;
                        $retPage['FileTemplate'] = $this->getFileTemplate(APP_URLParsing_WebService($sitePage)['webservice']);
                        $retPage['Category'] = $urlParser[1];
                        $retPage['ContentSubject'] = "";
                        ////
                        $urlParserID = explode('/', explode('.', $sitePage)[0]);
                        if(isset($urlParserID[0])){$retPage['ContentType'] = $urlParserID[0];}
                        $urlParserID = explode('-', explode('.', $urlParser[1])[0]);
                        if(isset($urlParserID[1])){$retPage['ContentSubject'] = $urlParserID[1];}
                        //////////////////////////////////////////////
                        //require_once _DAO_SERVICE_PATH.'class.g_category_type.php';
                        $categoryTypeObj = new GCategoryType();
                        $type_name_eng=str_replace("_"," ",$sitePage);
                        $typeID=$categoryTypeObj->getTypeIdByTypeNameEng($type_name_eng);
                        //////////////////////////////////////////////
                        //require_once _DAO_SERVICE_PATH.'class.g_category.php';
                        $categoryObj = new GCategory();
                        //
                        $cat_name_eng = str_replace("_"," ",$urlParser[1]);;
                        $categoryID=$categoryObj->GetCategoryByCatName($cat_name_eng , $typeID);
                        if( is_array($categoryID) && $categoryID!==NULL ){$retPage['CategoryID'] = $categoryID[0]['categoryID'];}
                    }else if( $urlParserCnt > 2 ){ // for category page
                        $retPage['Template'] = $sitePage;
                        //$retPage['FileTemplate'] = $urlParser[0]."-";
                        if($sitePage==="goto"){
                            $retPage['FileTemplate'] = $this->getFileTemplate($this->APP_URLParsing_WebService($sitePage)['webservice']);
                        }else{
                            $retPage['FileTemplate'] = $this->getFileTemplate($this->APP_URLParsing_WebService($sitePage)['webservice'])."-";
                        }
                        $retPage['Category'] = $urlParser[1];
                        if(strpos($urlParser[$i], "html")){
                            $parserArr = explode('.', $sitePage);
                            $retPage['ContentSubject'] = $parserArr[0];
                        }else{
                            $retPage['ContentSubject'] = $urlParser[1];
                        }
                        if(isset($sitePage) && $sitePage!==""){$retPage['ContentType'] = $sitePage;}
                        $urlParserID = explode('-', explode('.', $urlParser[2])[0]);
                        // Get content info by title_name_eng
                        if(count($urlParserID)===2){
                            $contentID = $urlParserID[0];
                        }else{
    //                        $content_title_eng = $urlParser[2];
                            //require_once _DAO_SERVICE_PATH.'class.g_content.php';
                            $contentObj = new GContent();
                            if(isset($content_title_eng)){
                                $content_title_eng = str_replace("_"," ",$content_title_eng);;
                                $contentID=$contentObj->GetContentIDByTitleEng($content_title_eng);
                            }
                        }
                        //
                        if(isset($urlParser[2])){$retPage['ContentSubject'] = str_replace("_"," ",$urlParser[2]);}
                        if(isset($contentID)){$retPage['ContentID'] = $contentID;}
                    }
                }
            }
        } // End if /// Check Login / Register / all authentication
        $retPage['ContentTitle']="";
        $retPage['ContentMetaKeyword']="";
        $retPage['ContentMetaDesc']="";
        if($retPage['ContentID']!=="" || $retPage['ContentSubject']!==""){
            if($retPage['ContentType']==="Gallery"){
                //////////////////////////////////////////
                //require_once _DAO_SERVICE_PATH.'class.g_gallery.php';
                $objDB = new GGallery();
                $objDB->selectById($retPage['ContentID']);
                $retPage['ContentTitle']=$objDB->galleryName." ".$objDB->tags;
                if($objDB->galleryBrief!=""){
                    $retPage['ContentMetaKeyword']=$objDB->galleryBrief." ".$objDB->tags;
                }else{
                    $retPage['ContentMetaKeyword']=$objDB->galleryName." ".$objDB->tags;
                }
                if($objDB->galleryDescription!=""){
                    $retPage['ContentMetaDesc']=$objDB->galleryDescription." ".$objDB->tags;
                }else{
                    $retPage['ContentMetaDesc']=$objDB->galleryName." ".$objDB->tags;
                }
            }else{
                if($retPage['ContentID']>0){
                    /////////////////////////////////
                    //require_once _DAO_SERVICE_PATH.'class.g_content.php';
                    $objDB = new GContent();
                    $objDB->selectById($retPage['ContentID']);
                    $retPage['ContentTitle']=$objDB->content_title." - ".$objDB->content_title_eng;
                    if($objDB->meta_keyword!==""){
                        $retPage['ContentMetaKeyword']=$objDB->meta_keyword." ".$objDB->tags;
                    }else{
                        $retPage['ContentMetaKeyword']=$objDB->content_title." ".$objDB->tags;
                    }
                    ///
                    if($objDB->meta_description!==""){
                        $retPage['ContentMetaDesc']=$objDB->meta_description." ".$objDB->tags;
                    }else{
                        $retPage['ContentMetaDesc']=$objDB->content_title." ".$objDB->content_subtitle." ".$objDB->tags;
                    }
                }elseif($retPage['ContentSubject']!==""){
                    if($retPage['ContentType'] === _MY_ACCOUNT){
                        if($retPage['Category']===""){
                            $retPage['FileTemplate'] = "index";
                        }else{
                            $retPage['FileTemplate'] = $retPage['Category'];
                        }
                    }else{
                        ////////////////////////////////////
                        //require_once _DAO_SERVICE_PATH.'class.g_category_type.php';
                        $categoryType = new GCategoryType(); 
                        $typeDetail = $categoryType->CheckType($retPage['ContentSubject']);
                        if(count($typeDetail) > 0){
                            $retPage['ContentTitle']=$typeDetail[0]['type_name']." - ".$typeDetail[0]['titleType'];
                            if($typeDetail[0]['metaKeywordType']!==""){
                                $retPage['ContentMetaKeyword']=$typeDetail[0]['metaKeywordType'];
                            }else{
                                $retPage['ContentMetaKeyword']=$typeDetail[0]['type_name']." ".$typeDetail[0]['type_name_eng'];
                            }
                            ///
                            if($typeDetail[0]['metaDescriptionType']!==""){
                                $retPage['ContentMetaDesc']=$typeDetail[0]['metaDescriptionType'];
                            }else{
                                $retPage['ContentMetaDesc']=$typeDetail[0]['type_name']." ".$typeDetail[0]['type_name_eng'];
                            }
                        }
                    }
                }
            }
        }else{
            if($retPage['ContentType'] === config('site.config._MY_ACCOUNT')){
                if($retPage['Category'] === ''){
                    $retPage['FileTemplate'] = "index";
                }else{
                    $retPage['FileTemplate'] = $retPage['Category'];
                }
            }
        }

        if(config('site.config.DEBUG_MODE')){
            echo "<pre> APP_URLParserManage() APP_URLParserManage ";print_r($retPage);echo "</pre>";
        }
        return $retPage;
    } // APP_URLParserManage

    /*
     * Function getFileTemplate
     * return $fileTemplate
     */
    function getFileTemplate($page=""){
        $keyIndex = array_search($page, array_keys(config('site.config.fr_appconfig.front-end-common.')));
        if($keyIndex !== FALSE){
            $urlParser = APP_URLParsing()['url'];
            $_arrFrontEndCommon = array_values(config('site.config.fr_appconfig.front-end-common.'))[$keyIndex];
            for($i=0;$i<count($_arrFrontEndCommon);$i++){
                if( $_arrFrontEndCommon[$i] === $urlParser[$keyIndex] ){
                    return $_arrFrontEndCommon[$i];
                }
            }
        }

        if( (in_array_multi($page, array_keys(config('site.config.fr_appconfig.front-end-common.'))) ? TRUE : FALSE) === TRUE ){
            return array_keys(config('site.config.fr_appconfig.front-end-common.'))[0];
        }elseif( (in_array_multi(strtolower($page), array_keys(config('site.config.fr_appconfig.front-end-search'))) ? TRUE : FALSE) === TRUE ){
            return array_keys(config('site.config.fr_appconfig.front-end-search'))[0];
        }else{
            return $page;
        }
    }/// End getFileTemplate

}//end class

