<?php

class Model_Moodle_Certificados_Gerados extends Pampa_Db_Table
{

  protected $_name = 'mdl_simplecertificate_issues';
  protected $_filePath;
  protected $_orderField = 'id';
  protected $_rowClass = 'Model_Moodle_Certificados_Gerado';
  

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



  /**
   * List the items based on filters
   * @param Array $filters
   * @return Zend_Paginator
   */
  public function adminList($filters)
  {
    // create the select
    $select = $this->select()
    ->order('id desc');

    // check for search
    if(!empty($filters['s'])) {
      $search = "%".$filters['s']."%";
      $select->where("firstname LIKE ?" ,$search);
    }
    
    // setup the paginator
    $paginator = Zend_Paginator::factory($select);
    $paginator->setCurrentPageNumber($filters['p']);
    $paginator->setDefaultItemCountPerPage($filters['t']);

    return $paginator;
  }

 public function getAll(){
    $select = $this->select()
    
    // ->where('online = ?',1)
    ->order('id desc');

   
    return $this->fetchAll($select);
  }
  public function getByCode($code){
    $select = $this->select()
    
    ->where('code = ?',$code)
    ->order('id desc');

   
    return $this->fetchRow($select);
  } 
  public function getByUserId($userid){
    $select = $this->select()
    
    ->where('userid = ?',$userid)
    ->order('id desc');

   
    return $this->fetchAll($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");
      }
      
    if(!empty($pageData['data'])){
      $pageData['data'] = implode('-', array_reverse(explode('/', $pageData['data'])));
    }

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


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

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

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

      // setup return
      $return->id = $page->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 _uploadAvatar($imageFile, &$formData, $field = 'foto')
  {
    // 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 image");
      }
      // 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]);
  }
  private function _uploadImage($imageFile, &$formData, $field = 'image')
  {
    // 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 image");
      }
      // 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]);
  }

}