<?php

class Model_Moodle_Cursos_Inscricoes extends Pampa_Db_Table
{

  protected $_name = 'ead_cursos_inscricoes';
  protected $_filePath;
  protected $_orderField = 'id';
  protected $_rowClass = 'Model_Moodle_Cursos_Inscricao';
  

  public function init(){
    $this->_filePath = BASE_PATH.'/uploads/inscricoes/';
    parent::init();
  }



  /**
   * List the items based on filters
   * @param Array $filters
   * @return Zend_Paginator
   */
  public function adminList($filters)
  {
    // create the select

    $select = $this->select()
      ->from(array('s' => $this->_name),array('s.id','s.curso_id','s.user_id','s.campo_id','s.valor','u.id as idu'))
      ->order('u.firstname')->setIntegrityCheck(FALSE)
      ->joinLeft(array('u' =>'mdl_user') ,'u.id = s.user_id',array('iduser' =>'u.id'));

    // check for search
    if(!empty($filters['s'])) {
      $filters['s'] = trim($filters['s']);
      $search = "%".$filters['s']."%";
      $select->where("LOWER(u.firstname) like LOWER(?) or LOWER(u.lastname) like LOWER(?) or LOWER(u.username) like LOWER(?) or LOWER(u.email) like LOWER(?) " ,$search,$search,$search,$search);
      // $select->where("u.firstname LIKE ? or u.lastname LIKE ? or u.username LIKE ? or u.email LIKE ?" ,$search,$search,$search,$search);
    }



    
    if(!empty($filters['r'])) {      
      $select->where("s.curso_id = ".$filters['r']);
      
    }
      // $select->group("user_id");
      $select->group("u.id");
      $select->group("s.id");
      // echo $select;
      
    
    // setup the paginator
    $paginator = Zend_Paginator::factory($select);
    $paginator->setCurrentPageNumber($filters['p']);
    $paginator->setDefaultItemCountPerPage($filters['t']);

    return $paginator;
  }

 public function getByCursoId($curso_id){
    $select = $this->select()
    
    ->where('curso_id = '.$curso_id)
    ->order($this->_orderField);

   
    return $this->fetchAll($select);
  }
  public function getByUserId($user_id){
    $select = $this->select()
    
    ->where('user_id = '.$user_id)
    ->order($this->_orderField);

   
    return $this->fetchAll($select);
  }
  public function getByUsuarioAndCursoId($usuario_id, $curso_id){
    $select = $this->select()
    
    ->where('user_id = '.$usuario_id)
    ->where('curso_id = '.$curso_id)
    ->order($this->_orderField);
    // echo $select;
   
    return $this->fetchAll($select);
  }
   public function getByUsuarioAndCampoId($usuario_id, $campo_id){
    $select = $this->select()
    
    ->where('user_id = '.$usuario_id)
    ->where('campo_id = '.$campo_id)
    ->order($this->_orderField);

   
    return $this->fetchRow($select);
  }
  
  protected function beforeInsert(){
    $this->_data[$this->_orderField] = $this->getOrder();
  }

  public function submit($pageData, $imageFile = null)
  {
    $return = new stdClass();
    $return->error = FALSE;
    $return->message = '';

    try {
      // validates data
      if (empty($pageData)) {
        throw new Exception("Invalid page information");
      }
      
    

     // upload imagem
      if(!empty($imageFile))
      {
        $this->_uploadImage($imageFile, $pageData,'valor');
      }


  
      
      if(empty($pageData['id']))
      {
        // insert the page
        $page = $this->insertRow($pageData);

        // log
        Pampa_Log::log("Inserted page #{$page->id} {$page->label}");
      }
      else
      {
        
        
        // insert the page
        $page = $this->updateRow($pageData);

        // log
        Pampa_Log::log("Updated page #{$page->id} {$page->label}");
      }

      // setup return
      $return->id = $page->id;
      $return->curso_id = $page->curso_id;
      

    } catch (Exception $exc) {
      $return->error = TRUE;
      $return->message = $exc->getMessage();
    }

    return $return;
  }

  public function deleteFromId($itemId = NULL)
  {
    $return = new stdClass();
    $return->error = FALSE;
    $return->message = '';

    try {
      // find the record
      $banner = $this->find($itemId)->current();

      // remove the image
      if(!empty($banner->image)){
        @unlink($this->_filePath . $banner->image);
      }

      // remove the row
      $banner->delete(); // sem order_id
      //$this->remove($banner_id); // com order_id


      // log
      Pampa_Log::log("Deleted page #{$itemId}");

    } catch (Exception $exc) {
      $return->error = TRUE;
      $return->message = $exc->getMessage();
    }

    return $return;
  }
    public function online($id = null, $online){
    $return = new stdClass();
    $return->error = FALSE;
    $return->message = '';

    try {
      // find the record
      $record = $this->find($id)->current();

      $libera = (($online == 1)? 0: 1);

      // update the row
      $this->updateRow(array('id' => $id, 'online' => $libera));

      // log
      // Pampa_Log::log("Changed user status #{$id} {$record->login} to ".(($libera == 1)? 'online': 'offline'));

    } catch (Exception $exc) {
      $return->error = TRUE;
      $return->message = $exc->getMessage();
    }

    return $return;
  }
private function _uploadImage($imageFile, &$formData, $field = 'valor')
  {
    // create the file upload
    $imageUpload = new Pampa_Util_Upload($imageFile);

    if ($imageUpload->isFile()) {

      // check the extension
      // if (!$imageUpload->isImage()) {
      //   throw new Exception("Please choose a valid image file");
      // }
      if(!Pampa_Util_File::checkPath($this->_filePath))
      {
        throw new Exception("File system error.");
      }

      // set image path
      $imageUpload->setPath($this->_filePath);

      if (!$imageUpload->doCopy()) {
        throw new Exception("Error uploading file");
      }
      // add the filename with the uploaded filename
      $formData[$field] = $imageUpload->getFilename();

      // check for old file
      if(!empty($formData['old_'.$field])){
        @unlink($this->_filePath . $formData['old_'.$field]);
      }
    } else {
      // check if it's new banner
      if(empty($formData['id'])){
        // imagem obrigatoria, descomentar linha abaixo
        //throw new Exception('Please select an image file');
      }
    }
    unset($formData['old_'.$field]);
  }

}