<?php include('fncr-geral/configuracao_geral.php');
$pagina = "usuarios";


// Cadastrando jogador para acesso às estatísticas
if(isset($_POST['cadastrar']) && $_POST['cadastrar'] == 'usuario') {

  $login = $_POST['login'];
  if(isset($_POST['nivel']) && $_POST['nivel'] == 1){
    $nivel = 1;$status = 0;
  }else{
    $nivel = 2;$status = 1;
  }

  // Verificando se o login já existe // USUARIO
  $sql_verificar_cadastro = $bd->getConexao()->prepare('SELECT * FROM usuarios WHERE login = :login AND excluido = 0');
  $sql_verificar_cadastro->bindValue(':login', $login, PDO::PARAM_STR);
  if( $sql_verificar_cadastro->execute() ) { $resul_verificar_cadastro = $sql_verificar_cadastro->fetch(PDO::FETCH_ASSOC);}

  if($resul_verificar_cadastro['login'] == ""){
    $nome = $_POST['nome'];
    $senha = $_POST['senha'];

    $senha_md5 = md5($senha);

    // Cadastrando Usuário
    $sql_cadastrando = $bd->getConexao()->prepare('INSERT INTO usuarios
      (nome, login, senha, codigo, nivel, status, excluido) VALUES
      ("' . $nome . '", "' . $login . '", "' . $senha_md5 . '", "'.$clube_cod_acesso.'", "'.$nivel.'", "'.$status.'", "0")');
    if ($sql_cadastrando->execute()) ;

    // Coletando ID do usuario criado
    $sql_usuario_cadastrado = $bd->getConexao()->prepare('SELECT * FROM usuarios ORDER BY id DESC LIMIT 1');
    if( $sql_usuario_cadastrado->execute() ) { $resul_usuario_cadastrado = $sql_usuario_cadastrado->fetch(PDO::FETCH_ASSOC);}
    $id_usuario_cadastrado = $resul_usuario_cadastrado['id'];

    if($nivel != 1){
      // Cadastrando Permissões
      $sql_cadastrando = $bd->getConexao()->prepare('INSERT INTO usuarios_permissoes
      (usuario_id) VALUES ("'. $id_usuario_cadastrado .'")');
      if ($sql_cadastrando->execute()) ;
    }

  }else{
    $mensagem = "erro";
    $mensagem_frase = "O Login de acesso já existe. Escolha outro.";
  }

}


// ************************************** GERAL **************************************

// Lista de Usuários
$sql_cadastros = $bd->getConexao()->prepare('
SELECT usuarios.*
FROM usuarios
WHERE nivel >= 1 AND excluido = 0
GROUP BY usuarios.id
ORDER BY nivel ASC, nome ASC');
if( $sql_cadastros->execute() ) { $resul_cadastros = $sql_cadastros->fetchall(PDO::FETCH_ASSOC);}

//Configurações do Controle
$valor_liberado = '0'; $valor_bloqueado = '1';

?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
  <?php include('fncr-geral/html-head.php');?>

  <link rel="stylesheet" type="text/css" href="js/datatables2/media/css/jquery.dataTables.css">
  <script type="text/javascript" language="javascript" src="js/datatables2/media/js/jquery.dataTables.js"></script>

  <link rel="stylesheet" href="js/checkbox/jquery.checkbox.css" />

<script type="text/javascript">

  $(document).ready(function(){

    $('input:checkbox.top5').checkbox();

    $("input[name='status[]']").click(function(){
      var $this = $( this );//guardando o ponteiro em uma variavel, por performance

      var i = $this.attr('id');
      var t = $this.attr('tabela');
      var c = $this.attr('controle');

      var s = $this.attr('checked') ? <?php echo $valor_bloqueado ?> : <?php echo $valor_liberado ?>;

      $.ajax({
        url: 'js/checkbox/checkbox_bd.php',
        type: 'POST', cache: false,
        data: { t: t, c: c, i: i, s: s, tk: "<?php echo $_SESSION['dados_usuario']['codacesso']?>" }
      });

      if($this.attr('checked')){
        $this.attr("checked", false);
      }else{
        $this.attr("checked", true);
      }

    });


  });
</script>

</head>
<body>

<!-- BARRA SUPERIOR -->
<?php include('barra-sup.php');?>
<!-- MENU PRINCIPAL -->
<?php include('menu.php');?>

<section id="content">
    <!-- MENSAGENS DE ALERTA -->
  <?php include('fncr-geral/mensagens.php');?>

    <div class="clearfix padder bg-fncr-clearfix">
        <h3 class="m-b">Usuários</h3>
    </div>

<section id="content" class="content-sidebar bg-white">
<section class="main">
<br>

  <div class="col-lg-12">
    <section class="panel" style="margin-bottom: 200px;">
      <header class="panel-heading">
        <a data-toggle="modal" href="#modal_cadastrar_usuario" data-backdrop="static" class="btn btn-inverse btn-xs pull-right jsinbloq">Novo Usuário</a>
        Usuários do Sistema
      </header>
      <div class="table-responsive">
        <table class="table table-striped b-t text-small" id="lista_jogadores">
          <thead>
          <tr>
            <th class="text-center" width="1"></th>
            <th width="200">Nome</th>
            <th class="text-center" width="150">Login</th>
            <th class="text-center" width="150">Status</th>
          </tr>
          </thead>
          <tbody>
          <?php foreach ($resul_cadastros as $linha_cadastros) {

            if($linha_cadastros['status'] == 0){
              $checked = 'checked="checked"';  }else{
              $checked = '';  }

          ?>
          <tr>
            <td class="text-info">
              <div class="btn-group jsinbloq">
                <a href="usuarios_detalhes.php?u=<?php echo $linha_cadastros['id']?>"><i class="fa fa-folder-open fa-lg" data-toggle="tooltip" data-placement="top" title="Abrir Cadastro"></i></a>
              </div>
            </td>
            <td><?php echo $linha_cadastros['nome']?></td>
            <td class="text-center"><?php echo $linha_cadastros['login']?></td>
            <td class="text-center">
              <div class="top5 jsinbloq">
                <input type="checkbox" name="status[]" class="top5" <?php echo $checked?> id="<?php echo $linha_cadastros['id']?>" tabela="usuarios" controle="status"/>
              </div>
            </td>
          </tr>
          <?php } ?>
          </tbody>
        </table>
      </div>
    </section>
  </div>

</section>
</section>

<!-- FOOTER -->
<?php include('footer.php');?>

<!-- Modal Cadastrar Usuário -->
<div id="modal_cadastrar_usuario" class="modal fade bs-example-modal-sm">
  <form class="m-b-none" method="post" action="" data-validate="parsley" enctype="multipart/form-data">
    <input type="hidden" name="cadastrar" value="usuario" />
    <div class="modal-dialog  modal-sm" style="width: 350px;">
      <div class="modal-content">
        <div class="modal-header bg-info">
          <button type="button" class="close" data-dismiss="modal"><i class="fa fa-times"></i></button>
          <h4 class="modal-title" id="myModalLabel">Novo Usuário</h4>
        </div>
        <div class="modal-body">
          <div class="row">
            <div class="col-lg-12" style="margin-bottom: 15px;">
              <input type="text" class="form-control" name="nome" placeholder="Nome" data-required="true">
            </div>
            <div class="col-lg-6">
              <input type="text" class="form-control" name="login" placeholder="Login" data-required="true">
            </div>
            <div class="col-lg-6">
              <input type="password" class="form-control" name="senha" placeholder="Senha" data-required="true">
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-sm btn-default" data-dismiss="modal">Cancelar</button>
          <button type="submit" class="btn btn-sm btn-info">Criar</button>
        </div>
      </div>
    </div>
  </form>
</div>

<!-- app -->
<script src="js/app.js"></script>
<script src="js/app.plugin.js"></script>
<script src="js/app.data.js"></script>
<!-- Sparkline Chart -->
<script src="js/charts/sparkline/jquery.sparkline.min.js"></script>
<!-- Easy Pie Chart -->
<script src="js/charts/easypiechart/jquery.easy-pie-chart.js"></script>
<!-- select2 -->
<script src="js/select2/select2.min.js"></script>
<!-- fuelux -->
<script src="js/fuelux/fuelux.js"></script>
<!-- datepicker -->
<script src="js/datepicker/bootstrap-datepicker.js"></script>
<!-- slider -->
<script src="js/slider/bootstrap-slider.js"></script>
<!-- file input -->
<script src="js/file-input/bootstrap.file-input.js"></script>
<!-- combodate -->
<script src="js/combodate/moment.min.js"></script>
<script src="js/combodate/combodate.js"></script>
<!-- parsley -->
<script src="js/parsley/parsley.min.js"></script>
<!-- checkbox -->
<script src="js/checkbox/jquery.checkbox.min.js"></script>

</body>
</html>
<?php $bd = null; $bd_fn = null;?>