<?php

class Model_Cms_System_Modules extends Pampa_Db_Table
{

  protected $_name = 'cms_page';
  protected $_filePath;
  protected $_orderField = 'order_id';

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

  /**
   * List the items based on filters
   * @param Array $filters
   * @return Zend_Paginator
   */
  public function adminList($filters)
  {
    // create the select
    $select = $this->select()
        ->setIntegrityCheck(false)
        ->from(
          array('r' => $this->_name)
        //,array('conta' => '*,(SELECT COUNT(*) FROM cms_page sm WHERE sm.page_cat_id = r.id)')
        )
        ->where("page_cat_id = ?", $filters['r'])
        ->order($this->_orderField);

    // check for search
    if(!empty($filters['s'])) {
      $search = "%".$filters['s']."%";
      $select->where("title LIKE ?" ,$search);
    }

    // setup the paginator
    $paginator = Zend_Paginator::factory($select);
    $paginator->setCurrentPageNumber($filters['p']);
    $paginator->setDefaultItemCountPerPage($filters['t']);

    return $paginator;
  }

  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");
      }

      // checkbox
      $pageData['list'] = ((isset($pageData['list']))? 1: 0);
      $pageData['insert'] = ((isset($pageData['insert']))? 1: 0);
      $pageData['edit'] = ((isset($pageData['edit']))? 1: 0);
      $pageData['delete'] = ((isset($pageData['delete']))? 1: 0);

      $pageData['hidden'] = ((isset($pageData['hidden']))? 1: 0);
      $pageData['online'] = ((isset($pageData['online']))? 1: 0);

      if(!is_null($imageFile)){
        $this->_uploadImage($imageFile, $pageData);
      }

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

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

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

      // setup return
      $return->id = $page->id;
      $return->page_id = $page->page_cat_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
      $this->remove($itemId);

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

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

    return $return;
  }

  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]);
  }

  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 sys module status #{$id} {$record->title} to ".(($libera == 1)? 'online': 'offline'));

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

    return $return;
  }

  /**
   * find all links from a given field update
   * @param Integer $categoryId
   * @return Zend_Db_Table_Rowset
   */
  public function findFromCategory($categoryId = NULL, $userStatus = 0)
  {
    $select = $this->select()
        ->where("page_cat_id = ?", $categoryId)
        ->order("{$this->_orderField}");

    if($userStatus != 0)
    {
      $select->where("status_id	>= ? ", $userStatus);
    }

    $links = $this->fetchAll($select);
    return $links;
  }

  public function homeList(){
    // SELECT * FROM cms_page WHERE ONLINE = '1' AND hidden = '0' ORDER BY `page_cat_id` ASC, order_id ASC
    $select = $this->select()
        ->where('online = \'1\'')
        ->where('hidden = \'0\'')
        ->order(array('page_cat_id ASC', 'order_id ASC'));
        echo $select;
    return $this->fetchAll($select);
  }

}