<?php
   require $_SERVER["DOCUMENT_ROOT"].'/inc/topo.php';
   require $_SERVER["DOCUMENT_ROOT"].'/inc/menu.php';
   require $_SERVER["DOCUMENT_ROOT"].'/api/pages/apuracao.php';
   requerPermissao('22:23');
?>
<link rel="stylesheet" href="/assets/vendor_plugins/iCheck/all.css">
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
   <!-- Content Header (Page header) -->
   <section class="content-header">
      <h1>
         Relatório
         <small>Financeiro</small>
      </h1>
      <a href="javascript:history.back('-1');" class="btn btn-danger btn-md pull-right" style="margin-top: -35px;"><i class="fa fa-reply"></i> &nbsp; Voltar</a>
   </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">Relatório</strong></h4>
               </div>
               <div class="box-content">
                  <div class="box-body">
                  <form action="/api/getBalanceByApuration" id="formApuracao">
                      <div style="max-width: 800px; margin: 0px auto;">
                        <center>
                          Situação:<br />
                          <label class="btn btn-info"><input class="chk-col-green checkbox-input" type="checkbox" name="status[]" value="1" checked> &nbsp; Aguardando Resultado </label>
                          <label class="btn btn-warning"><input class="chk-col-green checkbox-input" type="checkbox" name="status[]" value="5" checked> &nbsp; Process. Parcial </label>
                          <label class="btn btn-danger"><input class="chk-col-green checkbox-input" type="checkbox" name="status[]" value="3" checked> &nbsp; Perdeu </label>
                          <label class="btn btn-success"><input class="chk-col-green checkbox-input" type="checkbox" name="status[]" value="2" checked> &nbsp; Ganhou </label>
                          <label class="btn bg-dark" style="background: #84100d;"><input class="chk-col-green checkbox-input" type="checkbox" name="status[]" value="4"> &nbsp; Cancelados </label>
                        </center>
                      </div>
                      <div class="row" style="max-width: 800px; margin: 0px auto; text-align: center;">
                        <div class="col-sm-6">
                          <input  class="form-control datepicker" name="date" value="<?php echo date('d/m/Y'); ?>" placeholder="Data de Início" id="data" /><br />
                        </div>
                        <div class="col-sm-6">
                          <input  class="form-control datepicker" name="enddate" value="<?php echo date('d/m/Y'); ?>" placeholder="Data de Fim" id="data" /><br />
                        </div>
                      </div>
                      <div class="row" style="max-width: 800px; margin: 0px auto;">
                        <?php $i = 2; foreach ($api['users'] as $k => $v) { ?>
                        <div class="col-sm-4">
                          <select class="selLevel form-control" name="level<?php echo $i; ?>" id="">
                            <option value="0"><?php echo $k; ?></option>
                            <?php foreach ($v as $t) { echo '<option value="'.$t['id'].'">'.$t['name'].'</option>'; } ?>
                          </select><br />
                        </div>
                        <?php $i++; } ?>
                      </div>
                      <div class="row" style="max-width: 800px; margin: 0px auto;">
                        <div class="col-12">Filtros:<br /></div>
                        <div class="col-sm-6">
                          <select class="selLevel form-control" name="sort" id="">
                            <option value="0">Ordenar por</option>
                            <option value="dateasc">Data (Crescente)</option>
                            <option value="datedesc">Data (Decrescente)</option>
                            <option value="priceasc">Valor (Crescente)</option>
                            <option value="pricedesc">Valor (Decrescente)</option>
                            <option value="returnasc">Prêmio (Crescente)</option>
                            <option value="returndesc">Prêmio (Decrescente)</option>
                          </select><br />
                        </div>
                        <div class="col-sm-6">
                          <input class="form-control" name="client_name" placeholder="Nome do cliente" id="" /><br />
                        </div>
                        <div class="col-sm-6">
                          <select class="form-control" name="type" id="">
                            <option value="general" selected>Resumo Geral</option>
                            <option value="user">Por usuário</option>
                            <option value="manager">Por supervisor</option>
                            <option value="manager2">Por gerente</option>
                            <option value="detailed">Resumo Detalhado</option>
                          </select><br />
                        </div>
                        <div class="col-sm-6">
                          <label class="btn btn-default btn-md btn-block"><input class="chk-col-green checkbox-input" type="checkbox" name="show_bets" value="1" > &nbsp; Detalhar apostas </label>
                        </div>
                      </div>
                        <br /><center><button type="submit" class="btn btn-lg btn-info" id="btnFormSubmit"><i class="fa fa-file-text-o"></i> &nbsp; Gerar Relatório</button> &nbsp; <a style="margin: 0 auto; display: none;" id="generatePDF" class="btn btn-warning btn-lg"><i class="fa fa-print"></i> &nbsp; Gerar PDF</a></center>
                    </form>

                    <br /><br />
                    <div class="table-responsive" id="printableData">
                      <table class="table table-bordered table-striped" id="tableResult"></table>
                    </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
      <!-- /.row -->
   </section>
   <!-- /.content -->
</div>
<!-- /.content-wrapper -->
<!-- ./wrapper -->
<?php require $_SERVER["DOCUMENT_ROOT"].'/inc/rodape.php'; ?>
<!-- end - This is for export functionality only -->
<!-- Unique_Admin for Data Table -->
<script src="/plugins/pickadate/lib/picker.js"></script>
<script src="/plugins/pickadate/lib/picker.date.js"></script>
<link href="/plugins/pickadate/lib/themes/default.css" rel="stylesheet" />
<link href="/plugins/pickadate/lib/themes/default.date.css" rel="stylesheet" />
<script>
    $(function(){
      $(document).ready(function(){

        $('.datepicker').pickadate({
          // Strings and translations
          monthsFull: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
          monthsShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
          weekdaysFull: ['Domingo', 'Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado'],
          weekdaysShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'],
          showMonthsShort: undefined,
          showWeekdaysFull: undefined,

          // Buttons
          today: 'Hoje',
          clear: 'Limpar',
          close: 'Fechar',

          // Accessibility labels
          labelMonthNext: 'Prox Mês',
          labelMonthPrev: 'Mês Anterior',
          labelMonthSelect: 'Selecione um mês',
          labelYearSelect: 'Selecione um ano',

          // Formats
          format: 'dd/mm/yyyy',
        });

        $('.selLevel').change(function(){
          var select = $(this).attr('name');

          $('.selLevel').each(function(e){
            if($(this).attr('name') != select){
              $(this).val('0');
            }
          });
        });

          $('#generatePDF').click(function(){
            var lv2 = $('[name="level2"]').children("option:selected").text();
            var lv3 = $('[name="level3"]').children("option:selected").text();
            var lv4 = $('[name="level4"]').children("option:selected").text();

            var titulo = '';
            if(lv2 != 'Gerentes'){ titulo = lv2; }
            if(lv3 != 'Supervisores'){ titulo = lv3; }
            if(lv4 != 'Vendedores'){ titulo = lv4; }
            titulo = titulo+ ' | '+$('[name="date"]').val()+' a '+$('[name="enddate"]').val();

            $('#printableData table').attr('cellspacing', '0');
            var data = $('#printableData').html();
            data = '<style> * { font-family: Arial; } th { padding: 7px; border: 1px solid #000; background: #555; color: #FFF; } table { width: 100%; border: 1px solid #000; } td { padding: 7px; border: 1px solid #000; } </style><div style="text-align: center; padding: 15px 0;"><h2>'+titulo+'</h2></div>'+data+"<script>print();<\/script>";
            var w = window.open('about:blank');
            w.document.open();
            w.document.write(data);
            w.document.close();
          });

          $('#formApuracao').submit(function(){
            var dados = $( this ).serialize();
            $('#tableResult').html('');
            var f = $(this);
            $('#btnFormSubmit').html('<i class="fa fa-spinner fa-spin"></i> &nbsp; Processando');
            $.ajax({
              type: "POST",
              url: f.attr('action'),
              data: dados,
              success: function(data){
                 var info = $.parseJSON(data);
                console.log(data);
                 if(info.error != undefined){
                    alert(info.error);
                    $('#btnFormSubmit').html('<i class="fa fa-file-text-o"></i> &nbsp; Gerar Relatório');
                 }
                 else if(info.success != undefined){
                    // location.href = "/ver-apuracao";
                    var el = '';
                    for (var tr in info.table) {
                      el = el + '<tr>';
                      var td2 = info.table[tr];
                      for (var td in td2){
                        el = el + '<'+td2[td]['type']+' colspan="'+td2[td]['colspan']+'" align="'+td2[td]['align']+'" class="'+td2[td]['class']+'">'+td2[td]['html']+'</'+td2[td]['type']+'>';
                      }
                      el = el + '</tr>';
                    }
                    $('#tableResult').append(el);
                    $('#btnFormSubmit').html('<i class="fa fa-file-text-o"></i> &nbsp; Gerar Relatório');
                    cancel();
                    viewBilhete();
                    $('#generatePDF').show();
                 }
              }
            });

            return false;
          });

      });
    });

    function cancel(){

      $('[id="cancelBtn"]').click(function(){
          var code = $(this).attr('data-code');
          var btn = $(this);
          $.get('/api/cancellCoupon?code='+code, function(d){
              var info = $.parseJSON(d);
              if(info.error != undefined){
                alert(info.error);
              }
              else if(info.success != undefined){
                $('[id="item'+code+'"]').attr('class', 'badge badge-danger').html('Cancelado');
              }
          });
      });

    }

    function viewBilhete(){
      $('[id="viewCoupon"]').click(function(){
          var code = $(this).attr('data-code');
          var btn = $(this);
          $('#verBilhete').modal('show');

          $.get('/resumo/'+code+'?print=no', function(e){
            $('#couponViewer').html(e);
          });

          return false;
      });
    }
</script>