<?php
   require $_SERVER["DOCUMENT_ROOT"].'/inc/topo.php';
   require $_SERVER["DOCUMENT_ROOT"].'/inc/menu.php';
   requerPermissao('20'); // Processamento de PINs
?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
   <!-- Content Header (Page header) -->
   <section class="content-header">
      <h1>
         Processar PIN
         <small>Bilhetes</small>
      </h1>
   </section>
   <!-- Main content -->
   <section class="content">
      <div class="row">
         <div class="col-lg-4 col-md-4 col-12">
            <div class="box box-solid bg-black">
               <div class="box-header">
                  <h4 class="box-title"><strong class="event-strong">Processar um PIN</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">
                     <form id="pinForm" method="POST" action="/api/getPin">
                        <label for="" class="block">
                        Informe o código:
                        <input type="text" class="form-control" name="code" placeholder="Código PIN..." value="PIN" />
                        </label>
                        <div class="row">
                           <div class="col-12">
                              <button class="btn btn-success btn-md pull-right"><i class="fa fa-search"></i> &nbsp; Pesquisar PIN</button>
                           </div>
                        </div>
                     </form>
                  </div>
               </div>
            </div>
         </div>
         <div class="col-lg-8 col-md-8 col-12">
            <form id="finishBetForm" action="/api/finishBet" method="POST">
               <div class="box box-solid bg-warning">
                  <div class="box-header">
                     <h4 class="box-title"><strong class="event-strong">Seu bilhete</strong></h4>
                     <button type="submit" class="btn bg-success btn-md pull-right" id="finishBet"><i class="fa fa-check"></i> &nbsp; Finalizar</button>
                  </div>
                  <div class="box-content">
                     <div class="box-body loadingSpinner revisar_bet" id="loadingData" style="display: none;">
                        <center>
                           <blockquote>Informações do bilhete</blockquote>
                        </center>
                        <div class="media-list media-list-hover media-list-divided">
                           <div class="media">
                              <div class="media-body">
                                 <p>
                                    <a class="hover-primary" href="#"><strong>Nome do cliente</strong></a>
                                    <time class="float-right"><input type="text" name="cliente" id="clientNameReview" class="form-control" placeholder="Nome do cliente" /></time>
                                 </p>
                              </div>
                           </div>
                           <div class="media">
                              <div class="media-body">
                                 <p>
                                    <a class="hover-primary" href="#"><strong>Valor da aposta</strong></a>
                                    <time class="float-right"><input type="text" name="valor" required="required" onkeyup="send(event)" id="priceBetReview" oninput="this.value = SimpleMaskMoney.format(this.value); calcReturn(this.value);" class="form-control" placeholder="Ex: 10,00" /></time>
                                 </p>
                              </div>
                           </div>
                           <div class="media">
                              <div class="media-body">
                                 <p>
                                    <a class="hover-primary" href="#"><strong>Possível Retorno</strong></a>
                                    <time class="float-right"><input type="text" class="form-control" disabled="" id="returnBet" placeholder="152,00" /></time>
                                 </p>
                              </div>
                           </div>
                        </div>
                        <center>
                           <blockquote>Jogos adicionados</blockquote>
                        </center>
                        <div class="media-list media-list-hover media-list-divided" id="listItems">
                        </div>
                        <p class="text-red help-block"><br />* Cotações em vermelho significam que foram alteradas. Consequentemente, o valor do retorno também foi alterado.</p>
                     </div>
                     <div class="box-body loadingSpinner" id="error">

                     </div>

                     <div class="cupom_concluido">
                        <div class="alert alert-success alert-dismissible">
                           <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                           <h4><i class="icon fa fa-check"></i> Pronto!</h4>
                           <?php
                              if(isset($_SESSION["usuario"])){
                                 echo 'Seu bilhete foi finalizado com sucesso.';
                              } else {
                                 echo 'Seu PIN foi gerado com sucesso. Agora, vá até um vendedor credenciado para finalizar o bilhete.';
                              }
                           ?>
                        </div>

                        <center><blockquote>Código</blockquote></center>
                        <div class="media-list media-list-hover media-list-divided">
                           <center>
                              <h1><b id="codigo_bilhete"></b></h1><br />
                           </center>
                        </div>

                        <center><blockquote>O que fazer agora?</blockquote></center>
                        <div class="media-list media-list-hover media-list-divided">
                           <center>
                              <div class="btn-group">

                                 <?php
                                    if(isset($_SESSION["usuario"])){
                                       echo '<a href="/imprimir" target="framePrint" class="btn mobile-btn-block btn-lg btn-info" id="printButtonFinishBet"><i class="fa fa-print"></i> &nbsp; Imprimir</a>';
                                    }
                                 ?>

                                 <a href="/bilhetes/processar-pin" class="btn mobile-btn-block btn-lg btn-success" data-dismiss="modal"><i class="fa fa-check"></i> &nbsp; Concluir</a>
                              </div>
                           </center>

                           <iframe src="" id="framePrint" name="framePrint" frameborder="0" height="1"></iframe>
                        </div>
                     </div>
                  </div>
               </div>
            </form>
         </div>
      </div>
      <!-- /.row -->
   </section>
   <!-- /.content -->
</div>
<!-- /.content-wrapper -->
<!-- ./wrapper -->
<?php require $_SERVER["DOCUMENT_ROOT"].'/inc/rodape.php'; ?>
<!-- DataTables -->
<script src="/assets/vendor_components/jquery/dist/jquery.min.js"></script>
<!-- popper -->
<script src="/assets/vendor_components/popper/dist/popper.min.js"></script>
<!-- DataTables -->
<script src="/assets/vendor_components/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="/assets/vendor_components/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>
<script src="/assets/vendor_plugins/DataTables-1.10.15/media/js/jquery.dataTables.min.js"></script>
<!-- start - This is for export functionality only -->
<script src="/assets/vendor_plugins/DataTables-1.10.15/extensions/Buttons/js/dataTables.buttons.min.js"></script>
<script src="/assets/vendor_plugins/DataTables-1.10.15/extensions/Buttons/js/buttons.flash.min.js"></script>
<script src="/assets/vendor_plugins/DataTables-1.10.15/ex-js/jszip.min.js"></script>
<script src="/assets/vendor_plugins/DataTables-1.10.15/ex-js/pdfmake.min.js"></script>
<script src="/assets/vendor_plugins/DataTables-1.10.15/ex-js/vfs_fonts.js"></script>
<!-- script src="/assets/vendor_plugins/DataTables-1.10.15/extensions/Buttons/js/buttons.html5.min.js"></script -->
<!-- script src="/assets/vendor_plugins/DataTables-1.10.15/extensions/Buttons/js/buttons.print.min.js"></script -->
<!-- end - This is for export functionality only -->
<!-- Unique_Admin for Data Table -->
<script src="/js/pages/data-table.js"></script>

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

    // configuration
    SimpleMaskMoney.args = {
        prefix: '',
        suffix: '',
        fixed: true,
        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(){
      $(document).ready(function(){
         var spinner = '<div class="loadermodal"><center><img class="floader" src="/loaders/rings.svg" /> Recuperando PIN...</center></div>';
         $('#pinForm').submit(function(e){
            $('#msg').remove();
            $('#loadingData, #error').hide();
            $('.loadingSpinner').append(spinner);
            var dados = $( this ).serialize();
            var form = $(this);

            $.ajax({
               type: "POST",
               url: form.attr('action'),
               data: dados,
               success: function( d )
               {
                  JSON.parse(d);
                  var d = $.parseJSON(d);
                  if(d.error != undefined){
                     $('#error').html('<div class="callout callout-danger" id="msg"><p>'+d.error+'</p> </div>').show();
                  } else {
                     $('#clientNameReview').val(d.client);
                     $('#priceBetReview').val(d.price);
                     $('#returnBet').val(d.return);

                     $('#listItems').html('');
                     $.each(d.bets, function(i, item){
                        var changedClass = '';
                        var old_odd = '';
                        if(item.old_odd != undefined){ old_odd = item.old_odd+' > '; }
                        if(item.changed == '1'){ changedClass = 'text-red'; }
                        $('#listItems').append('<div class="media"> <div class="media-body"> <p> <a class="hover-primary" href="#"><strong class="'+changedClass+'">'+item.match_name+'</strong></a> <time class="float-right"><b>'+old_odd+'<span class="'+changedClass+'">'+item.odd+'</span></b></time> </p> <p class="'+changedClass+'">'+item.market+' - <b>'+item.option+'</b></p> </div> </div>');
                     });

                     $('#loadingData').show();
                  }
                  $('.loadermodal').remove();
               }
            });
            e.preventDefault();
         });

         $('[id="finishBet"]').click(function(){
           var btn = $(this);
           if($('#priceBetReview').val() == ''){ alert('Informe o valor do bilhete.'); return false; }

           btn.html('<i class="fa fa-spinner fa-spin" style="margin-right: 5px;"></i> Finalizando').removeClass('bg-success').addClass('btn-info');
         });

         $('#finishBetForm').submit(function(e){
           var dados = $( this ).serialize();
           var f = $(this);

           $.ajax({
             type: "POST",
             url: f.attr('action'),
             data: dados,
             success: function( d )
             {
               try {
                   JSON.parse(d);
                   var dd = $.parseJSON(d);
                   if(dd.codigo != 'undefined'){
                     $('#codigo_bilhete').html(dd.codigo);

                     // RESET VARS
                     $('.creditInformation').html('R$'+dd.credito);
                     $('.cupom_concluido, .revisar_bet, #finishBet, #footerReviewBet').toggle();
                     $('#printButtonFinishBet').attr('href', '/imprimir/'+dd.codigo);
                     $('#couponContent').html('');
                     $('#priceBet, #clientName').val('');
                     $('#totalReturns').html('R$0,00');
                     $('#totalOdds, #coupon-qtd').html('0');
                     $('[id="sendBet"], [id="btnOpenMoreOdds"]').removeClass('bg-success');
                   }
               } catch (e) {
                   alert(d);
               }

               $('[id="finishBet"]').html('<i class="fa fa-check" style="margin-right: 5px;"></i> Finalizar').removeClass('btn-info').addClass('bg-success');
             }
           });

           return false;
           e.preventDefault();
         });
      });
   });
</script>