<?php

class Model_Cms_Systems extends Pampa_Db_Table
{

  protected $_name = 'cms_page_cat';
  protected $_filePath;
  protected $_orderField = 'order_id';
  protected $_rowClass = "Model_Cms_System";

  public function init(){
    $this->_filePath = BASE_PATH.'/uploads/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)')
      )
      ->order($this->_orderField);

    // check for search
    if(!empty($filters['s'])) {
      $search = "%".$filters['s']."%";
      $select->where("page_cat 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['online'] = ((isset($pageData['online']))? 1: 0);

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

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

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

      // 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
      $this->remove($itemId);

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

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

    return $return;
  }

  private function _uploadBannerImage($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");
      }
      // 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_img']);
      }
    } 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_img']);
  }

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

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

    return $return;
  }

}