<?php 

  require_once("./session_job.php");

  date_default_timezone_set('America/Bahia');

  require_once("./config/conexao.php");

  $conn   = conn();
  $conn_s = conn_s();
  
  require_once("./checar_loja.php");
  
  function connWeb(){
    $db = mysqli_connect("mysql60-farm2.uni5.net", "unidosimportad02", "Xtdc122714", "unidosimportad02") or die("Erro ao selecionar banco");
	   //$db = mysqli_connect("192.185.176.211", "unidosim_newjay", "Chamod@777", "unidosim_db_system") or die("Erro ao selecionar banco");
	   //   $db = mysqli_connect("localhost", "root", "", "unidos_web") or die("Erro ao selecionar banco");
	   mysqli_set_charset($db,"utf8");
	   return $db;
  }
	$connWeb = connWeb();

  if ($_SESSION['tipo_user'] == 6 && $_SESSION['id_user'] != '1'){
    if (!in_array(4, $_SESSION['PRIVILEGIOS'])) {
      session_destroy();
      echo "<script>window.location = 'index.php';</script>";
    }
  } else {
    if ($_SESSION['tipo_user'] != 5 && $_SESSION['id_user'] != '1') {
      echo "<script>window.location = 'index.php'</script>";
    }
  }

?>

<!DOCTYPE html>

<html lang="pt-br">

  <head>

    <meta charset="UTF-8" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>Users</title>



    <link rel="stylesheet" href="./utils/css/bootstrap.min.css" />

    <link rel="stylesheet" href="./utils/css/bootstrap-select.min.css" />

    <link rel="stylesheet" href="./utils/css/styles.css" />

    <link

      rel="stylesheet"

      href="https://use.fontawesome.com/releases/v5.8.2/css/all.css"

      integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay"

      crossorigin="anonymous"

    />

  </head>

  <body>

    <nav class="navbar">

      <div class="container caixa_logo">

        <a href="javascript:void(0);">

          <img src="./utils/img/logo.png" alt="" width="150" />

        </a>

        <div>
        <?php
          if (isset($_SESSION['id_user'])){
            if (@$_SESSION['id_user'] == '11' || @$_SESSION['id_user'] == '6' || @$_SESSION['id_user'] == '1') {
              ?>
                <!-- <span><a href="fazer_backup.php" style="color: #fff;background-color:#00f; padding:5px;border-radius: 15px;">BACKUP</a></span> -->
              <?php
            }
          }
        ?>

          <?php if (isset($_SESSION['id_user']) || !empty($_SESSION['id_user'])) {?>

          <span><?= $_SESSION['nome_user'];?></span> &nbsp;

          <?php if ($_SESSION['tipo_user'] == 6 || $_SESSION['id_user'] == '1'){?>
          <span><a href="index.php"><img src="./utils/img/icons/home.svg" width="19"></a></span> &nbsp;
          <?php }?>

          <?php if ($_SESSION['tipo_user'] == 5){?>
            <span><a href="index.php"><img src="./utils/img/icons/archive.svg" width="19"></a></span> &nbsp;
          <span><a href="dashboard.php"><img src="./utils/img/icons/home.svg" width="19"></a></span> &nbsp;
          <?php }?>

          <span><a href="exit.php"><img src="./utils/img/icons/exit.svg" width="17"></a></span>

          <?php }?>

        </div>

      </div>

    </nav>



    <!--Body-->

    <div class="container">

      <div class="table-responsive mt-5">

        <div class="row">
          <div class="col-lg-2">
            <?php if ($_SESSION['tipo_user'] == 6){?>
              <?php if (in_array(3, $_SESSION['PRIVILEGIOS'])) {?>
                <button class="btn btn-info" data-toggle="modal" data-target="#create_user"><i class="fa fa-plus"></i> Novo Usuário</button>
              <?php }?>
            <?php }else{?>
              <button class="btn btn-info" data-toggle="modal" data-target="#create_user"><i class="fa fa-plus"></i> Novo Usuário</button>
            <?php }?>
          </div>

          <?php
            if ($_SESSION['loja'] == 'todas') {
              ?>
                <div class="col-lg-2">
                  <select class="form-control" name="loja" id="loja" onchange="window.location='/sistema/users.php?loja='+this.value">
                    <option value="0">Todas</option>
                    <?php 
                      $getAlllojas = mysqli_query($conn_s, "SELECT * FROM uni_lojas");
      
                      if ($getAlllojas) {
                        while ($lj = mysqli_fetch_array($getAlllojas)) {
                          ?>
                            <option value="<?= $lj['id'];?>" <?php if(@$_GET['loja'] == $lj['id']) {echo "selected";}?>><?= $lj['nome'];?></option>
                          <?php
                        }
                      }
                    ?>
                  </select>
                </div>

                <div class="col-lg-8">
                  <span>A listagem apresenta usuários que atuam em todas as lojas e usuários que atuam apenas na loja especificada.</span>
                </div>
              <?php
            }
          ?>

        </div>

        <table class="table table-bordered table-sm mt-3" style="font-size: 14px;">

          <thead>

            <tr>

              <th style="width:10px;text-align:center;">#</th>

              <th style="width: 150px">Criação</th>

              <th>Nome</th>

              <th>Email</th>
              
              <th>Loja</th>
              
            <?php if ($_SESSION['tipo_user'] == 6){?>
              <?php if (in_array(5, $_SESSION['PRIVILEGIOS'])) {?>
                <!-- <th style="text-align: center;width: 80px;">Privilégios</th> -->
              <?php }?>
            <?php }else{?>
              <!-- <th style="text-align: center;width: 80px;">Privilégios</th> -->
            <?php }?>

              
            <?php if ($_SESSION['tipo_user'] == 6){?>
              <?php if (in_array(5, $_SESSION['PRIVILEGIOS'])) {?>
              <th style="width:50px;text-align:center;"><img src='./utils/img/icons/user_single.svg' width='18' /></th>
              <?php }?>
            <?php }else{?>
              <th style="width:50px;text-align:center;"><img src='./utils/img/icons/user_single.svg' width='18' /></th>
            <?php }?>

            <?php if ($_SESSION['tipo_user'] == 6){?>
              <?php if (in_array(5, $_SESSION['PRIVILEGIOS'])) {?>
              <th style="width:50px;text-align:center;"><img src="./utils/img/icons/edit.svg" width="18" /></th>
              <?php }?>
            <?php }else{?>
              <th style="width:50px;text-align:center;"><img src="./utils/img/icons/edit.svg" width="18" /></th>
            <?php }?>

            <?php if ($_SESSION['tipo_user'] == 6){?>
              <?php if (in_array(6, $_SESSION['PRIVILEGIOS'])) {?>
              <th style="width:50px;text-align:center;"><img src="./utils/img/icons/remove.svg" width="18" /></th>
              <?php }?>
            <?php }else{?>
              <th style="width:50px;text-align:center;"><img src="./utils/img/icons/remove.svg" width="18" /></th>
            <?php }?>
            
            </tr>

          </thead>

          <tbody>

            <?php 

            $loja_id = $_SESSION['loja'];
            if ($_SESSION['loja'] != 'todas') {

              $getAllUsers = mysqli_query($conn, "SELECT * FROM user WHERE id <> 1 AND loja_id = $loja_id ORDER BY id DESC");

            } else {
              
              if(!empty($_GET['loja'])){
                $search_loja = $_GET['loja'];
                $getAllUsers = mysqli_query($conn, "SELECT * FROM user WHERE id <> 1 AND (loja_id = $search_loja OR user_geral = 'sim') ORDER BY id DESC");
              } else {
                
                $getAllUsers = mysqli_query($conn, "SELECT * FROM user WHERE id <> 1 ORDER BY id DESC");
              }
            }


            if ($getAllUsers) {

              $contador = 1;

              while ($lista = mysqli_fetch_array($getAllUsers)) {

            ?>

            <tr>

              <td style="text-align:center;"><?= $contador;?></td>

              <td><?= date('d-m-Y H:i:s', strtotime($lista['data_cadastro']));?></td>

              <td><?= $lista['nome'];?></td>

              <td><?= $lista['email'];?></td>
              
              <td>
                <?php
                  if(!empty($lista['loja_id'])){
                    $loja_id = $lista['loja_id'];
                    $getLoja = mysqli_query($conn_s, "SELECT * FROM uni_lojas WHERE id = $loja_id");
                    $result  = mysqli_fetch_array($getLoja);
                    echo $result['nome'];
                  } else{
                    echo "Geral";
                  }
                ?>
              </td>

              <?php if ($_SESSION['tipo_user'] == 6){?>
                <?php if (in_array(5, $_SESSION['PRIVILEGIOS'])) {?>
                <!-- <td><div style="display: flex;justify-content: center;">
                  <?php if ($lista['tipo_user'] == 6){?>
                    <a data-toggle="modal" data-target="#modalPriv" style="cursor: pointer;" onclick="popularCampoPrivilegio('<?= $lista['id'];?>')"
                    >&#9776;
                    </a></div>
                    <?php }?>
                </td> -->
                <?php }?>
              <?php }else{?>
                <!-- <td><div style="display: flex;justify-content: center;">
                  <?php if ($lista['tipo_user'] == 6){?>
                    <a data-toggle="modal" data-target="#modalPriv" style="cursor: pointer;" onclick="popularCampoPrivilegio('<?= $lista['id'];?>')"
                    >&#9776;
                    </a></div>
                    <?php }?>
                </td> -->
              <?php }?>

              <?php 

                if (!empty($lista['status'])) {

                  $received = "<img src='./utils/img/icons/user_block.svg' width='18' />";

                } else {

                  $received = "<img src='./utils/img/icons/user_check.svg' width='18' />";

                }

              ?>
              <?php if ($_SESSION['tipo_user'] == 6){?>
                <?php if (in_array(5, $_SESSION['PRIVILEGIOS'])) {?>
                <td style="text-align:center;"><button onClick="mudarSituacao('<?= $lista['status'];?>','<?= $lista['id'];?>')"><?= $received;?></button></td>
                <?php }?>
              <?php }else{?>
                <td style="text-align:center;"><button onClick="mudarSituacao('<?= $lista['status'];?>','<?= $lista['id'];?>')"><?= $received;?></button></td>
              <?php }?>

              <?php if ($_SESSION['tipo_user'] == 6){?>
                <?php if (in_array(5, $_SESSION['PRIVILEGIOS'])) {?>
                <td style="text-align:center;"><button data-toggle="modal" data-target="#update_user"

                onClick="popularEditarUser('<?= $lista['id'];?>','<?= $lista['nome'];?>','<?= $lista['email'];?>','<?= $lista['tipo_user'];?>','<?= $lista['senha_block'];?>', '<?= $lista['email_vendedor'];?>', '<?= $lista['loja_id'];?>', '<?= $lista['user_geral'] ?>')"        

              ><img src="./utils/img/icons/edit.svg" width="18" /></button></td>
                <?php }?>
              <?php }else{?>
                <td style="text-align:center;"><button data-toggle="modal" data-target="#update_user"

                onClick="popularEditarUser('<?= $lista['id'];?>','<?= $lista['nome'];?>','<?= $lista['email'];?>','<?= $lista['tipo_user'];?>','<?= $lista['senha_block'];?>', '<?= $lista['email_vendedor'];?>', '<?= $lista['loja_id'];?>', '<?= $lista['user_geral'] ?>')"

              ><img src="./utils/img/icons/edit.svg" width="18" /></button></td>
              <?php }?>

              <?php if ($_SESSION['tipo_user'] == 6){?>
                <?php if (in_array(6, $_SESSION['PRIVILEGIOS'])) {?>
                <td style="text-align:center;"><button onClick="deletarUser('<?= $lista['id'];?>')"><img src="./utils/img/icons/remove.svg" width="18" /></button></td>
                <?php }?>
              <?php }else{?>
                <td style="text-align:center;"><button onClick="deletarUser('<?= $lista['id'];?>')"><img src="./utils/img/icons/remove.svg" width="18" /></button></td>
              <?php }?>

            </tr>

            <?php $contador++;}}?>

          </tbody>

        </table>

      </div>

    </div>

    <!--/. Body-->

    <div style="margin-top: 50px;"></div>

    <!--Footer-->

    <footer>

      <div class="container">

        <p>&copy; UNIDOS IMPORTADOS</p>

        <p>

          DESENVOLVIDO PELA

          <a href="https://agenciadp.com.br/" target="_blank">AGÊNCIA DP WEB</a>

        </p>

      </div>

    </footer>

    <!--/. Footer-->



    <!--Criar Usuário-->

    <div class="modal fade" id="create_user" tabindex="-1" role="dialog" aria-labelledby="create_userdms" aria-hidden="true">

      <form class="px-4 py-3" method="post" id="form_create_user" onSubmit="ChamadaPadrao(this.id,'create_btn');return false;" >

        <div class="modal-dialog" role="document">

          <div class="modal-content">

            <div class="modal-header">

              <h5 class="modal-title" id="create_userdms">Criar Usuário</h5>

              <button type="button" class="close" data-dismiss="modal" aria-label="Fechar">

                <span aria-hidden="true">&times;</span>

              </button>

            </div>

            <div class="modal-body">

                <input type="hidden" name="cod" value="12">



                <div class="form-group">

                  <label for="nome_create">Nome</label>

                  <input class="form-control" name="nome" id="nome_create" placeholder="Nome Completo" required>

                </div>

                <div class="form-group">

                  <label for="email_create">E-mail</label>

                  <input type="email" class="form-control" name="email" id="email_create" required placeholder="E-mail para acessar o sistema">

                </div>

                <div class="form-group">

                  <label for="senha_create">Senha</label>

                  <input type="password" class="form-control" name="senha" id="senha_create" required placeholder="Senha do Usuário">

                </div>

                <?php
                  $display = 'block';
                  if ($_SESSION['id_user'] == '1') {
                    $display = 'none';
                    ?>
                      <div class="form-group">
                    
                        <label for="user_geral">Atuação em todas as lojas</label>
                      
                        <select class="form-control" name="user_geral" id="user_geral" onchange="disableLojas(this.value, 'loja')" required>
                          <option value="sim">Sim</option>
                          <option value="nao">Não</option>
                        </select>
                      
                      </div>
                    <?php
                  }

                  if ($_SESSION['loja'] != 'todas') {

                    ?>
                      <div class="form-group">
                    
                        <label for="loja">Loja</label>
                      
                        <input type="hidden" class="form-control" name="loja" id="loja" value="<?= $_SESSION['loja'] ?>">

                        <input type="text" readonly class="form-control" value="<?php

                            $getLoja = mysqli_fetch_object(mysqli_query($conn_s, "SELECT * FROM uni_lojas WHERE id = $loja_id"));

                            echo $getLoja->nome;

                          ?>">
                      
                      </div>
                    <?php
                    
                  } else {

                    ?>
                      <div class="form-group">
                    
                        <label for="loja">Loja</label>
                      
                        <select style="display:<?= $display ?>;" class="loja form-control" name="loja" id="loja">

                          <option value="" selected disabled>Selecione uma opção</option>

                          <?php 

                            $getAlllojas = mysqli_query($conn_s, "SELECT * FROM uni_lojas");

                            if ($getAlllojas) {
                              while ($lj = mysqli_fetch_array($getAlllojas)) {

                          ?>

                          <option value="<?= $lj['id'];?>" <?php if(@$_GET['loja'] == $lj['id']){echo "selected";} ?>><?= $lj['nome'];?></option>

                          <?php }}?>

                        </select>
                      
                      </div>
                    <?php

                  }
                ?>
        
        

                <div class="form-group">

                  <label for="tipo_create">Tipo do Usuário</label>

                  <select class="form-control" name="tipo" id="tipo_create" required >

                    <option value="" selected="">Selecione uma opção</option>

                    <?php 

                      $getAllTipos = mysqli_query($conn, "SELECT * FROM tipo_user");

                      if ($getAllTipos) {

                        while ($lista = mysqli_fetch_array($getAllTipos)) {

                    ?>

                    <option value="<?= $lista['id'];?>"><?= $lista['descricao_tipo'];?></option>

                    <?php }}?>

                  </select>

                </div>

                <div class="form-group">
                  <label for="senha_block_add">Bloqueio de Senha <br><small>esse bloqueio impede que essa senha seja utilizada nos processos de solicitações</small></label>
                  <select name="senha_block" id="senha_block_add" class="form-control" required="">
                    <option value="1" selected="">Desbloqueada</option>
                    <option value="2">Bloqueada</option>
                  </select>
                </div>

            </div>

            <div class="modal-footer">

              <button type="submit" class="btn btn-success" id="create_btn">Salvar</button>

              <button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>

            </div>

          </div>

        </div>

      </form>

    </div>

    <!--/. Criar Usuário-->

    <!--privilégios-->
    <div class="modal fade" id="modalPriv" tabindex="-1" role="dialog" aria-labelledby="modalPrivdms" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
            <form method="post" id="form_modalPriv" onSubmit="ChamadaPadrao(this.id,'btn_modalPriv');return false;">
          <div class="modal-header">
            <h5 class="modal-title" id="modalPrivdms">Tela de Privilégios</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <input type="hidden" name="cod" value="15">
            <input type="hidden" name="id_user_esc" id="id_user_esc">
            <div id="recebe_campos"></div>
          </div>
          <div class="modal-footer">
            <button class="btn btn-success" name="BTN_SAVE" id="btn_modalPriv">&#9998; Salvar <span id="span_modalPriv"></span></button>
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>
          </div>
          </form>
        </div>
      </div>
    </div>



    <!--Editar Usuário-->

    <div class="modal fade" id="update_user" tabindex="-1" role="dialog" aria-labelledby="update_userdms" aria-hidden="true">

      <form class="px-4 py-3" method="post" id="form_update_user" onSubmit="ChamadaPadrao(this.id,'update_btn');return false;" >

        <div class="modal-dialog" role="document">

          <div class="modal-content">

            <div class="modal-header">

              <h5 class="modal-title" id="update_userdms">Editar Usuário</h5>

              <button type="button" class="close" data-dismiss="modal" aria-label="Fechar">

                <span aria-hidden="true">&times;</span>

              </button>

            </div>

            <div class="modal-body">

                <input type="hidden" name="cod" value="13">

                <input type="hidden" name="id_esc" id="id_esc_up_user">



                <div class="form-group">

                  <label for="nome_update">Nome</label>

                  <input class="form-control" name="nome" id="nome_update" placeholder="Nome Completo" required>

                </div>

                <div class="form-group">

                  <label for="email_update">E-mail</label>

                  <input type="email" class="form-control" name="email" id="email_update" required placeholder="E-mail para acessar o sistema">

                </div>
				
			          <div class="form-group">

                  <label for="email_vendedor">E-mail de vendedor</label>

                  <input type="email" class="form-control" name="email_vendedor" id="email_vendedor" placeholder="E-mail para envio">

                </div>

                <?php

                  if ($_SESSION['id_user'] == '1') {


                    ?>

                      <div class="form-group">
                    
                        <label for="user_geral_edit">Atuação em todas as lojas</label>
                      
                        <select class="form-control" name="user_geral" id="user_geral_edit" onchange="disableLojas(this.value, 'loja_edit')" required>
                          <option value="sim">Sim</option>
                          <option value="nao">Não</option>
                        </select>
                      
                      </div>
                    <?php
                  }

                  if ($_SESSION['loja'] != 'todas') {

                    ?>
                      <div class="form-group">
                    
                        <label for="loja">Loja</label>
                      
                        <input type="hidden" class="loja_edit form-control" name="loja" id="loja_edit" value="<?= $_SESSION['loja'] ?>">

                        <input type="text" readonly class="form-control" value="<?php

                            $getLoja = mysqli_fetch_object(mysqli_query($conn_s, "SELECT * FROM uni_lojas WHERE id = $loja_id"));

                            echo $getLoja->nome;

                          ?>">
                      
                      </div>
                    <?php
                    
                  } else {

                    ?>

                      <div class="form-group">
                    
                        <label for="loja">Loja</label>
                      
                        <select class="loja_edit form-control" name="loja" id="loja_edit" required>

                          <option value="0" selected disabled>Selecione uma opção</option>

                          <?php 

                            $getAlllojas = mysqli_query($conn_s, "SELECT * FROM uni_lojas");

                            if ($getAlllojas) {
                              while ($lj = mysqli_fetch_array($getAlllojas)) {

                          ?>

                          <option value="<?= $lj['id'];?>"><?= $lj['nome'];?></option>

                          <?php }}?>

                        </select>
                      
                      </div>

                    <?php

                  }
                ?>

                <div class="form-group">

                  <label for="senha_update">Senha

                  <small> <br> Ao digitar uma nova senha no campo a baixo, a antiga será perdida e substituída pela nova.</small>

                  </label>

                  <input type="password" class="form-control" name="senha" id="senha_update"

                    onfocus="this.removeAttribute('readonly');"

                    onblur="this.setAttribute('readonly', true);"

                    readonly="true"

                    autocomplete="off" placeholder="Substituir senha">

                </div>

                <div class="form-group">

                  <label for="tipo_update">Tipo do Usuário</label>

                  <select class="form-control" name="tipo" id="tipo_update" required>

                    <option value="" selected="">Selecione uma opção</option>

                    <?php 

                      $getAllTipos = mysqli_query($conn, "SELECT * FROM tipo_user");

                      if ($getAllTipos) {

                        while ($lista = mysqli_fetch_array($getAllTipos)) {

                    ?>

                    <option value="<?= $lista['id'];?>"><?= $lista['descricao_tipo'];?></option>

                    <?php }}?>

                  </select>

                </div>

                <div class="form-group">
                  <label for="senha_block_edt">Bloqueio de Senha <br><small>esse bloqueio impede que essa senha seja utilizada nos processos de solicitações</small></label>
                  <select name="senha_block" id="senha_block_edt" class="form-control">
                    <option value="1">Desbloqueada</option>
                    <option value="2">Bloqueada</option>
                  </select>
                </div>

                

              

            </div>

            <div class="modal-footer">

              <button type="submit" class="btn btn-success" id="update_btn" onClick="return confirm('Confirmar esta ação?');">Salvar</button>

              <button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>

            </div>

          </div>

        </div>

      </form>

    </div>

    <!--/. Editar Usuário-->



    <?php
      require("./modal.php");


      require_once './components/body_imports.php';
    ?>

    <script type="text/javascript">
      function disableLojas(geral, select_loja_class) {
        const select_loja    = document.querySelector(`.${select_loja_class}`);
        const input_readonly = document.querySelector('#loja-geral');
        if(geral == 'sim'){
          
          const option_null = (select_loja.children)[0];
          option_null.setAttribute('selected', true);
          option_null.setAttribute('disabled', false);
          select_loja.value = '0';
          select_loja.setAttribute('readonly', true);
          select_loja.removeAttribute('required');
          select_loja.style.display = 'none';
          input_readonly.style.display = 'block';
        } else {
          
          select_loja.removeAttribute('readonly');
          select_loja.setAttribute('required', true);
          select_loja.style.display = 'block';
          input_readonly.style.display = 'none';
        }
      }
    </script>

  </body>

</html>

