<?php  

 ini_set('display_errors', 1);
 ini_set('display_startup_erros', 1);
 error_reporting(E_ALL);
require_once(__DIR__."/../config.php");
    
$cs = new cs;
    
$_SESSION['error'] = 0;

if (!isset($_SESSION['error_count'])) {
    $_SESSION['error_count'] = 0;
}

if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST' && isset($_POST['token'], $_POST['username'], $_POST['password'], $_SESSION['tkn_log'])) {  
    $login = $cs->filterKey($_POST['username']);
    $senha = $cs->filterKey($_POST['password']);

    $row_user = $cs->getManager($login);
    
    //var_dump($_POST, $_SESSION); exit;
    
    if (count($row_user) > 0) {
        
        //var_dump(!is_null($row_user['timeout']) || strtotime($row_user['timeout']) <= strtotime('now')); exit;
        
        // if (!is_null($row_user['timeout']) || strtotime($row_user['timeout']) <= strtotime('now')) {

        //     if ($_SESSION['error_count'] > 3) {
        //         $query = $cs->executeQuery("UPDATE authenticator SET token = null, ip = '".$_SERVER["REMOTE_ADDR"]."', timeout = '". date('Y-m-d H:i:s', strtotime('+30 minutes')) ."' WHERE user_id = {$row_user['id']}");
                
        //     } else {
               
                if ($_SESSION['error_count'] <= 3 && $_POST['token'] == $_SESSION['tkn_log'])
                {
                    $query = $cs->executeQuery("SELECT * from gerenciadores WHERE login = '{$login}' AND senha = '{$senha}' ");

                    if($cs->num_rows($query) == 0)
                    {
                        $_SESSION['error']        = 1;
                        $_SESSION['error_count'] += 1;
                    }
                    else
                    {
                        list($row_info) = $cs->fetchQuery($query);

                        // $row_info['gerenciador_responsavel'] = 0;
                        
                        // Seleciona os dados do gerenciador responsavel
                        $query = $cs->executeQuery("SELECT * from gerenciadores WHERE id = '{$row_info['gerenciador_responsavel']}'");

                        // Atribui o resultado a variavel gerenciador_exists
                        $gerenciador_exists = $cs->num_rows($query);

                        // Atribui os dados do gerenciador responsavel
                        list($gerenciador_responsavel) = $cs->fetchQuery($query);

                        // Checa se o gerenciador responsavel é is_null OU 'NULL' OU se não existe OU se está desativado
                        
                        if (count($row_info['gerenciador_responsavel']) == 0) {
                        
                            echo "<script>alert('Seu gerenciador está bloqueado no momento!\\nContate a administração.')</script>";
                        
                        // Checa se está desativado
                        } else if ($row_info['status'] == 'desativado') {
                            
                            echo "<script>alert('Seu gerenciador PAI está desativado no momento!\\nContate a administração.')</script>";

                        } else if ($row_info['status'] == 'normal' && strtotime(date('Y-m-d')) < strtotime($row_info['vencimento'])) {
                            
                            $_SESSION['token']       = $cs->setTokenGerenciador($row_info['id']);
                            $_SESSION['error_count'] = 0;
                            $_SESSION['logado_unf']  = 1;
                            $_SESSION['info_unf']    = $row_info;
                            // var_dump($row_info); 
                            // echo "ENTREI EM LOGIN" ; exit;
                            exit(header("Location: /beta/dashboard/"));
                        } elseif(strtotime(date('Y-m-d')) > strtotime($row_info['vencimento'])) {
                            echo "<script>alert('Seu gerenciador está expirado!\\nContate a administração para renovação do mesmo.')</script>";
                        } else
                        {
                            echo "<script>alert('Seu gerenciador está desativado no momento!\\nContate a administração.')</script>";
                        }
                    }
                }                 
            //}

        // } else {
        
        //     echo "<script>alert('Seu gerenciador está bloqueado no momento até as ".date('H:i', strtotime($row_user['timeout']))." !\\nContate a administração.')</script>";
        // }  

    } else {
        
        $_SESSION['error'] = 1;
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" type="image/png" sizes="16x16" href="../plugins/images/favicon.png">
    <title>Space Code 2.0 - Login</title>
    <!-- Bootstrap Core CSS -->
    <link href="../public/assets/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../plugins/bower_components/bootstrap-extension/css/bootstrap-extension.css" rel="stylesheet">
    <!-- animation CSS -->
    <link href="../public/assets/css/animate.css" rel="stylesheet">
    <!-- Custom CSS -->
    <link href="../public/assets/css/style.css" rel="stylesheet">
    <!-- color CSS -->
    <link href="../public/assets/css/colors/default-dark.css" id="theme" rel="stylesheet">
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
    <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>

<body>
    <input type="hidden" value="<?= $_SESSION['error_count']; ?>"> 
    <!-- Preloader -->
    <div class="preloader">
        <div class="cssload-speeding-wheel"></div>
    </div>
    <section id="wrapper" class="login-register" >

        
        <div class="login-box">
            
            <div class="white-box">
                <div class="panel panel-danger loginerror">
                    <div class="panel-heading">
                        <span class="msgLogin">Login e/ou senha inválidos!</span>
                        <div class="pull-right">
                            <a href="#" data-perform="panel-dismiss"><i class="ti-close"></i></a> 
                        </div>
                    </div>   
                </div>
                <form class="form-horizontal form-material" id="login" method="POST" data-toggle="validator" novalidate="true">
                   
                    <h3 class="box-title m-b-20">Login</h3>
                    <div class="form-group">
                        <div class="help-block with-errors"></div>
                        <input name="token" value="<?= $_SESSION['tkn_log'] = md5(rand()); ?>" type="hidden"/>
                        <div class="col-xs-12">
                            <input class="form-control" type="text" required id="username" name="username" placeholder="Entre com Usuário">
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-xs-12">
                            <div class="help-block with-errors"></div>
                            <input class="form-control" type="password" required id="password" name="password" placeholder="Entre com a Senha">
                        </div>
                    </div>
                    
                    <div class="form-group text-center m-t-20">
                        <div class="col-xs-12">
                            <button class="btn btn-info btn-lg btn-block text-uppercase waves-effect waves-light" type="submit">Entrar</button>
                        </div>
                    </div>
                    
                    
                </form>
                
            </div>
        </div>
    </section>
    <!-- jQuery -->
    <script src="../plugins/bower_components/jquery/dist/jquery.min.js"></script>
    <!-- Bootstrap Core JavaScript -->
    <script src="../public/assets/bootstrap/dist/js/tether.min.js"></script>
    <script src="../public/assets/bootstrap/dist/js/bootstrap.min.js"></script>
    <script src="../plugins/bower_components/bootstrap-extension/js/bootstrap-extension.min.js"></script>
    <!-- Menu Plugin JavaScript -->
    <script src="../plugins/bower_components/sidebar-nav/dist/sidebar-nav.min.js"></script>
    <!--slimscroll JavaScript -->
    <script src="../public/assets/js/jquery.slimscroll.js"></script>
    <!--Wave Effects -->
    <script src="../public/assets/js/waves.js"></script>
    <!-- Custom Theme JavaScript -->
    <script src="../public/assets/js/custom.min.js"></script>
    <!--Style Switcher -->
    <script src="../plugins/bower_components/styleswitcher/jQuery.style.switcher.js"></script>

    <script src="../public/assets/js/validator.js"></script>
    
    <script type="text/javascript">
        
        $(document).ready(function(){
            $('.loginerror').hide()

            
            $('#login').submit(function(){
                
                var u = jQuery(this).find('#username');
                var l = jQuery(this).find('#password');
                
                if(u.val() == '' || l.val() == '') {
                    jQuery('.loginerror').show() 
                    jQuery('.msgLogin').text('Insira seu login e/ou senha')
                    jQuery('.loginerror').slideDown()
                    u.focus();
                    return false;   
                }
            })
            
            $('#username').keypress( function(){
                jQuery('.loginerror').slideUp()
            })
                
            <?php
            if($_SESSION['error'])
            {
            ?>
                jQuery('.loginerror').slideDown();
            <?php
            }
            ?>
        })
    </script>
</body>

</html>
