<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

include_once("server/lib/mod_dbm/package.dbm.php");

class User {

    private $idUsuario;
    private $login = null;
    private $userName;
    private $nombre;
    private $isOrgAdmin;
    private $isDivAdmin;
    private $isRoot;
    private $idOrganizacion;
    private $idDivision;
    private $groups;
    private $activeGroups;
    private $phone;

    public function __construct($userName, $password) {

        $u = filter_var($userName, FILTER_SANITIZE_EMAIL);
        $p = filter_var($password, FILTER_SANITIZE_STRING);

        $dao = new dbObject();
        $query = sprintf("SELECT * FROM usuarios WHERE login = '%s' AND password='%s'", $u, $p);
        $res = $dao->fetchQuery($query);

        if (is_array($res) && count($res) == 1) {
            $this->idUsuario = $res[0]['id_usuario'];
            $this->login = $u;
            $this->userName = $res[0]['login'];
            $this->nombre = $res[0]['nombre'];
            $this->isOrgAdmin = $res[0]['administrador_organizacion'];
           // $this->isDivAdmin = $res[0]['administrador_division'];
            $this->isRoot = $res[0]['administrador_sistema'];
            $this->idOrganizacion = $res[0]['id_organizacion'];
            //$this->idDivision = $res[0]['id_division'];
            $this->groups = $this->getGroupsList(false);
            $this->activeGroups = $this->getGroupsList(true);
            $this->phone = $res[0]['celular'];
        } else {
            $this->idUsuario=null;
            $this->login = null;
        }
        
        $query = sprintf("INSERT INTO log_login (timestamp, username, result) VALUES (%s,'%s',%d)",time(),$userName,($this->idUsuario != null)?1:0);
        $res = $dao->execute($query);
        
    }
    
    public function hasMachine(int $machineId): bool{
        $q = sprintf("SELECT machine_id FROM machines WHERE machine_id=%d AND id_grupo IN (%s)",$machineId,$this->getGroupsString());
        $dao = new dbObject();
        $res = $dao->fetchQuery($q);
        return (is_array($res) && count($res) === 1);
    }
    
    public function getIdOrganizacion() : int{
        return $this->idOrganizacion;
    }
    
    public function getUserId(){
        return $this->idUsuario;
    }
    
    public function getUserName(){
        return $this->nombre;
    }

    public function getLogin(){
        return $this->userName;
    }
    
    public function getPhone(){
        return $this->phone;
    }
    
    public  function setNombre($nombre){
        $this->nombre = $nombre;
    }
    
    public  function setPhone($phone){
        $this->phone = $phone;
    }

    public function isValidated() {
        return $this->login != null;
    }

    public function isRoot(): bool {
        return $this->isRoot!=null && $this->isRoot;
    }

    public function isOrgAdmin(): bool {
        return $this->isOrgAdmin!=null && $this->isOrgAdmin;
    }

    public function isDivAdmin(): bool {
        return $this->isDivAdmin!=null && $this->isDivAdmin;
    }
   
    public function getGroupsString(bool $activeOnly=true) :string{
        
        $groups="";
        try{
            $groupsCopy = $this->getGroups($activeOnly);
            foreach($groupsCopy as $grp){
                $groups .= ($groups)?",":"";
                $groups .= $grp;
            }
        } catch (Exception $ex) {
            $groups="-1";
        }
        return $groups;
    }
    
    public function getGroups( bool $activeOnly=true) :array{
        return ($activeOnly)?$this->activeGroups:$this->groups;
    }
    
    public function getGroupsList(bool $activeOnly = true):array {
        $listaGrupos = array();
        $cond = ($activeOnly)?"activa=1":"true";
       
        if($this->isRoot){  
            $q = ($cond)
                    ?"SELECT * FROM grupos g WHERE g.activo=1"
                    :"SELECT * FROM grupos g";
            
        } elseif($this->isOrgAdmin()){
            $q = ($cond)
                    ?sprintf("SELECT id_grupo FROM grupos g WHERE id_organizacion = %d AND g.activo=1",$this->idOrganizacion)
                    :sprintf("SELECT id_grupo FROM grupos g WHERE id_organizacion = %d",$this->idOrganizacion);
            
        } else {
            $q = ($cond)
                    ?sprintf("SELECT gu.id_grupo FROM grupos_de_usuarios gu LEFT JOIN grupos g ON gu.id_grupo = g.id_grupo WHERE g.activo=1 AND gu.id_usuario = %d",$this->idUsuario)
                    :sprintf("SELECT id_grupo FROM grupos_de_usuario gu WHERE gu.id_usuario = %d",$this->idUsuario); 
        }
        $dao = new dbObject();
        $res = $dao->fetchQuery($q);
        if(is_array($res) && count($res)){
            foreach($res as $grupo){
                $listaGrupos[] = $grupo['id_grupo']; 
            }
        }
        return $listaGrupos;
    }
}
?>