<?php
class Usuario extends Conexion {
    /* =============================================
      LOGIN Y VARIABLES DE SESSION
      ============================================= */

    public function login() {
        $conectar = parent::conectar();
        parent::set_names();
        if (isset($_POST["enviar"])) {
            $nick = $_POST["nickname"];
            $pass = $_POST["clave"];
            if (empty($nick) or empty($pass)) {
                //echo '<script>window.location="http://localhost/sied/index.php?m=2";</script>';
                //echo '<script>window.location="https://cemlad.org/sied/index.php?m=2";</script>';
                header("Location:https://cemlad.org/sied/index.php?m=2");
                exit();
            } else {
                $pass = crypt($_POST["clave"], '$2a$07$asxx54ahjppf45sd87a5a4dDDGsystemdev$');
                $intento = "SELECT intentos FROM usuario WHERE nickname =?";
                //$intento = 0;
                $stmt = $conectar->prepare($intento);
                $stmt->bindValue(1, $nick);
                $stmt->execute();
                $resul = $stmt->fetch();
                //$intento = 0;
                if (is_array($resul) and count($resul) > 0) {
                    $intento = $resul["intentos"];
                }
                if ($intento < 3) {
                    $sql = "SELECT * FROM usuario                
                        INNER JOIN persona ON personadbk = persona 
                        WHERE nickname =? and clave =?";
                    $stmt2 = $conectar->prepare($sql);
                    $stmt2->bindValue(1, $nick);
                    $stmt2->bindValue(2, $pass);
                    $stmt2->execute();
                    $resultado = $stmt2->fetch();
                    if (is_array($resultado) and count($resultado) > 0) {
                        
                        $sql = "UPDATE usuario SET intentos = 0 WHERE nickname=?";
                        $stmt3 = $conectar->prepare($sql);
                        $stmt3->bindValue(1, $nick);
                        $stmt3->execute();
                        $_SESSION["iniciarSesion"] = "ok";
                        $_SESSION["usuariodbk"] = $resultado["usuariodbk"];
                        $_SESSION["papellido"] = $resultado["papellido"];
                        $_SESSION["sapellido"] = $resultado["sapellido"];
                        $_SESSION["identificacion"] = $resultado["identificacion"];
                        $_SESSION["pnombre"] = $resultado["pnombre"];
                        $_SESSION["snombre"] = $resultado["snombre"];
                        $_SESSION["personadbk"] = $resultado["personadbk"];
                        $_SESSION["perfil"] = $resultado["perfil"];
                        $_SESSION["foto"] = $resultado["foto"];
                        $_SESSION["nickname"] = $resultado["nickname"];
                        $sql = "SELECT * FROM periodo                                              
                        WHERE estado = 'ACTIVO'";
                        $stmt4 = $conectar->prepare($sql);                        
                        $stmt4->execute();
                        $res = $stmt4->fetch();
                        $_SESSION["periodbk"] = $res["periodbk"];
                        $_SESSION["descrip"] = $res["descrip"];
                        //session_start();
                        //echo '<script>window.location="https://cemlad.org/sied/view/UsuHome"</script>';    
                        
                        //echo '<script>window.location="http://localhost/sied/view/UsuHome";</script>';
                        
                        //header("Location:" . Conexion::ruta() . "view/UsuHome/");
                        header("Location:https://cemlad.org/sied/view/UsuHome/index.php");                        
                        exit();
                    } else {
                        header("Location:" . Conexion::ruta() . "index.php?m=1");
                        //echo '<script>window.location="https://cemlad.org/sied/index.php?m=1";</script>';
                        $sql = "UPDATE usuario SET intentos =? WHERE nickname=?";
                        $stmt = $conectar->prepare($sql);
                        $stmt->bindValue(1, $intento + 1);
                        $stmt->bindValue(2, $nick);
                        $stmt->execute();
                        exit();
                    }
                } else {
                    //echo '<script>window.location="http://localhost/sied/index.php?m=3";</script>';
                    //echo '<script>window.location="https://cemlad.org/sied/index.php?m=3";</script>';
                    header("Location: https://cemlad.org/sied/index.php?m=3");
                    exit();
                }
            }
        }
    }

    /* =============================================
      VER DATOS DE USUARIO - USUPERFIL
      ============================================= */

    public function Usuario_por_ID($userId) {
        $conectar = parent::conectar();
        parent::set_names();
        $sql = "
                SELECT * FROM usuario                 
                INNER JOIN persona ON personadbk = persona
                LEFT JOIN academico ON aca_personadbk = persona
                LEFT JOIN discapacidad ON dis_personadbk = persona
                LEFT JOIN residencia ON res_personadbk = persona 
                LEFT JOIN procedencia ON proc_personadbk = persona
                WHERE usuariodbk = ?
                ";
        $sql = $conectar->prepare($sql);
        $sql->bindValue(1, $userId);
        $sql->execute();
        return $resultado = $sql->fetchAll();
    }

    /* =============================================
      ACTUALIZAR PERFIL - USUARIO
      ============================================= */

    public function mdlActualizarClave($datos) {
        $conectar = parent::conectar();
        parent::set_names();
        $sql = "UPDATE usuario SET clave = ? WHERE usuariodbk = ?";
        $sql = $conectar->prepare($sql);
        $sql->bindValue(1, $datos["clave"]);
        $sql->bindValue(2, $datos["usuariodbk"]);
        $sql->execute();
        return $resultado = $sql->fetchAll();
    }

    /* =============================================
      TOTAL DE USUARIOS ACTIVOS
      ============================================= */

    public function Total_Activos() {
        $conectar = parent::conectar();
        parent::set_names();
        $sql = "SELECT count(*) as activos FROM usuario WHERE estado = 'ACTIVO'";
        $sql = $conectar->prepare($sql);
        $sql->execute();
        return $resultado = $sql->fetchAll();
    }

    /* =============================================
      TOTAL DE USUARIOS INACTIVOS
      ============================================= */

    public function Total_Inactivos() {
        $conectar = parent::conectar();
        parent::set_names();
        $sql = "SELECT count(*) as inactivos FROM usuario WHERE estado = 'INACTIVO'";
        $sql = $conectar->prepare($sql);
        $sql->execute();
        return $resultado = $sql->fetchAll();
    }

    /* =============================================
      IMPRIMIR TABLA DE USUARIOS
      ============================================= */

    public function Consultar($fil) {
        $conectar = parent::conectar();
        parent::set_names();
        switch ($fil) {
            case "all":
                $sql = "SELECT * FROM usuario";
                break;
            case "H":
                $sql = "";
                break;
            case "M":
                $sql = "";
                break;
            case "D":
                $sql = "";
                break;
        }
        $sql = $conectar->prepare($sql);
        $sql->execute();
        return $resultado = $sql->fetchAll();
    }

    /* =============================================
      ACTUALIZAR O INSERTAR USUARIO
      ============================================= */

    public function mdlActualizarUsuario($datos) {
        $conectar = parent::conectar();
        parent::set_names();
        if ($datos["usuariodbk"] == "") {
            $encriptar = crypt($datos["clave"], '$2a$07$asxx54ahjppf45sd87a5a4dDDGsystemdev$');
            $sql = "INSERT INTO " . $datos["tabla"] . "  
                (nickname, clave,estado,persona,perfil,foto)
                VALUES (?,?,?,?,?,?);
                ";
            $sql = $conectar->prepare($sql);
            $sql->bindValue(1, $datos["nickname"]);
            $sql->bindValue(2, $encriptar);
            $sql->bindValue(3, "ACTIVO");
            $sql->bindValue(4, $datos["persona"]);
            $sql->bindValue(5, $datos["perfil"]);
            $sql->bindValue(6, "views/img/usuarios/default/anonymous.png");
            $sql->execute();
        } else {
            $encriptar = crypt($datos["clave"], '$2a$07$asxx54ahjppf45sd87a5a4dDDGsystemdev$');
            $sql = "UPDATE " . $datos["tabla"] . " SET
                nickname = ?, clave = ?, persona = ?, perfil = ?, foto = ?                
                WHERE usuariodbk = ?;
                ";
            $sql = $conectar->prepare($sql);
            $sql->bindValue(1, $datos["nickname"]);
            $sql->bindValue(2, $encriptar);
            $sql->bindValue(3, $datos["persona"]);
            $sql->bindValue(4, $datos["perfil"]);
            $sql->bindValue(5, "views/img/usuarios/default/anonymous.png");
            $sql->bindValue(6, $datos["usuariodbk"]);
            $sql->execute();
        }
        return $resultado = $sql->fetchAll();
    }

    public function mdlActualizarEstado($datos) {
        $conectar = parent::conectar();
        parent::set_names();
        $sql = "UPDATE " . $datos["tabla"] . "  
                SET estado = ?
                WHERE usuariodbk = ?";
        $sql = $conectar->prepare($sql);
        $sql->bindValue(1, $datos["estado"]);
        $sql->bindValue(2, $datos["usuariodbk"]);
        $sql->execute();
        return $resultado = $sql->fetchAll();
    }

    public function mdlActualizarFoto($userId,$foto) {
        $conectar = parent::conectar();
        parent::set_names();
        $sql = "UPDATE usuario  
                SET foto = ?
                WHERE usuariodbk = ?";
        $sql = $conectar->prepare($sql);
        $sql->bindValue(1, $foto);
        $sql->bindValue(2, $userId);
        $sql->execute();
        return $resultado = $sql->fetchAll();
    }       
    
    public function Eliminar_por_ID($usuarioId) {
        $conectar = parent::conectar();
        parent::set_names();
        $sql = "
                DELETE FROM usuario WHERE usuariodbk = ?
                ";
        $sql = $conectar->prepare($sql);
        $sql->bindValue(1, $usuarioId);
        $sql->execute();
        return $resultado = $sql->fetchAll();
    }    

}

?>
