<?php
require_once("$CFG->dirroot/local/badiunet/lib/util.php");
require_once("$CFG->dirroot/local/badiunet/lib/netlib.php");
require_once("$CFG->dirroot/local/badiunet/lib/response.php");
require_once("$CFG->dirroot/local/badiunet/lib/factorydnakey.php");
require_once("$CFG->dirroot/local/badiunet/lib/syskey.php");
require_once("$CFG->dirroot/local/badiunet/lib/templetecript.php");
require_once("$CFG->dirroot/local/badiunet/lib/httpquerystring.php");
require_once("$CFG->dirroot/local/badiunet/fcservice/maccess.php");
class local_badiunet_factorycontent {

    private $content = null;
    private $navlinks = null;
    private $util = null;
    private $netlib = null;
    private $maccess = null;
    private $tcript = null;
    private $typecontent='notformated'; //formated | notformated 
    private $service='badiu.system.core.functionality.content.service';
    private $criptk1 = null;
    private $criptk2 = null;
    private $criptks = null;

    private $routefrontpage = null;
    /**
     * param to send to server setted by php client application it can be override by http param
     *
     * @var array
     */
    private $paramsytemstart = null;

    /**
     * param to send to server setted by php client application it can not be override by http param
     *
     * @var array
     */
    private $paramsytemdefault = null;
    function __construct($typecontent='notformated') {
        $this->typecontent=$typecontent;
       
       // if($this->typecontent !== 'formated' || $this->typecontent !== 'notformated' ){$this->typecontent='notformated';}
        $this->util=new local_badiunet_util();
        $this->netlib=new local_badiunet_netlib();
        $this->maccess=new local_badiunet_maccess();
        $this->tcript=new local_badiunet_templatecript();
        
    }
    
function init(){
    
    $this->checkRegister();
    $islogged=$this->checkLogin();
    if(!$islogged){return null;}
    $data=$this->makeParam();
    $url=$this->netlib->getUrlService();
    
    $sservicid=$this->netlib->getModuleInstance();
    $tkey=$this->maccess->getByKey('tkey');
    $tkey=$this->tcript->encode('k1',$tkey,$sservicid);
    
    
   // $criptykey=$this->maccess->getByKey('criptykey');
   // $this->cript->setKey($criptykey);
    
    //$data=$this->encriptQuery($data);
   
    $reqparam=array();
     
    
    
    $data['_tokensession']=$tkey; 
    
    $client=array('browser'=>$_SERVER['HTTP_USER_AGENT'],'ip'=>$_SERVER["REMOTE_ADDR"],'typecontent'=>$this->typecontent);
     $reqparam['client']= $client;
   
    $reqparam['_tokendv']=$this->makeTokedv();
    $reqparam=json_encode($reqparam);
 
    $reqparam=$this->tcript->encode('ks',$reqparam,$sservicid);  
    $data['_param']=$reqparam;

    $response=$this->util->request($url,$data);

    $isipallowed=$this->netlib->isIpAllowed($this->util->getLastipconnection());
    if(!$isipallowed){$this->content=get_string('remoteipconnectionnotallowed', 'local_badiunet');return null;}
    if($this->typecontent=='notformated'){
        $this->content=$response;
        return null;
    }
    
   if($this->util->isResponseError($response)){$this->content=$response;return null;}
    $status= $this->util->getVlueOfArray($response, 'status');
    $info= $this->util->getVlueOfArray($response, 'info');
    $message=$this->util->getVlueOfArray($response, 'message');
    
    $message=$this->tcript->decode($message);   
    $message=$this->util->getJson($message, true);

         //$result=$this->util->getJson($result); 
         
         if($status=='accept'){
              $this->maccess->tryrelogin(2);
              $this->content=$this->util->getVlueOfArray($message, 'content');
              $this->navlinks=$this->util->getVlueOfArray($message, 'links');
              $this->formatContent($url);
            
          }else if($status=='danied'){
              $tryrelogin=$this->maccess->tryrelogin();
              if($info=='badiu.system.access.authwebservice.sessionexpired' && $tryrelogin <3 ){
                 
                  $this->maccess->tryrelogin(1);
                   $this->maccess->end();
                   global $CFG;
                    $query = $_SERVER["QUERY_STRING"];
                   $url=$CFG->httpswwwroot."/local/badiunet/fcservice/index.php?$query";
                   redirect($url);
              }else{$this->content="Ocorreu uma falha</br> erro: $info <br /> Mesagem:$message ";}
          }
             
          
        
    }
   function checkLogin() {
       $maccess=new local_badiunet_maccess();
       $islogged=$maccess->isLogged();
       if(!$islogged){$this->content=$maccess->getMessageeror();}
       return $islogged;
   }

   function addParamSystem($param) {
        $sysparam=$this->getParamsytemstart();
        $sysparamdefault=$this->getParamsytemdefault();
        if(empty($sysparam)){$sysparam=array();}
        if(isset($sysparam['_service'])){unset($sysparam['_service']);}
        if(isset($sysparamdefault['_service'])){unset($sysparamdefault['_service']);}
        if(is_array($param)){
            foreach ($param as $key => $value) {
                $sysparam[$key]=$value;
            }
        }
        if(is_array($sysparamdefault)){
            foreach ($sysparamdefault as $key => $value) {
                $sysparam[$key]=$value;
            }
        }
        return $sysparam;
   }
    function makeParam() {
        
        $param=array();
        
        $query = $_SERVER["QUERY_STRING"];
        if (empty($query)) {
            $param=$this->getDefaultParam();
            $param=$this->addParamSystem($param);
            return $param;
        }else{$query=urldecode($query);}
      
      
       
        $key=optional_param('_key', NULL, PARAM_TEXT);
        if ($key == 'badiu.system.core.core.frontpage' || $key == 'badiu.moodle.mreport.site.index'  || $key == 'badiu.moodle.mreport.sitedata.frontpage' ) {
            $param= $this->getDefaultParam();
            $param=$this->addParamSystem($param);
            return $param;
        } else {
             $querystring=new local_badiunet_httpquerystring($query);
             $querystring->makeParam();
            $param=$querystring->getParam();
            $param['_service']=$this->getService();
            $param=$this->addParamSystem($param);
         }
         $param=$this->addParamSystem($param);
        return $param;
    }

    function getDefaultParam() {
       if(isset($_SESSION['_local_badiunet_maccess_session_routefrontpage'])){
            $this->setRoutefrontpage($_SESSION['_local_badiunet_maccess_session_routefrontpage']);
            return $this->getRoutefrontpage();
        } 
      
           $key = $this->netlib->getDefaultmodulekey();
           
            $defaultparam = $this->netlib->getDefaultmoduleurlparam();
        if (empty($key)) {
            $key = "badiu.moodle.mreport.sitedata.frontpage";
            //$key = "badiu.system.core.core.frontpage";
            if (empty($defaultparam)) {
                $defaultparam = "parentid={SERVERSERVICEID}";
                // $defaultparam = "";
            }
        }
        $pos = stripos($defaultparam, "{SERVERSERVICEID}");
        if ($pos !== false) {
            $sserviceid = $this->netlib->getModuleInstance();
            if ($sserviceid > 0) {
                $defaultparam = str_replace("{SERVERSERVICEID}", $sserviceid, $defaultparam);
            }
        }
        $querystring=new local_badiunet_httpquerystring($defaultparam);
        $querystring->makeParam();
        $param=$querystring->getParam();
        $param['_service']=$this->getService();
        $param['_key']=$key;
          
        return $param;
    }

    
     function makeTokedv() {
            $tdvposition=rand (0,1000);
            $syskey=new local_badiunet_syskey();
            $criptykey=$this->maccess->getByKey('sessiondna');
            $psession=substr($criptykey,$tdvposition,25);
            $dv=$syskey->make_verifying_digit($psession,100);
            $tokendv=array('postion'=>$tdvposition,'dv'=>$dv);
           
            return $tokendv;
        }
    function formatContent($url=null) {
        global $CFG;
        $this->content=utf8_decode($this->content);
        $this->content=$this->replaceUrl($this->content,$url);
               
    }
    function replaceUrl($content,$url=null){
        global $CFG;
        $urlbase=$CFG->httpswwwroot.'/local/badiunet/fcservice/index.php';
        $content=str_replace("BADIU_CORE_SERVICE_CLIENTE_URLBASE",$urlbase,$content);
        if(!empty($url)){$content=str_replace("BADIU_CORE_SERVICE_CLIENTE_CURRENT_URL",$url,$content);}
        return $content;
    }
    function encriptQuery($query) {
        if(!is_array($query)){return $query;}
        $newdata=array();
        $sservicid=$this->netlib->getModuleInstance();
        foreach ($query as $key => $value) {
                $endwithid=$this->stringEndsWith($key,'id');
               if($key=="_service" || $key=="_key" || $key=="_datasource" || $endwithid==true){
                 $newdata[$key]=$value;
               }else{
                   $key=$this->tcript->encode('k1',$key,$sservicid);
                   $value=$this->tcript->encode('k1',$value,$sservicid);
                  $newdata[$key]=$value;
               }
              
        }
       return $newdata; 
    }
 function stringEndsWith($text, $tend)
    {
        $length = strlen($tend);
        if ($length == 0) {
        return false;
    }
   return (substr($text, -$length) === $tend);
}   
function makeNavbar() {
          global $PAGE;
          global $CFG;
         $links=$this->navlinks;
           if(!empty($links)){
              foreach ($links as $key => $items) {
                  //print_r($items);
                  foreach ($items as $k => $item) {
                      $type= $item['type'];
                      $position= $item['position'];
                       
                      
                     // echo "$type | $position <hr>";
                      if($type=='link' && $position=='navbar'){
                         
                          $url= $item['link']['url'];
                          $url= $this->replaceUrl($url);
                          $name=$item['link']['name'];
                        
                          $PAGE->navbar->add($name, new moodle_url($url));
                        
                      }
                  }
                 // print_r($items); echo "<hr>";
              }
          }
             // $PAGE->navbar->add($this->menulib->getTlabel()); 
    }
    
       
function makeMenu() {
         global $CFG;
         if($CFG->version <=2016052317){return null;}
          $links=$this->navlinks;
          /*  echo "<pre>";
              print_r($links);
              echo "</pre>";exit;*/
         $html="";
         $html.="<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\">";
         $html.="<script>";        
         $html.="$('#nav-drawer').append('<nav class=\"list-group\" style=\"margin-top:10px\"><a class=\"list-group-item list-group-item-action font-weight-bold\" href=\"#\"><div class=\"m-l-0\" id=\"badiu_menu\">Badiunet</div></a></nav>')";
        $html.="</script>";  
          if(!empty($links)){
              foreach ($links as $key => $items) {
                  //print_r($items);
                  foreach ($items as $k => $item) {
                      $type= $item['type'];
                      $position= $item['position'];
                      $type=$this->util->getVlueOfArray($item, 'type');
                      
                      // echo "$type | $position | with category type<hr>";
                      if($type=='category' && $position=='menu'){
                         $titems=$this->util->getVlueOfArray($item, 'items');
                        foreach ($titems as $tk => $titem) {
                             $url= $titem['link']['url'];
                             $url= $this->replaceUrl($url);
                             $name=$titem['link']['name'];
                             $html.="<script>";  
                             $html.=" $('#nav-drawer').append('<a class=\"list-group-item list-group-item-action \" href=\"$url\"><div class=\"m-l-0\"> $name</div></a>')";
                             $html.="</script>";
                         }
                            
                        
                      }
                      
                     // echo "$type | $position | without category type<hr>";
                      if($type=='link' && $position=='menu'){
                         
                          $url= $item['link']['url'];
                          $url= $this->replaceUrl($url);
                          $name=$item['link']['name'];
                          $html.="<script>";  
                          $html.=" $('#nav-drawer').append('<a class=\"list-group-item list-group-item-action \" href=\"$url\"><div class=\"m-l-0\"> $name</div></a>')";
                        $html.="</script>";  
                        
                      }
                  }
                 // print_r($items); echo "<hr>";
              }
          }
           
          
          return $html;
    }
    
    function checkRegister(){
       
        global $CFG;
        $token=$this->netlib->getToken();
         if(empty($token)){
            $url=$CFG->httpswwwroot.'/local/badiunet/fcservice/status.php';
            redirect($url);
        }
      }
  
        function getContent() {
            return $this->content;
        }

        function setContent($content) {
            $this->content = $content;
        }

        function getUtil() {
            return $this->util;
        }

        function getNetlib() {
            return $this->netlib;
        }

        function getMaccess() {
            return $this->maccess;
        }

        function getTcript() {
            return $this->tcript;
        }

        function setUtil($util) {
            $this->util = $util;
        }

        function setNetlib($netlib) {
            $this->netlib = $netlib;
        }

        function setMaccess($maccess) {
            $this->maccess = $maccess;
        }

        function setTcript($tcript) {
            $this->tcript = $tcript;
        }
        function getNavlinks() {
            return $this->navlinks;
        }

        function setNavlinks($navlinks) {
            $this->navlinks = $navlinks;
        }

        function getRoutefrontpage() {
            return $this->routefrontpage;
        }

        function setRoutefrontpage($routefrontpage) {
            $this->routefrontpage = $routefrontpage;
        }
        function getTypecontent() {
            return $this->typecontent;
        }

        function setTypecontent($typecontent) {
            $this->typecontent = $typecontent;
        }

        function getParamsytemstart() {
            return $this->paramsytemstart;
        }

        function setParamsytemstart($paramsytemstart) {
            $this->paramsytemstart = $paramsytemstart;
        }
    
        function getParamsytemdefault() {
            return $this->paramsytemdefault;
        }

        function setParamsytemdefault($paramsytemdefault) {
            $this->paramsytemdefault = $paramsytemdefault;
        }


        function getService() {
            return $this->service;
        }

        function setService($service) {
            $this->service = $service;
        }
}

?>
