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


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

  public function indexAction() {
    $this->forward('lista');
  }
  public function listaAction() {

    $this->view->headTitle("Cursos ofertados");
    $this->view->classmain = 'interna';
    $Model = new Model_Moodle_Cursos();
    $filters = array(
      "t" => $this->_getParam("t", 12),
      "p" => $this->_getParam("p", 1),
      "s" => $this->_getParam("s"),
      "old" => $this->_getParam("old"),
    );

    $this->view->filters = $filters;
    $this->view->old = $this->_getParam("old");

    // retrieves the items list
    $this->view->items = $Model->siteList($filters);

  }

  public function verAction() {
    $this->view->headTitle("Cursos");
    $objid = $this->_getParam("id");
    $Model = new Model_Moodle_Cursos();

    $obj = $Model->find($objid)->current();
    $this->view->headTitle($obj->shortname);
    $this->view->obj = $obj;
    $this->view->classmain = 'interna noticias';
$this->view->preinscritos = array();
if(!empty($_SESSION[NOME_SESSAO]['usuario'])){
    $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();

}else{
    $this->view->inscritos = array();

}

   
    
  }
  public function sucessoAction() {
  }
  public function formularioAction() {
    if(empty($_SESSION[NOME_SESSAO]['usuario'])){
     $this->redirect('/usuarios/login');
   }else{
    $Model = new Model_Moodle_Cursos();
    $ModelCampos = new Model_Moodle_Cursos_Campos();
    $ModelInscricoes = new Model_Moodle_Cursos_Inscricoes();

    if(!empty($_POST['obj'])){
      
      $arquivo = null;
      
      //adduser to course
      $arrCampo = $_POST['obj'];
      $arrCampo['campo_id']= '99';
      $arrCampo['valor']= 1;
      $ModelInscricoes->submit($arrCampo,$arquivo);


      foreach ($_POST['campos'] as $key => $value) {
        $arrCampo = $_POST['obj'];
        
        $old = $ModelInscricoes->getByUsuarioAndCampoId($_POST['obj']['user_id'],$key);
        if(!empty($old)){
          $arrCampo['id']= $old->id;          
        }
        $arrCampo['campo_id']= $key;
        $arrCampo['valor']= $value;
        $ModelInscricoes->submit($arrCampo,$arquivo);
      }

      foreach ($_FILES as $key => $value) {
        // echo print_r($value);
        if(!empty($value['name'])){

          $arrCampo = $_POST['obj'];
          $arquivo = $value;
          $campo_id = str_replace('arquivo_','', $key);
          // echo $campo_id;
          $old = $ModelInscricoes->getByUsuarioAndCampoId($_POST['obj']['user_id'],$campo_id);
          if(!empty($old)){
            $arrCampo['id']= $old->id;          
          }
          $arrCampo['campo_id']= $campo_id;
          $arrCampo['valor']= $value;
          $ModelInscricoes->submit($arrCampo,$arquivo);
        }
      }
      // die();
      $this->redirect('/cursos/sucesso');
    }
    $this->view->headTitle("Cursos inscrição");
    $objid = $this->_getParam("id");

    $obj = $Model->find($objid)->current();
    $this->view->obj = $obj;
    $this->view->headTitle("Formulário de inscrição - ".$obj->shortname);


    $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);
    $inscritos = $enrolled;
    $ainscricao = null;
    foreach ($inscritos as $inscricao) {
      if($inscricao->id == $objid){
        $ainscricao = $inscricao;
        break;
      }
    }
    $this->view->inscricao = $ainscricao;

    
    $this->view->campos = $ModelCampos->getByCursoId($objid);
    $this->view->preenchidos = $ModelInscricoes->getByUsuarioAndCursoId($_SESSION[NOME_SESSAO]['usuario']->id,$objid);

  }
}
public function inscricaoAction() {
  $objid = $this->_getParam("id");
  $objtitle = $this->_getParam("title");
  if(empty($_SESSION[NOME_SESSAO]['usuario'])){
    $_SESSION[NOME_SESSAO]['redirect'] = '/cursos/ver/'.$objid.'-'.$objtitle;
    $this->redirect('/usuarios/login');
 }else{
  $this->view->headTitle("Cursos inscrição");
  $Model = new Model_Moodle_Cursos();

  $obj = $Model->find($objid)->current();
  $this->view->headTitle($obj->shortname);




  $ModelCampos = new Model_Moodle_Cursos_Campos();
  $campos = $ModelCampos->getByCursoId($objid);
  if(count($campos) > 0){

    $this->redirect('/cursos/formulario/id/'.$objid);
  }else{


//       $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(
//     'roleid'=>5,
//     'userid'=>$_SESSION[NOME_SESSAO]['usuario']->id,
//     'courseid'=>$obj->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' => 'enrol_manual_enrol_users',
//     'moodlewsrestformat' => 'json',
//     'enrolments' => array($enrolments),
//   );
//   $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);

  $ModelInscricoes = new Model_Moodle_Cursos_Inscricoes();

      $arrCampo = array();
      $arrCampo['user_id']= $_SESSION[NOME_SESSAO]['usuario']->id;
      $arrCampo['curso_id']= $obj->id;
      $arrCampo['campo_id']= '99';
      $arrCampo['valor']= 1;
      $ModelInscricoes->submit($arrCampo,$arquivo);

    $this->redirect('/cursos/sucesso/');

  }

    // die();
}
}

}

