<?php
@session_start();
class UsuariosController extends Pampa_Controller_Action_Site {


  public function init() {
    parent::init();
    $this->view->menu = '';
  }

  public function logoutAction() {
    unset($_SESSION[NOME_SESSAO]['usuario']);
    $this->forward('login');

  }
  public function indexAction() {
    $this->forward('login');
  }  
  public function inscricoesAction() {
    if(empty($_SESSION[NOME_SESSAO]['usuario'])){
     $_SESSION[NOME_SESSAO]['redirect'] = '/usuarios/inscricoes';
     $this->forward('login');
   }else{
     $this->view->menu = 'inscricoes';
     $Model = new Model_Moodle_Cursos();
     

     $tokenurl = MOODLE_URL.'login/token.php?username=phpuser&password=Thais2010*&service=servicoceped2';      

     $tokenresponse = file_get_contents($tokenurl);
     $tokenobject = json_decode($tokenresponse);

     if (!empty($tokenobject->error)) {        
      $this->view->message .= '<div class="alert alert-danger"><strong>Atenção</strong> '.$tokenobject->error.' </div>';      
    }

      // Newusers will be an array of objects containing the new user ids.

    $enrolments = array(

      'userid'=>$_SESSION[NOME_SESSAO]['usuario']->id,

    );
// See the api documentation /admin/webservice/documentation.php
// for enrol_manual_enrol_users for building the $enrolments array

// Then enrol the users.
    $params = array(
      'wstoken' => $tokenobject->token,
      'wsfunction' => 'core_enrol_get_users_courses',
      'moodlewsrestformat' => 'json',
      'userid' => $_SESSION[NOME_SESSAO]['usuario']->id,
    );
    $baseurl = MOODLE_URL.'webservice/rest/server.php?';
    $url = $baseurl . http_build_query($params);

    $response = file_get_contents($url);

    // echo $url;
    // echo $response;
    $enrolled = json_decode($response);
    $this->view->inscritos = $enrolled;

    $ModelUsers = new Model_Moodle_Usuarios();
    $user = $ModelUsers->find($_SESSION[NOME_SESSAO]['usuario']->id)->current();
    
    $this->view->preinscritos = $user->getPreinscricoes();

      // retrieves the items list
     $filters = array(
      "t" => $this->_getParam("t", 12),
      "p" => $this->_getParam("p", 1),
      "s" => $this->_getParam("s"),
      // "old" => $this->_getParam("old"),
    );
    $this->view->items = $Model->siteList($filters);
  }
}
public function confereCertificadoAction() {
 $this->_helper->viewRenderer->setNoRender(true);
 $this->_helper->layout->disableLayout();
 $codigo = $_POST['code'];
 if(!empty($codigo)){

  $modelGerados = new Model_Moodle_Certificados_Gerados();
  $gerado = $modelGerados->getByCode($codigo);
  if(!empty($gerado)){
    $usuario = $gerado->getUsuario();
    $certificado = $gerado->getCertificado();
    $curso = $certificado->getCurso();

    echo '<div class="well">
    <h4>Certificado válido</h4>
    <strong>Aluno:</strong> '.$usuario->firstname.'<br>
    <strong>Curso:</strong> '.$curso->fullname.'<br>
    </div>';
  }else{
    echo '<div class="alert alert-danger" role="alert">Código de certificado não encontrado</div>';
  }
}else{
  echo '<div class="alert alert-danger" role="alert">Código de certificado não encontrado</div>';
}
}
public function certificadosAction() {

  $this->view->menu = 'certificados';

  $options = '';
  if(!empty($_SESSION[NOME_SESSAO]['usuario'])){

   $modelGerados = new Model_Moodle_Certificados_Gerados();
   $gerados =  $modelGerados->getByUserId($_SESSION[NOME_SESSAO]['usuario']->id);
   foreach ($gerados as  $gerado) {
     $certificado = $gerado->getCertificado();
     if(!empty($certificado)){      
       $curso = $certificado->getCurso();
       $moduleCurso = $curso->getModuleIdCourse();
       if(!empty($moduleCurso)){

       // $link = MOODLE_URL.'mod/simplecertificate/wmsendfile.php?id='.$gerado->id.'&sk=e4HWlk9O4c'; 
       // http://www.ensino.ceped.pr.gov.br/mod/simplecertificate/view.php?id=1413&action=get
          $link = MOODLE_URL.'mod/simplecertificate/view.php?id='.$moduleCurso->id.'&action=get'; // http://www.ensino.ceped.pr.gov.br/mod/simplecertificate/view.php?id=1413&action=get
          $options .= '<option value="'.$link.'">'.$curso->fullname.'</option>';
       }
     }
   }
 }
 $this->view->options = $options;

}
public function loginAction() {

  $this->view->headTitle("Login");
  $this->view->classmain = 'interna';

  if(!empty($_POST['obj'])){

   $Model = new Model_Moodle_Usuarios();
   $tokenurl = MOODLE_URL.'login/token.php?username=phpuser&password=Thais2010*&service=servicoceped2';      

   $tokenresponse = file_get_contents($tokenurl);
   $tokenobject = json_decode($tokenresponse);

   if (!empty($tokenobject->error)) {        
    $this->view->message .= '<div class="alert alert-danger"><strong>Atenção</strong> '.$tokenobject->error.' </div>';      
  }

  $method ='core_user_get_users_by_field';

  $params = array(
    'wstoken' => $tokenobject->token,
    'wsfunction' => $method,
    'moodlewsrestformat' => 'json',
    'field' => 'username',
    'values' => array($_POST['obj']['username']),
  );
  $baseurl = MOODLE_URL.'webservice/rest/server.php';
  $url = $baseurl . '?'.http_build_query($params);

  $response = file_get_contents($url);


  $retUsers = json_decode($response);

  if(!empty($retUsers->errorcode)){
    $this->view->message .= '<div class="alert alert-danger"><strong>Atenção</strong> '.$retUsers->message.'<br><br>'.(!empty($retUsers->debuginfo) ? $retUsers->debuginfo:'').' </div>';
  }else{
      if(!empty($retUsers[0])){

        $user = $Model->find($retUsers[0]->id)->current();
        $_SESSION[NOME_SESSAO]['usuario'] = $user;
        $_SESSION[NOME_SESSAO]['thepasswd'] = $_POST['obj']['password'];
      }

  }

}

if(!empty($_SESSION[NOME_SESSAO]['usuario'])){
  if(!empty($_SESSION[NOME_SESSAO]['redirect'])){
    $redi = $_SESSION[NOME_SESSAO]['redirect'];
    $_SESSION[NOME_SESSAO]['redirect'] = null;
    $this->redirect($redi);
  }else{
    $this->forward('inscricoes');    

  }
}

}

public function cadastroAction() {
  $this->view->headTitle("Cadastro de Usuário");

  $Model = new Model_Moodle_Usuarios();


  $this->view->page = $Model->createRow();
  $this->view->classmain = 'interna noticias';
  $this->view->message = '';

  if(!empty($_POST['page'])){
    
    $tokenurl = MOODLE_URL.'login/token.php?username=phpuser&password=Thais2010*&service=servicoceped2';
      // echo $tokenurl;

    $objectPost = new stdClass();


    foreach ($_POST['page'] as $key => $value)
    {
      $objectPost->$key = $value;
    }

    $this->view->page =  $objectPost;

    $tokenresponse = file_get_contents($tokenurl);

    $tokenobject = json_decode($tokenresponse);

    if (!empty($tokenobject->error)) {
        // echo $tokenobject->error;
      $this->view->message .= '<div class="alert alert-danger"><strong>Atenção</strong> '.$tokenobject->error.' </div>';

        // die();
    }

// Then call the create user and enrol functions

    $baseurl = MOODLE_URL.'webservice/rest/server.php';


// Then add these parameters to the url.
      //tool/uploaduser:uploaduserpictures
    $method = 'core_user_update_users';
    if(empty($_POST['page']['id'])){
      unset($_POST['page']['id']);
      $method = 'core_user_create_users';
      if(empty($_POST['page']['password'])){
        unset($_POST['page']['password']);        
      }
    }else{
      if(empty($_POST['page']['password'])){
        unset($_POST['page']['password']);        
      }

    }

//INICIO UPLOAD FOTO
    if(!empty($_FILES['foto'])){

      $Model->submit(array('id'=>$_SESSION[NOME_SESSAO]['usuario']->id),$_FILES['foto']);
      
    }
//FIM UPLOAD FOTO
    $userObj = new stdClass();
    // $userObj->username = $_POST['page']['username'];
    // $userObj->firstname = $_POST['page']['firstname'];
    // $userObj->lastname = $_POST['page']['lastname'];
    // $userObj->email = $_POST['page']['email'];
    $arrOBJ =  array(
      'username' => $_POST['page']['username'],      
      'firstname' => $_POST['page']['firstname'],
      'lastname' => $_POST['page']['lastname'],
      'email' => $_POST['page']['email'],
    );
    if(!empty( $_POST['page']['password'])){
      if($method == 'core_user_create_users'){

      // $arrOBJ['createpassword'] = 1;
      }
      // $userObj->auth = 'manual';
      // $userObj->password = $_POST['page']['password'];
      $arrOBJ['password'] = $_POST['page']['password'];
      // $userObj->password = 'Password_2018';
      // $arrOBJ['password'] = 'Password_2018';
    }
    if(!empty( $_POST['page']['id'])){
      $userObj->id = $_POST['page']['id'];
      $arrOBJ['id'] = $_POST['page']['id'];
    }
    $users   = array( $arrOBJ);
    
    // echo print_r($users);
// See the api documentation /admin/webservice/documentation.php
// for core_user_create_users for building the $users array

    // $params = array(
    //   'wstoken' => $tokenobject->token,
    //   'wsfunction' => $method,
    //   'moodlewsrestformat' => 'json',
    //   'users' => $users,
    // );

    // $url = $baseurl . '?'.http_build_query($params);
      
    // $response = file_get_contents($url);
    //   // echo $response ;

    // $retUsers = json_decode($response);




$serverurl = $baseurl. '?wstoken=' . $tokenobject->token . '&wsfunction='.$method.'&moodlewsrestformat=json';

$users = array($arrOBJ);
$params = array('users' => $users); 

$fields = $params;
// $fields_string ="";

// foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
// $fields_string = rtrim($fields_string,'&');

//open connection
// $ch = curl_init();

// //set the url, number of POST vars, POST data
// curl_setopt($ch,CURLOPT_URL,$serverurl);
// curl_setopt($ch,CURLOPT_POST,count($fields));
// // curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
// curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($fields));
// curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

// //execute post
// $contents = curl_exec($ch);


// $content = http_build_query(array(
//                 'txtXML' => $_POST['txtXML']
//             ));
$content = http_build_query($fields);

            $context = stream_context_create(array(
                'http' => array(
                    'method' => 'POST',                    
                    'header' => "Connection: close\r\n".
                                "Content-type: application/x-www-form-urlencoded\r\n".
                                "Content-Length: ".strlen($content)."\r\n",
                    'content' => $content                               
                )
            ));
            // Realize comunicação com o servidor
            $contents = file_get_contents($serverurl, null, $context);            




// $context = stream_context_create(array(
//     'http' => array(
//         'method' => 'POST',                    
//         'header' => 'Content-Type: text/plain',
//         'content' => $params                             
//     )
// ));

// $contents = file_get_contents($serverurl, null, $context);            

// print_r($contents);

$retUsers = json_decode($contents);  








    if(!empty($retUsers->errorcode)){
      $this->view->message .= '<div class="alert alert-danger"><strong>Atenção </strong> '.$retUsers->message.''.(!empty($retUsers->debuginfo) ? $retUsers->debuginfo:'').' </div>';
      $this->view->message .= '<div class="alert alert-danger"><strong>Atenção </strong> Email já cadastrado </div>';
    }else{
      if(!empty($_POST['page']['password'])){
        $_SESSION[NOME_SESSAO]['thepasswd'] = $_POST['page']['password'];          
      }
      if( empty($retUsers)){
        $_POST['page']['id'] = $_SESSION[NOME_SESSAO]['usuario']->id;
        unset($_POST['page']['password']);        
        $Model->submit($_POST['page'],null);
        $user = $Model->find($_SESSION[NOME_SESSAO]['usuario']->id)->current();

      }else{

        $_POST['page']['id'] = $retUsers[0]->id;
        unset($_POST['page']['password']);        
        $Model->submit($_POST['page'],null);
        $user = $Model->find($retUsers[0]->id)->current();
      }
      if(!empty($user)){
       $_SESSION[NOME_SESSAO]['usuario'] = $user;
     }
     $this->view->page = $_SESSION[NOME_SESSAO]['usuario'];

     $this->view->message .= '<div class="alert alert-success"><strong>Sucesso!</strong> Usuário salvo com sucesso </div>';

   }

      // die();
 }else if(!empty($_SESSION[NOME_SESSAO]['usuario'])){
   $this->view->page = $_SESSION[NOME_SESSAO]['usuario'];
 }
}
private function arraytostring($fields){
  foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
$fields_string = rtrim($fields_string,'&');
}
private function _object_to_array($data)
{
  if (is_array($data) || is_object($data))
  {
    $result = array();
    foreach ($data as $key => $value)
    {
      $result[$key] = $this->_object_to_array($value);
    }
    return $result;
  }
  return $data;
}

}

