<?php

class Cms_CursosInscricoesController extends Pampa_Controller_Action_Cms {
  /**
   * @var Model_Tags
   */
  private $_model;
  private $modelCategories;
  private $categoryId;
  /**
   * initialize controller, call super initialization
   */
  public function init() {
    // initialize all models
    $this->_model = new Model_Moodle_Cursos_Inscricoes();
    $this->modelCategories = new Model_Moodle_Cursos();
    
    
    $this->categoryId = $this->_getParam("r");
    parent::init();
  }

  /**
   * index page forward to list
   */
  public function indexAction() {
    $this->_forward("list");
  }

  /**
   * list based on filters
   */
  public function inscreverAction() {
    $this->_helper->viewRenderer->setNoRender(true);
    $this->_helper->layout->disableLayout();
    $user_id = $_POST['user_id'];
    $curso_id = $_POST['curso_id'];
    if(!empty($user_id) && !empty($curso_id)){

      $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'=>$user_id,
        'courseid'=>$curso_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);
      echo "1";
    }else{
      echo "Parâmetros inválidos";
    }
  }
  public function listAction() {

    // setup the list filters
    $filters = array(
      "t" => $this->_getParam("t", 20000),
      "p" => $this->_getParam("p", 1),
      "r" => $this->categoryId,
      "s" => $this->_getParam("s")
    );

    $this->view->filters = $filters;

    // retrieves the items list
    $this->view->items = $this->_model->adminList($filters);
    $this->view->category = $this->modelCategories->find($this->categoryId)->current();

    
  }

  /**
   * new form creates a blank instance
   */
  public function newAction() {
    // create the blank row
    $this->view->page = $this->_model->createRow();
    $this->view->category = $this->modelCategories->find($this->categoryId)->current();
  }

  /**
   * add the register to db, redirect with errors
   */
  public function addAction() {
    if(!$this->_request->isPost()) {
      $this->_redirector->gotoSimple("list");
    } else {
      // add the row
      $add = $this->_model->submit($_POST['page']);

      if($add->error) {
        // send the error
        $this->sendError($add->message, TRUE);
      } else {
        // send the success
        $this->sendSuccess('Item added!', $this->getUrlTo('cursos-inscricoes', 'edit', array('id' => $add->id,'r' => $add->curso_id)), false);
      }
    }

  }

  /**
   * edit item checking valid id
   */
  public function editAction() {
    // page id
    $page_id = $this->_getParam("id");

    if(empty($page_id)) {
      $this->_redirector->gotoSimple("list");
    }
    // the page row
    $page = $this->_model->getByUsuarioAndCursoId($page_id,$this->categoryId);
    
    
    $this->view->page = $page;
    $this->view->category = $this->modelCategories->find($this->categoryId)->current();

    $ModelCampos = new Model_Moodle_Cursos_Campos();
    $this->view->campos = $ModelCampos->getByCursoId($this->categoryId);
    $ModelUsuarios = new Model_Moodle_Usuarios();
    $this->view->user = $ModelUsuarios->find($page_id)->current();
  }

  /**
   * updates element on db
   */
  public function updateAction() {
    if(!$this->_request->isPost()) {
      $this->_redirector->gotoSimple("list");
    } else {
      // update the row
      $upd = $this->_model->submit($_POST['page']);

      if($upd->error) {
        // send the error
        $this->sendError($upd->message, TRUE);
      } else {
        // send the success
        $this->sendSuccess('Item updated!', $this->getUrlTo('cursos-inscricoes', 'edit', array('id' => $upd->id,'r' => $upd->curso_id)), false);
      }
    }
  }
  
  /**
   * fully delete element from db
   */
  public function deleteAction() {
    $page_id = $this->_getParam("id");

    if(empty($page_id)) {
      $this->_redirector->gotoSimple("list");
    }

    $del = $this->_model->deleteFromId($page_id);

    if($del->error) {
      $this->_helper->messenger('error', $del->message);
    } else {
      // $this->_helper->messenger('ok', "Item removed!");
    }
    $this->sendSuccess('Item removed!', $this->getUrlTo('cursos-inscricoes', 'list', array('r'=>$this->categoryId)), TRUE);
    
  }
  public function orderAction() {
    // row id
    $id = $this->_getParam("id", FALSE);
    // direction
    $dir = $this->_getParam("dir", FALSE);

    // check for valids
    if($id === FALSE || $dir === FALSE)
      $this->redirectTo("cursos-inscricoes", "list");

    // change the row's order
    $orderSet = $this->_model->setOrder($id, $dir);

    // set the message
    if($orderSet) {
      // $this->_helper->messenger('ok', "Item atualizado!");
    } else {
      $this->_helper->messenger('error', "Erro!");
    }

    $this->sendSuccess('Item updated!', $this->getUrlTo('cursos-inscricoes', 'list', array()), TRUE);
  }
  public function onlineAction()
  {

      // atualiza
    $upd = $this->_model->online($_POST['id'], $_POST['online']);
      // show the json result
    $this->renderJson($upd);
    
    
  }
}