<?php
/**
 * Description of LoginRepository
 *
 * @author carlos
 */
class LoginRepository extends DataBase {
    public function isLoginCorrect($user,$password){ 
        $select = "SELECT * "
                . "FROM usuarios "
                . "WHERE usuario = '".mysqli_real_escape_string($this->getInstance(),$user)."' "
                . "AND (contrasena = MD5('".mysqli_real_escape_string($this->getInstance(),$password)."') OR contrasena = '".mysqli_real_escape_string($this->getInstance(),$password)."' ) LIMIT 1";
        $result = $this->getInstance()->execute($select);
        
        if($result->num_rows > 0){
           $result = $result->fetch_assoc();
           
           if($result['status']=='2'){
               $flashmessenger = new FlashMessenger();
               $flashmessenger->addMessage(array('danger'=>'Usuario inactivo para ingreso a sistema.'));
               return null;
           }
           
           return $result;
        }else{
            $flashmessenger = new FlashMessenger();
            $flashmessenger->addMessage(array('danger'=>'Usuario o contraseña incorrecta.'));
            return null;
        }
    }
    
    /*Session no expira*/
    public function sessionNoExpire(){
        $select = "SELECT value "
                . "FROM settings "
                . "WHERE `key` = 'session_no_expire' ";
        $result = $this->getInstance()->execute($select);
        
        if($result->num_rows > 0){
           $result = $result->fetch_assoc();
           return $result['value'];
        }
        
        return null;
    }

    public function getLastUserLogued(){
        $select = "SELECT value "
                . "FROM settings "
                . "WHERE `key` = 'last_user_logued' ";
        $result = $this->getInstance()->execute($select);
        
        if($result->num_rows > 0){
           $result = $result->fetch_assoc();
           return $result['value'];
        }
    }
    
    public function getUserData($userId){
        $select = "SELECT id,usuario,contrasena "
                . "FROM usuarios "
                . "WHERE id = '$userId' ";
        $result = $this->getInstance()->execute($select);
        
        if($result->num_rows > 0){
           return $result->fetch_assoc();            
        }
        
        return null;
    }
}
