<?php

class Model_Cms_Users extends Pampa_Db_Table {

  protected $_name = "cms_user";

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

    try {

      if(empty($data)) {
        throw new Exception("Invalid information");
      }

      // get the auth adapter
      $adapter = Pampa_Auth_Adapter_Cms::getInstance()->getAdapter();
      // setup the info
      $adapter->setIdentity($data['login']);
      $adapter->setCredential($data['password']);

      // the auth class
      $cmsAuth = Pampa_Auth_Cms::getInstance();
      $authResult = $cmsAuth->authenticate($adapter);

      if($authResult->isValid()) {
        // retrieves the data without the password field
        $userData = $adapter->getResultRowObject(null, 'password');

        // store all data
        $cmsAuth->getStorage()->write($userData);
      } else {
        Pampa_Log::log("Tentativa de login usando: {$data['login']}//{$data['password']}");
        throw new Exception("Invalid login and/or password");
      }


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

    return $return;
  }

  public function add($data) {
    $return = new stdClass();
    $return->error = FALSE;
    $return->message = '';

    try {

      if(empty ($data)) {
        throw new Exception("Invalid data");
      }

      // verify if login already exists
      if($this->isRegisteredUsername($data['login'])) {
        throw new Exception("Username already taken");
      }

      // verify if email already exists
      if($this->isRegisteredEmail($data['email'])) {
        throw new Exception("E-mail already exists");
      }


      if(strlen($data['password']) < 4) {
        throw new Exception("Password must be at least 4 characters long");
      }
      $data['password'] = md5($data['password']);
      $data['usergroup_id'] =empty($data['usergroup_id']) ? '3' : $data['usergroup_id'];

      // insert row
      $row = $this->insertRow($data);
      $return->id = $row->id;

      // log
      Pampa_Log::log("Inserted user #{$row->id} {$row->name}");

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

    return $return;
  }


  public function update(array $data,$where) {
    $return = new stdClass();
    $return->error = FALSE;
    $return->message = '';

    try {

      if(empty ($data)) {
        throw new Exception("Invalid data");
      }

      // get the current user
      $user = $this->find($data['id'])->current();

      // check for login
      if($user->login != $data['login']) {
        // verify if login already exists
        if($this->isRegisteredUsername($data['login'])) {
          throw new Exception("Username already taken");
        }
      }

      // check for email
      if($user->email != $data['email']) {
        // verify if email already exists
        if($this->isRegisteredEmail($data['email'])) {
          throw new Exception("E-mail already exists");
        }
      }

      // check if the password was changed
      if(!empty($data['password'])) {
        if(strlen($data['password']) < 4) {
          throw new Exception("Password must be at least 4 characters long");
        }
        $data['password'] = md5($data['password']);
      } else {
        unset($data['password']);
      }
      
      // update rows
      $row = $this->updateRow($data);
      $return->id = $row->id;

      // log
      Pampa_Log::log("Updated user #{$row->id} {$row->name}");

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

    return $return;
  }

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

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

    return $zendPaginator;
  }

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

    try {
      if(empty($user_id)){
        throw new Exception("Invalid user ID");
      }

      // get the user to be deleted
      $delUser = $this->find($user_id)->current();

      // check the user level
      $delUserGroup = Plugin_Cms_User::getUserGroup($delUser);
      // if is a super user, only delete if the current user is a super user
      if($delUserGroup->super === "1"){
        if(Plugin_Cms_User::getUserGroup()->super != "1"){
          throw new Exception("You cannot delete a super user");
        }
      }

      // remove the user
      $delUser->delete();

      // log
      Pampa_Log::log("Deleted user #{$user_id}");
      
    } catch (Exception $exc) {
      $return->error = TRUE;
      $return->message = $exc->getMessage();
    }

    return $return;
  }

  /**
   * check if there is a login
   * in the database
   * @param String $login
   * @return Boolean
   */
  private function isRegisteredUsername($login = NULL) {
    if(empty($login)) {
      return FALSE;
    }
    // find the user with the given login
    $select = $this->select()
            ->where("login = ?", $login)
            ->limit(1);
    $user = $this->fetchRow($select);

    // returns TRUE if the user is not null
    return $user != NULL;
  }

  /**
   * check if ther is a email
   * in the database
   * @param String $email
   * @return Boolean
   */
  private function isRegisteredEmail($email = NULL) {
    if(empty($email)) {
      return FALSE;
    }
    // find the user with the given email
    $select = $this->select()
            ->where("email = ?", $email)
            ->limit(1);
    $user = $this->fetchRow($select);

    // returns TRUE if the user is not null
    return $user != NULL;
  }

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

}