<?php

class Model_Cms_Logs extends Pampa_Db_Table {

  protected $_name = "cms_log";

  public function adminList($filters) {
    // start the select
    $select = $this->select()->order('date_ins DESC');

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

    $zendPaginator = Zend_Paginator::factory($select);
    $zendPaginator->setCurrentPageNumber($filters['p']);
    $zendPaginator->setItemCountPerPage($filters['t']);

    return $zendPaginator;
  }

  public function add($user, $text = NULL){

    $return = new stdClass();
    $return->error = FALSE;
    $return->message = '';

    try {
      if(empty($text)){
        throw new Exception("Invalid data");
      }
      // check if is new or old log
      $logged = $this->isTodayLogged($user);
      if($logged){
        $log = $this->fetchRow($this->select()->where("DATE(date_ins) = DATE(NOW())"));
      } else {
        $log = new stdClass();
        $log->log = "";
      }

      // append the text
      $log->log = "<b>".date("H:i:s")."</b> ".$text."<br/>".$log->log;
      $log->user = $user;

      if($logged){
        $this->updateRow($log->toArray());
      } else {
        $this->insertRow($log);
      }


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

    return $return;

  }


  /**
   * check if today has a log
   * @return Boolean
   */
  private function isTodayLogged($user){
    $select = $this->select()
                   ->where("user = ?", $user)
                   ->where("DATE(date_ins) = DATE(NOW())");

    $log = $this->fetchRow($select);

    return $log != NULL;
  }

}