<?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/role.php");
require_once("$CFG->dirroot/local/badiunet/lib/theme.php");

class local_badiunet_register {

    private $util = null;
    private $netlib = null;
    private $tcript = null;

    function __construct() {
        $this->util = new local_badiunet_util();
        $this->netlib = new local_badiunet_netlib();
        $this->tcript = new local_badiunet_templatecript();
    }

    function serviceagree() {
        
        global $OUTPUT;
        global $CFG;
        $token = $this->netlib->getToken();

        if (!empty($token)) {
            $mreporturl = $CFG->wwwroot . "/local/badiunet/fcservice/index.php";
            redirect($mreporturl);
        }

        $html = "<div class=\"panel panel-default\">";
        $html .= "<div class=\"panel-body\">";
        $html .= "<br /><a href=\"status.php?_enableremoteservice=1\" class=\"btn btn-primary\" role=\"button\">Ativar servico de relatorio </a>";
        $html .= "</div>";
        $html .= "<div class=\"panel-footer\"></div>";
        $html .= "</div>";


        echo $OUTPUT->header();
        echo $html;
        echo $OUTPUT->footer();
        exit;
    }

    function enableservice() {

        global $CFG;
        global $USER;
        $enableremoteservice = optional_param('_enableremoteservice', null, PARAM_TEXT);
        if (!$enableremoteservice) {
            return null;
        }
        $url = $this->netlib->getUrlService();
        $rolelib=new local_badiunet_role($USER->id);
        $themelib=new local_badiunet_theme($USER->id);
        $useroles=$rolelib->get();
        $themeinfo=$themelib->get();
        $plugininfo= $this->util->plugininfo();
        
        $moodleinfo=$this->getMoodleName();
        $moodlename=$moodleinfo->fullname;
        $moodleshortname=$moodleinfo->shortname;
        $moodleadmins = $this->getAdmins();
        $fkey = new local_badiunet_factorydnakey();
        $fkey->set();
        $tokendna = $fkey->get();
        $data=array();
        $reqparam=array();
        $options=array();
        
        $reqparam['moodleurl'] = $CFG->wwwroot;
        $reqparam['moodlename'] = $moodlename;
        $reqparam['moodleshortname'] = $moodleshortname;
        $reqparam['moodleadmins'] = $moodleadmins;
        $reqparam['moodleversiontxt'] = $CFG->release;
        $reqparam['moodleversionnumber'] = $CFG->version;
        $reqparam['tokendna'] = $tokendna;
        $reqparam['client']=array('browser'=>$_SERVER['HTTP_USER_AGENT'],'ip'=>$_SERVER["REMOTE_ADDR"],'moodleurl'=>$CFG->httpswwwroot,'moodlename'=>$moodlename,'moodleshortname'=>$moodleshortname,'theme'=>$themeinfo,'plugin'=>$plugininfo);
        $reqparam['user']=array('firstname'=>$USER->firstname,'lastname'=>$USER->lastname,'id'=>$USER->id,'email'=>$USER->email,'roles'=>'');
        $data['_service'] = 'badiu.moodle.mreport.client.lib.moodleservice';
        
         $reqparam=json_encode($reqparam);
         $reqparam=$this->tcript->encode('s1',$reqparam);
         $data['_param']=$reqparam;
       
        $response = $this->util->request($url, $data);
        if($this->util->isResponseError($response)){echo "------------ocorreu um erro <hr>$response";exit;}
        $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);
       
        if ($status == 'accept') {
               $token = $this->util->getVlueOfArray($message, 'token');
               $criptk1 = $this->util->getVlueOfArray($message, 'criptk1');
               $criptk2 = $this->util->getVlueOfArray($message, 'criptk2');
               $ipallowed = $this->util->getVlueOfArray($message, 'ipallowed');
               $plugin = new local_badiunet_pluginconfig('local_badiunet');
               $cont=0;
                if (!empty($token)) {$plugin->add('servicetoken', $token);$cont++;}
                if (!empty($criptk1)) {$plugin->add('criptk1', $criptk1);$cont++;}    
                if (!empty($criptk2)) {$plugin->add('criptk2', $criptk2);$cont++;} 
                if (!empty($ipallowed)) {$plugin->add('serverrmoteipallowed', $ipallowed);} 
                 If($cont==3){
                    $mreporturl = $CFG->wwwroot . "/local/badiunet/fcservice/index.php";
                    redirect($mreporturl);
                }else{echo "ocrreu uma falha. Falha nos 3 tokens";exit;}
          
        }else {
            echo "------------status dained <hr>$info <br />$message";exit;
        }
    }

    public function getMoodleName() {
        global $CFG,$DB;
       $sql="SELECT fullname,shortname FROM {$CFG->prefix}course WHERE  id=1 AND format='site' ";
       $row=$DB->get_record_sql($sql);
       if(!empty($row)){return $row;}
       return null;
   }

    function getAdminsid() {
        global $CFG, $DB;
        $sql = "SELECT value FROM {$CFG->prefix}config WHERE name =  'siteadmins' ";
        $row = $DB->get_record_sql($sql);

        return $row->value;
    }

    function getAdmins() {
        global $CFG, $DB;
        $ids = $this->getAdminsid();
        if (empty($ids))
            return null;
        $sql = "SELECT id, username, firstname, lastname, email FROM {$CFG->prefix}user WHERE id IN ($ids)";

        $rows = $DB->get_records_sql($sql);

        $list = array();
        if (!empty($rows)) {
            foreach ($rows as $row) {
                $user = array();
                $name = $row->firstname;
                if (!empty($row->lastname)) {
                    $name .= " " . $row->lastname;
                }
                $user['username'] = $row->username;
                $user['name'] = $name;
                $user['email'] = $row->email;
                array_push($list, $user);
            }
        }
        return $list;
    }

}

?>
