<?php

class Plugin_User {

  /**
   * @var Plugin_User
   */
  private static $instance;

  /**
   * @var Zend_Session_Namespace
   */
  private $_session;

  private function __construct() {
    $this->_session = new Zend_Session_Namespace('SiteAuth');
  }

  /**
   * get the 
   * @return Plugin_user
   */
  public static function singleton() {
    if (!isset(self::$instance)) {
      $className = __CLASS__;
      self::$instance = new $className;
    }
    return self::$instance;
  }

  /**
   * login user
   * @param array $userData
   * @return stdClass
   */
  public function login(Array $userData) {
    $return = new stdClass();
    $return->error = FALSE;
    $return->message = '';

    try {
      $modelUsers = new Model_Users;
      $select = $modelUsers->select()
                           ->where('email = ?', $userData['email'])
                           ->where('password = MD5(?)', $userData['password'])
                           ->limit(1);
      $sql = $select->__toString();
      $user = $modelUsers->fetchRow($select);
      if (empty($user)) {
        $this->_session->unsetAll();
        $this->_session->isLogged = FALSE;
        throw new Exception('Invalid login info');
      } else {
        $this->_session->isLogged = TRUE;
        $this->_session->user = $user->toArray();
      }
    } catch (Exception $exc) {
      $return->error = TRUE;
      $return->message = $exc->getMessage();
    }
    return $return;
  }

  public function logout() {
    $this->_session->unsetAll();
    $this->_session->isLogged = FALSE;
  }

  public function isLogged() {
    return $this->_session->isLogged;
  }
  
  public function getSession(){
    return $this->_session;
  }
  
  public function getUser(){
    if(!$this->isLogged()){
      return NULL;
    }
    return $this->_session->user;
  }

}