<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class UserRepository extends EntityRepository {

    private $table = 'users';
    private $flashmessenger = null;
     private $options = array(
        'usuario'=>null,
        'contrasena'=>null,
        'nip'=>null,
        'nombre'=>null,
        'apellido'=>null,
        'telefono'=>null,        
        'email'=>null,
        'role'=>null,       
        'status'=>null,
    );
     
         
    public function __construct() {
        if(!$this->flashmessenger instanceof FlashMessenger){
            $this->flashmessenger = new FlashMessenger();
        }
    }
    
    public function _getTranslation($text){
        return $this->flashmessenger->_getTranslation($text);
    }
    
    public function setOptions($data){
      foreach ($this->options as $option => $value){
          if(isset($data[$option])){
            $this->options[$option] = $data[$option];
          }
      }
    }
  
    public function getOptions(){
        return $this->options;
    }
    
     public function getUsuario(){
        return $this->options['usuario'];
    }
    
    public function getContrasena(){
        return $this->options['contrasena'];
    }
    
    public function getNombre(){
        return $this->options['nombre'];
    }
    
    public function getTable(){
        return $this->table;
    }

    public function save(array $data, $table = null) {        
        $data['contrasena'] = MD5($data['contrasena']);
        
        if($data['role'] == '1'){
            $data['master_key'] = $data['nip'];
        }else{
            $data['master_key'] = '';
        }

        return parent::save($data, $this->table);
    }
    
    public function delete($id, $table = null) {
        return parent::delete($id, $this->table);
    }

    public function update($id, $data, $table = null) {
        $currentData = $this->getById($id);
        if($data['contrasena']!='' && $data['contrasena']!=null){
            $data['contrasena'] = MD5($data['contrasena']);
        }else{
            unset($data['contrasena']);
        }
        
        if($data['role'] == '1'){ 
            /*Si al momento de hacer update de cambio de rol*/
            if($currentData['role'] != $data['role']){
                if(trim($data['nip'])=='' || $data['nip'] == null){
                    $data['master_key'] = $currentData['nip'];
                }else{
                    $data['master_key'] = $data['nip'];
                }              
            }
        }else{
            $data['master_key'] = '';
        }
        
        if(trim($data['nip']=='') || $data['nip']==null){ unset($data['nip']);}
        
        $this->startTransaction();
        parent::update($id, $data, $this->table);
        
        $this->commit();
        return true;
    }

    public function getById($id, $table = null,$selectAux = null) {
        return parent::getById($id, $this->table,$selectAux);
    }

    public function isUsedInRecord($id, array $buscarEn = null,$andWhere = null) {
        return parent::isUsedInRecord($id, array(
            'manifest' => 'creado_por',
            'receiving' => 'creado_por',
            'manufacturing' => 'creado_por',
            'shipping_request' => 'creado_por',
            'shipping' => 'creado_por',
            'waste' => 'creado_por'));
    }

    public function getListRoles() {
        $select = "SELECT id,role FROM acl_roles";
        $result = $this->query($select);

        if ($result) {
            $array = array();
            while ($row = $result->fetch_assoc()) {
                $array[$row['id']] = $row['role'];
            }
            return $array;
        }
        return null;
    }
    
    public function getUsersByIds($ids){
        $select = "SELECT *,CONCAT(nombre,' ',apellido)as completeName FROM $this->table WHERE id IN($ids)";
        $result = $this->query($select);
        
        if($result){
            return $this->resultToArray($result);
        }
        
        return null;
    }
    
    public function getListSelectUsers() {
        $select = "SELECT * FROM $this->table ";
        $result = $this->query($select);

        if ($result) {
            $array = array();
            while ($row = $result->fetch_assoc()) {
                $array[$row['id']] = $row['name'];
            }
            return $array;
        }
        return null;
    }
    
     public function getListUsers() {
        $select = "SELECT *,"
                . "fxGetStatusName(status,'User') as statusName, "
                . "fxGetRoleName(role) as roleName "
                . "FROM $this->table ";
        
        $result = $this->query($select);

        if ($result) {
           return $this->resultToArray($result);
        }
        return null;
    }
    
    public function getListStatus(){
        $query = "SELECT * FROM status_code WHERE operation = 'User'";
        $result = $this->query($query);
        
        if($result->num_rows > 0){
            $array = array();
            foreach($result as $status){
                $array[$status['code']] = $status['description'];
            }
            return $array;
        }
        return null;
    }
    
    public function existUserName($username,$id){
        $query = "SELECT id FROM $this->table WHERE usuario = '$username' AND id != '{$id}'";
        $result = $this->query($query);
        
        if($result->num_rows > 0){
            return true;
        }
        return null;
    }
    
     public function existNIP($nip,$id){
        $query = "SELECT id FROM $this->table WHERE nip = '$nip' AND id != '{$id}'";
        $result = $this->query($query);
        
        if($result->num_rows > 0){
            return true;
        }
        return null;
    }
}