<?php
   require $_SERVER["DOCUMENT_ROOT"].'/inc/topo.php';
   require $_SERVER["DOCUMENT_ROOT"].'/inc/menu.php';
   require $_SERVER["DOCUMENT_ROOT"].'/api/pages/novo-usuario.php';
   requerPermissao('1');
?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
   <!-- Content Header (Page header) -->
   <section class="content-header">
      <h1>
         Novo Usuário
         <small>Usuários</small>
      </h1>
   </section>
   <!-- Main content -->
   <section class="content">
      <div class="row">
         <div class="col-12">
            <div class="box box-solid bg-black">
               <div class="box-header">
                  <h4 class="box-title"><strong class="event-strong">Cadastro de Usuários</strong></h4>
                  <a href="javascript:history.back('-1');" class="btn btn-danger btn-md pull-right"><i class="fa fa-reply"></i> &nbsp; Voltar</a>
               </div>
               <div class="box-content">
                  <div class="box-body wizard-content">
                     <form action="/usuarios/salvar" id="form_new_user" method="POST" class="tab-wizard wizard-circle">
                        <!-- Step 1 -->
                        <h6>Info. Básica</h6>
                        <section>
                           <div class="row">
                              <div class="col-md-6">
                                 <div class="form-group">
                                    <label for="name">Nome:</label>
                                    <input type="text" class="form-control" name="name" id="name">
                                 </div>
                              </div>
                              <div class="col-md-6">
                                 <div class="form-group">
                                    <label for="login">Gerente:</label>
                                    <select class="custom-select form-control" id="manager" name="manager">
                                       <option value="">Sem gerente</option>
                                       <?php
                                          echo '<optgroup label="Gerentes">';
                                          foreach ($managers as $u) {
                                             $selected = '';
                                             if($_SESSION["tipos_usuarios"][$_SESSION["usuario"]["tipo"]]["hierarquia"] <> '1' && $u["id"] <> $_SESSION["usuario"]["id"]){ continue; } elseif($_SESSION["tipos_usuarios"][$_SESSION["usuario"]["tipo"]]["hierarquia"] <> '1'){ $selected = 'selected'; }
                                             echo '<option '.$selected.' value="'.$u["id"].'">'.$u["nome"].'</option>';
                                          }
                                          echo '</optgroup>';
                                          $selected = '';

                                          foreach ($users as $tuid => $v) {
                                             // if($_SESSION["tipos_usuarios"][$_SESSION["usuario"]["tipo"]]["hierarquia"] <> '1'){ continue; }
                                             echo '<optgroup label="'.$_SESSION["tipos_usuarios"][$tuid]["nome"].'">';
                                             foreach ($v as $u) {
                                                $selected = '';
                                                if($_SESSION["tipos_usuarios"][$_SESSION["usuario"]["tipo"]]["hierarquia"] <> '1' && $u["id"] <> $_SESSION["usuario"]["id"]){ continue; } elseif($_SESSION["tipos_usuarios"][$_SESSION["usuario"]["tipo"]]["hierarquia"] <> '1'){ $selected = 'selected'; }
                                                echo '<option '.$selected.' value="'.$u["id"].'">'.$u["nome"].'</option>';
                                             }
                                             echo '</optgroup>';
                                          }
                                       ?>
                                    </select>
                                 </div>
                              </div>
                           </div>
                           <div class="row">
                              <div class="col-md-6">
                                 <div class="form-group">
                                    <label for="pass">Senha:</label>
                                    <input type="password" class="form-control" name="pass" id="pass">
                                 </div>
                              </div>
                              <div class="col-md-6">
                                 <div class="form-group">
                                    <label for="phone">Telefone:</label>
                                    <input type="tel" class="form-control tel" name="phone" id="phone">
                                 </div>
                              </div>
                           </div>
                           <div class="row">
                              <div class="col-md-6">
                                 <div class="form-group">
                                    <label for="user_type">Tipo de usuário:</label>
                                    <select class="custom-select form-control" id="user_type" name="user_type">
                                       <option value="">Selecione</option>
                                       <?php
                                          foreach ($_SESSION["tipos_usuarios"] as $id => $v) {
                                             if($v["hierarquia"] <= $_SESSION["tipos_usuarios"][$_SESSION["usuario"]["tipo"]]["hierarquia"] && $_SESSION["tipos_usuarios"][$_SESSION["usuario"]["tipo"]]["hierarquia"] <> '1'){ continue; }
                                             echo '<option value="'.$id.'">'.$v["singular"].'</option>';
                                          }
                                       ?>
                                    </select>
                                 </div>
                              </div>
                              <div class="col-md-6">
                                 <div class="form-group">
                                    <label for="date1">Status:</label>
                                    <div class="c-inputs-stacked">
                                       <input name="status" type="radio" id="ativo" value="1" class="radio-col-green" checked>
                                       <label for="ativo" class="block">Ativo</label>
                                       <input name="status" type="radio" id="inativo" class="radio-col-red" value="0">
                                       <label for="inativo">Inativo</label>
                                    </div>
                                 </div>
                              </div>
                              <div class="col-md-6" style="display: none;" id="manager_comission">
                                 <div class="form-group">
                                    <label for="comission_manager">Comissão Gerente (do lucro):</label>
                                    <input type="number" class="form-control" name="comission_manager" id="comission_manager" placeholder="Ex: 10">
                                 </div>
                              </div>
                           </div>
                        </section>
                        <!-- Step 2 -->
                        <h6>Limites</h6>
                        <section>
                           <div class="row">
                              <div class="col-md-6">
                                 <div class="form-group">
                                    <label for="diary_limit_1">Limite diário de apostas (1 time):</label>
                                    <input type="text" class="form-control" onkeyup="send(event)" oninput="this.value = SimpleMaskMoney.format(this.value);" name="diary_limit_1" id="diary_limit_1">
                                 </div>
                              </div>
                              <div class="col-md-6">
                                 <div class="form-group">
                                    <label for="diary_limit_2">Limite diário de apostas (2 times):</label>
                                    <input type="text" class="form-control" onkeyup="send(event)" oninput="this.value = SimpleMaskMoney.format(this.value);" name="diary_limit_2" id="diary_limit_2">
                                 </div>
                              </div>
                              <div class="col-md-6">
                                 <div class="form-group">
                                    <label for="diary_limit_general">Limite diário de apostas (GERAL):</label>
                                    <input type="text" class="form-control" onkeyup="send(event)" oninput="this.value = SimpleMaskMoney.format(this.value);" name="diary_limit_general" id="diary_limit_general">
                                 </div>
                              </div>
                              <div class="col-md-6">
                                 <div class="form-group">
                                    <label for="min_matches">Mínimo de apostas por bilhete:</label>
                                    <select class="custom-select form-control" id="min_matches" name="min_matches">
                                       <option value="1">1</option>
                                       <option value="2">2</option>
                                       <option value="3">3</option>
                                       <option value="4">4</option>
                                       <option value="5">5</option>
                                       <option value="6">6</option>
                                       <option value="7">7</option>
                                       <option value="8">8</option>
                                    </select>
                                 </div>
                              </div>
                              <div class="col-md-6">
                                 <div class="form-group">
                                    <label for="min_price">Valor mínimo do bilhete:</label>
                                    <input type="text" class="form-control" onkeyup="send(event)" oninput="this.value = SimpleMaskMoney.format(this.value);" name="min_price" id="min_price">
                                 </div>
                              </div>
                              <div class="col-md-6">
                                 <div class="form-group">
                                    <label for="max_price">Valor máximo do bilhete:</label>
                                    <input type="text" class="form-control" onkeyup="send(event)" oninput="this.value = SimpleMaskMoney.format(this.value);" name="max_price" id="max_price">
                                 </div>
                              </div>
                              <div class="col-md-6">
                                 <div class="form-group">
                                    <label for="credit">Crédito inicial:</label>
                                    <input type="text" class="form-control" onkeyup="send(event)" oninput="this.value = SimpleMaskMoney.format(this.value);" name="credit" id="credit">
                                 </div>
                              </div>
                              <div class="col-md-6">
                                 <div class="form-group">
                                    <label for="bet_live">Apostas ao vivo?</label>
                                    <select class="custom-select form-control" id="bet_live" name="bet_live">
                                       <option value="1">Sim</option>
                                       <option value="0">Não</option>
                                    </select>
                                 </div>
                              </div>
                           </div>
                        </section>
                        <!-- Step 3 -->
                        <h6>Comissões</h6>
                        <section>
                           <div class="row" id="comissions_section">
                              <div class="col-md-6">
                                 <div class="form-group">
                                    <label for="comission_rate">Grade de comissões</label>
                                    <select class="custom-select form-control" id="comission_rate" name="comission_rate">
                                       <option value="0">Selecione</option>
                                       <?php
                                          while($g = $sql->fetch_assoc()){
                                             echo '<option value="'.$g["grade_id"].'">'.utf8_encode($g["grade_nome"]).'</option>';
                                          }
                                       ?>
                                    </select>
                                 </div>
                              </div>
                              <div class="col-md-6">
                                 <div class="form-group">
                                    <label for="new_comission_name">Ou crie uma nova grade</label>
                                    <input type="text" class="form-control" name="new_comission_name" id="new_comission_name" placeholder="Nome da grade"><br />
                                    <textarea name="new_comission_rules" id="new_comission_rules" rows="4" class="form-control"></textarea>
                                 </div>
                              </div>
                              <div class="col-md-12">
                                 <blockquote>
                                    <h4>Como criar uma grade</h4>
                                    <p style="font-size: 16px;">Após inserir o nome da grade, informe quantos jogos serão necessários para cada comissão, <b>separando por ENTER (uma regra a cada linha)</b>. Ex: 1:5 - Significa que para 1 jogo, paga-se 5%. 3:10 - Para 3 jogos, paga-se 10%. Se a aposta tiver mais jogos que o especificado na grade, paga-se pela maior comissão da grade.</p>

                                    <h4>Exemplo: Grade 5, 7 e 10</h4>
                                    <div style="padding: 5px; background: #FFF; font-size: 18px; border: 1px solid #AAA; max-width: 300px;">
                                       1:5<br />
                                       2:7<br />
                                       3:10
                                    </div>
                                    <p>Neste exemplo, se houverem 4 apostas ou mais em um bilhete, a comissão será de 10%.</p>
                                    <br />

                                    <h4>Exemplo: Grade 5 e 10</h4>
                                    <div style="padding: 5px; background: #FFF; font-size: 18px; border: 1px solid #AAA; max-width: 300px;">
                                       1:5<br />
                                       2:10
                                    </div>
                                    <p>Neste exemplo, se houverem 3 apostas ou mais em um bilhete, a comissão será de 10%.</p>
                                 </blockquote>
                              </div>
                           </div>
                        </section>
                     </form>
                  </div>
                  <!-- /.box-body -->
               </div>
            </div>
         </div>
      </div>
      <!-- /.row -->
   </section>
   <!-- /.content -->
</div>
<!-- /.content-wrapper -->
<!-- ./wrapper -->
<?php require $_SERVER["DOCUMENT_ROOT"].'/inc/rodape.php'; ?>

<script src="/js/moneymask.js"></script>
<script src="/js/jquery.mask.js"></script>
<script>
    let input = document.getElementsByTagName('input')[0];

    // configuration
    SimpleMaskMoney.args = {
        prefix: '',
        suffix: '',
        fixed: false,
        fractionDigits: 2,
        decimalSeparator: ',',
        thousandsSeparator: '.',
        autoCompleteDecimal: false
    };

    // Your send method
    send = (e) => {
        if (e.key !== "Enter") return;
        // This method return value of your input in format number to save in your database
        SimpleMaskMoney.formatToNumber(input.value);
    }
   $(function(){
      var SPMaskBehavior = function (val) {
        return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009';
      },
      spOptions = {
        onKeyPress: function(val, e, field, options) {
            field.mask(SPMaskBehavior.apply({}, arguments), options);
          }
      };

      $(document).ready(function(){
         $('#user_type').change(function(){
            var type = $(this).val();
            if(type == '4'){
               $('#manager_comission').fadeToggle();
               $('#comissions_section').hide();
            } else {
               $('#manager_comission').hide();
               $('#comissions_section').show();
            }
         });
      });

      $('.tel').mask(SPMaskBehavior, spOptions);;
      $('#form_new_user').submit(function(){
         $('[href="#finish"]').html('<i class="fa fa-spinner fa-spin"></i> &nbsp; Salvando...');
         var dados = $( this ).serialize();
         var f = $(this);

         $.ajax({
            type: f.attr('method'),
            url: f.attr('action'),
            data: dados,
            success: function( data )
            {
               var info = $.parseJSON(data);
               if(info.error != undefined){ alert(info.error); $('[href="#finish"]').html('Salvar'); }
               else if(info.success != undefined){
                  // alert(info.success);
                  $('[href="#finish"]').css('background', '#1b890e').html('<i class="fa fa-check"></i> &nbsp; Cadastrado');

                  $.toast({
                     heading: 'Pronto!',
                     text: 'O usuário foi cadastrado com sucesso.',
                     position: 'top-right',
                     loaderBg: '#FFF',
                     icon: 'success',
                     hideAfter: 3500,
                     stack: 6
                  });

                  setTimeout(function(){ location.href = "/usuarios/"+info.slug; }, 2000);
               }
            }
         });

         return false;
      });
   });
</script>

<!-- steps  -->
<script src="/assets/vendor_components/jquery-steps-master/build/jquery.steps.js"></script>
<!-- validate  -->
<script src="/assets/vendor_components/jquery-validation-1.17.0/dist/jquery.validate.min.js"></script>
<!-- wizard  -->
<script src="/js/pages/steps.js"></script>