<?php include('fncr-geral/configuracao_geral.php');
$pagina = "financeiro";
$blq_pag = "fingeral";
include('fncr-geral/permissoes_restricao.php');

// Funções do Financeiro
$config_fingeral = array( "tipo"=>"financeiro" );
require_once('scripts/financeiro/functions_fingeral.php');

$id_rep = isset($_GET['idr']) ? $_GET['idr'] : null;


// ********************** FILTROS ***********************
if($id_rep){

  $filtro_ligado = 0;

  $data_inicio = date("Y-m-01");
  $data_fim = date("Y-m-t");
  $competencia = false;

  if(isset($_POST['filtro']) && $_POST['filtro'] = "realizar"){
    $filtro_ligado = 1;
    $data_inicio = (isset($_POST['filtro_data_inicio']) && $_POST['filtro_data_inicio']>0) ? databd($_POST['filtro_data_inicio']) : $data_inicio;
    $data_fim = (isset($_POST['filtro_data_fim']) && $_POST['filtro_data_fim']>0) ? databd($_POST['filtro_data_fim']) : $data_fim;

    $competencia = (isset($_POST['filtro_competencia']) && $_POST['filtro_competencia']>0) ? $_POST['filtro_competencia'] : false;
    if($competencia){
      $data_competencia = explode('-',$competencia);
      $data_competencia[0] = substr($data_competencia[0], -2);
    }
  }



  /*
  if(isset($_POST['filtro']) && $_POST['filtro'] = "realizar") {
    $filtro_data_inicio = isset($_POST['filtro_data_inicio']) && $_POST['filtro_data_inicio']>0 ? databd($_POST['filtro_data_inicio']):$data_inicio;
    $filtro_data_fim = isset($_POST['filtro_data_fim']) && $_POST['filtro_data_fim']>0 ? databd($_POST['filtro_data_fim']):$data_fim;
    $filtro_competencia = isset($_POST['filtro_competencia'])&&$_POST['filtro_competencia']>0?$_POST['filtro_competencia']:'';
  }else{
    $filtro_data_inicio = isset($_POST['json_filtro_data_inicio'])?$_POST['json_filtro_data_inicio']:$data_inicio;
    $filtro_data_fim = isset($_POST['json_filtro_data_fim'])?$_POST['json_filtro_data_fim']:$data_fim;
    $filtro_competencia = isset($_POST['json_filtro_competencia'])?$_POST['json_filtro_competencia']:'';
  }
  */

  // Libera Filtro
  //if(($filtro_data_inicio>0 && $filtro_data_fim>0) or ($filtro_competencia>0)){ $filtro_ligado = 1; }



  // ************************************** GERAL - SELECTS **************************************

  $where_competencia = $competencia ? ' AND ex.periodo_ano = '.$data_competencia[0].' AND ex.periodo_mes = '.$data_competencia[1] : '';

  // SALDOS
  $sql = $bd->getConexao()->prepare('
  SELECT
    SUM(ifnull(valor_setup,0)) as valor_setup,
    SUM(ifnull(valor_mensalidade,0)) as valor_mensalidade,
    SUM(ifnull(valor,0)) as valor
  FROM representantes_extrato ex
  WHERE ex.id_clube_painel = :id_clube_painel AND ex.data_hora < :data_ini '.$where_competencia);
  $sql->bindValue(':id_clube_painel', $id_rep, PDO::PARAM_STR);
  $sql->bindValue(':data_ini', $data_inicio.' 00:00:00', PDO::PARAM_STR);
  if($sql->execute()){$saldos_anteriores = $sql->fetch(PDO::FETCH_ASSOC);}

  $sql = $bd->getConexao()->prepare('
  SELECT
    SUM(ifnull(valor_setup,0)) as valor_setup,
    SUM(ifnull(valor_mensalidade,0)) as valor_mensalidade,
    SUM(ifnull(valor,0)) as valor,
    SUM(CASE WHEN valor>0 THEN ifnull(valor,0) ELSE 0 END) as entrada,
    SUM(CASE WHEN valor<0 THEN ifnull(valor,0) ELSE 0 END) as saida
  FROM representantes_extrato ex
  WHERE ex.id_clube_painel = :id_clube_painel AND ex.data_hora BETWEEN (:data_ini) AND (:data_fim) '.$where_competencia);
  $sql->bindValue(':id_clube_painel', $id_rep, PDO::PARAM_STR);
  $sql->bindValue(':data_ini', $data_inicio.' 00:00:00', PDO::PARAM_STR);
  $sql->bindValue(':data_fim', $data_fim.' 23:59:59', PDO::PARAM_STR);
  if($sql->execute()){$saldos_periodo = $sql->fetch(PDO::FETCH_ASSOC);}

  $sql = $bd->getConexao()->prepare('
  SELECT
    SUM(ifnull(valor_setup,0)) as valor_setup,
    SUM(ifnull(valor_mensalidade,0)) as valor_mensalidade,
    SUM(ifnull(valor,0)) as valor
  FROM representantes_extrato ex
  WHERE ex.id_clube_painel = :id_clube_painel AND ex.data_hora > :data_fim '.$where_competencia);
  $sql->bindValue(':id_clube_painel', $id_rep, PDO::PARAM_STR);
  $sql->bindValue(':data_fim', $data_fim.' 23:59:59', PDO::PARAM_STR);
  if($sql->execute()){$saldos_futuro = $sql->fetch(PDO::FETCH_ASSOC);}


  // REGISTROS
  $sql = $bd->getConexao()->prepare('
  SELECT
    ex.*,
    DATE_FORMAT(ex.data_hora,"%d/%m/%Y - %H:%i") AS data_hora,
    c.nome as clube
  FROM representantes_extrato ex
    LEFT JOIN clubes c ON c.id = ex.id_clube
  WHERE ex.id_clube_painel = :id_clube_painel AND ex.data_hora BETWEEN (:data_ini) AND (:data_fim) '.$where_competencia.'
  ORDER BY ex.data_hora');
  $sql->bindValue(':id_clube_painel', $id_rep, PDO::PARAM_STR);
  $sql->bindValue(':data_ini', $data_inicio.' 00:00:00', PDO::PARAM_STR);
  $sql->bindValue(':data_fim', $data_fim.' 23:59:59', PDO::PARAM_STR);
  if($sql->execute()){$registros = $sql->fetchall(PDO::FETCH_ASSOC);}

}


// ********************** SELECTS ***********************

// Paineis de Representantes
$sql = $bd->getConexao()->prepare('
SELECT 
  c.id,
  c.nome as painel,
  r.nome as representante
FROM clubes c
  LEFT JOIN clientes r ON r.id = c.id_representante
WHERE c.id_representante >0 AND c.painel_representante = 1
ORDER BY c.nome');
if( $sql->execute() ) { $rep_paineis = $sql->fetchall(PDO::FETCH_ASSOC);}

$rep_paineis = arrayIndice($rep_paineis, 'id');

if($id_rep){
  $representante = $rep_paineis[$id_rep];
}

?>

<!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>

  <style>
    .linha_destaque td{
      background-color: #dadada !important;
    }
  </style>
  <script type="text/javascript">

    $(document).ready(function() {
      <?php if($id_rep){ ?>
        // Modal Informações do Lançamento
        $("#modal_inf_lancamento").on('show.bs.modal', function(event){
          var button = $(event.relatedTarget);  // Button that triggered the modal
          var id_lancamento = button.data('id_lancamento');
          var id_conta = button.data('id_conta');
          var link = 'scripts/financeiro/modals.php?idc='+id_conta+'&inf_lancamento='+id_lancamento;
          $(this).find('.modal-body').load(link)
        });

        $("select.filtro_select").select2({
          placeholder: "Selecione",
          allowClear:true
        }).on("change", function(e) {
          var display;
          if(e.val==""){display='none'}else{display=''}
          exibeCheck($(this).parent().parent().find("i.fa-check"), display)
        })

        <?php
        if($filtro_ligado==1){
          if($data_inicio>0 && $data_fim>0){
            echo '$("select[name=\'filtro_data_inicio[]\']").select2("val", '.$data_inicio.');';
            echo 'var json_filtro_data_inicio = \''.$data_inicio.'\';';
            echo '$("select[name=\'filtro_data_fim[]\']").select2("val", '.$data_fim.');';
            echo 'var json_filtro_data_fim = \''.$data_fim.'\';';
          }
          ?>
          $("form").submit(function(event) {
            <?php if($data_inicio>0 && $data_fim>0){ ?>
            $('<input />').attr('type', 'hidden').attr('name', "json_filtro_data_inicio").attr('value', json_filtro_data_inicio).appendTo(this);
            $('<input />').attr('type', 'hidden').attr('name', "json_filtro_data_fim").attr('value', json_filtro_data_fim).appendTo(this);
            <?php } ?>
            <?php if($filtro_competencia>0){ ?>
            $('<input />').attr('type', 'hidden').attr('name', "json_filtro_competencia").attr('value', json_filtro_pgto_inicio).appendTo(this);
            <?php } ?>
            this.submit();
          });
        <?php } ?>
      <?php } ?>

      <?php if(isset($_POST['fingeral']) && $_POST['fingeral'] == 'cadastrar_lanc'){ ?>
        $(document).scrollTop($(document).height());
      <?php } ?>
    });

    // Limpar Seleção dos Filtros
    function limparFiltro(obj){
      var campo = $(obj).data('filtro_campo')
      $("select[name='"+campo+"[]']").select2("val", "")
      exibeCheck($("select[name='"+campo+"[]']").parent().parent().find("i.fa-check"), 'none')
    }

    function selectAll(obj){
      var campo = $(obj).data('filtro_campo')
      $("select[name='"+campo+"[]'] > option").prop("selected","selected");
      $("select[name='"+campo+"[]']").trigger("change");
      exibeCheck($("select[name='"+campo+"[]']").parent().parent().find("i.fa-check"), '')
    }

    function exibeCheck(obj, display){
      obj.css('display', display);
    }

    // Fiiltro de Mesa
    function altConta(){
      var link = window.location.href;
      var idRep = $('#select_id_rep').val();
      link = link.replace("?idr=<?php echo isset($id_rep) ? $id_rep : ''?>", "");
      link = link+"?idr="+idRep;
      window.location.replace(link);
    }

    $(window).scroll(function(){
      var altura = $(document).scrollTop();

      var margin = altura - 113
      if(altura >= 113){ $('#coluna_infs').css('margin-top', margin) }else {
        $('#coluna_infs').css('margin-top', 0) }
    });


  </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">Representante (<?php echo $id_rep ? $representante['painel'] : ''?>)</h3>
</div>

<section id="content" class="content-sidebar bg-white">
  <section class="main">
    <div class="row" style="padding: 15px">
      <div class="col-app-2">
        <div id="coluna_infs" class="col-lg-12" style="padding-right: 0">

          <section class="panel" style=" margin: 0 0 10px 0">
            <header class="panel-heading" style="padding: 5px 5px 4px 10px">
              <div class="pull-left" style="margin-top: 5px">Representante</div>
              <div class="pull-right">
                <button type="button" onclick="altConta()" class="btn btn-inverse btn-xs pull-right jsinbloq">Selecionar</button>
              </div>
            </header>
            <div class="panel-body" style="padding: 2px">
              <select id="select_id_rep" class="form-control">
                <?php foreach($rep_paineis as $l){ ?>
                  <option value="<?php echo $l['id']?>" <?php echo $id_rep==$l['id'] ? 'selected' : ''; ?>><?php echo $l['painel'].' ('.$l['representante'].')'?></option>
                <?php } ?>
              </select>
            </div>
          </section>

          <?php if($id_rep){ ?>

            <section class="panel">
              <header class="panel-heading" style="padding: 5px 5px 4px 10px">
                <div class="pull-left" style="margin-top: 5px">Resumos</div>
              </header>

              <table id="table_registros" class="table table-striped b-t text-small" style="font-size: 11px">
                <thead>
                </thead>
                <tbody>
                <tbody>
                <tr>
                  <td>Saldo Anterior</td>
                  <td class="text-right"><?php echo valorStyle($saldos_anteriores['valor'], 'moeda')?></td>
                </tr>
                <tr>
                  <td>
                    <div>Receitas no Período</div>
                    <div>Despesas no Período</div>
                    <div style="border-top: solid 1px #666; font-weight: bold; padding-top: 3px">Saldo no Período</div>
                  </td>
                  <td class="text-right">
                    <div class="text-right"><?php echo valorStyle($saldos_periodo['entrada'], 'moeda')?></div>
                    <div class="text-right"><?php echo valorStyle($saldos_periodo['saida'], 'moeda')?></div>
                    <div class="text-right" style="border-top: solid 1px #666; font-weight: bold; padding-top: 3px"><?php echo valorStyle($saldos_periodo['valor'], 'moeda')?></div>
                  </td>
                </tr>
                <tr>
                  <td>Anterior + Período</td>
                  <td class="text-right"><?php echo valorStyle($saldos_anteriores['valor'] + $saldos_periodo['valor'], 'moeda')?></td>
                </tr>
                <tr>
                  <td>Pós Período</td>
                  <td class="text-right"><?php echo valorStyle($saldos_futuro['valor'], 'moeda')?></td>
                </tr>
                <tr style="font-weight: bold;font-size: 12px">
                  <td>SALDO FINAL</td>
                  <td class="text-right"><?php echo valorStyle(($saldos_anteriores['valor'] + $saldos_periodo['valor'] + $saldos_futuro['valor']), 'moeda')?></td>
                </tr>
                </tbody>
              </table>
            </section>

            <?php if($filtro_ligado==1){ ?>
              <section class="panel" style="padding: 0">
                <div class="filtro_ligado">
                  Filtro Ligado
                  <a href="fingeral_rep.php?idr=<?php echo $id_rep?>" class="pull-right" title="Desligar Filtro" style="margin-top: -1px;margin-right: -5px"><div class="pull-left" style="color: #e1e1e1;font-size: 10px;margin: 3px 5px 0 0">Desligar</div> <i class="fa fa-times fa-1x text-danger"></i></a>
                </div>
              </section>
            <?php } ?>

            <form class="m-b-none" method="post" action="" enctype="multipart/form-data">
              <input type="hidden" name="filtro" value="realizar" />

              <section class="panel painel_filtro">
                <header class="panel-heading" style="padding: 2px">
                  <div class="pull-left" style="margin: 5px 0 0 7px;font-weight: bold">Filtros <?php if($filtro_ligado==1){ echo '<span style="color: #00558d;margin-left: 10px;font-size: 11px">Ligado</span>'; };?></div>
                  <button type="submit" class="btn btn-inverse btn-xs pull-right jsinbloq">Filtrar</button>
                </header>

                <section class="panel filtro_collapse">
                  <header class="panel-heading">
                    <a href="#" class="panel-toggle">
                      <div>
                        Data - Vencimento
                        <i class="fa fa-caret-down fa-lg pull-right"></i>
                        <?php $check_style = ($filtro_ligado && $data_inicio>0 && $data_fim>0) ? '' : 'style="display:none"'; ?>
                        <i class="fa fa-check fa-lg pull-right filtro_check" <?php echo $check_style?>></i>
                      </div>
                    </a>
                  </header>
                  <div class="panel-body collapse">
                    <input class="input-sm form-control datepicker text-center col-app-6" name="filtro_data_inicio" type="text" value="<?php echo echodata($data_inicio)?>" data-date-format="dd/mm/yyyy">
                    <input class="input-sm form-control datepicker text-center col-app-6" name="filtro_data_fim" type="text" value="<?php echo echodata($data_fim)?>" data-date-format="dd/mm/yyyy">
                  </div>
                </section>

                <section class="panel filtro_collapse">
                  <header class="panel-heading">
                    <a href="#" class="panel-toggle">
                      <div>
                        Competência
                        <i class="fa fa-caret-down fa-lg pull-right"></i>
                        <?php $check_style = $competencia ? '' : 'style="display:none"'; ?>
                        <i class="fa fa-check fa-lg pull-right filtro_check" <?php echo $check_style?>></i>
                      </div>
                    </a>
                  </header>
                  <div class="panel-body collapse">
                    <input type="text" class="combodate form-control pull-right" data-format="YY-MM" data-template="MM YYYY" name="filtro_competencia" value="<?php echo $competencia?>" data-parsley-required="true">
                  </div>
                </section>
              </section>

            </form>
          <?php } ?>
        </div>
      </div>
      <?php if($id_rep){ ?>
        <div class="col-app-10">

          <div class="col-lg-12">
            <form class="m-b-none" method="post" action="" enctype="multipart/form-data">
              <input type="hidden" name="fingeral" value="acao_multipla" />

              <section class="panel">
                <header class="panel-heading">
                  <div class="pull-left" style="padding-top: 4px;">
                    Lançamentos
                    <?php echo ' Período: '.echodata($data_inicio).' à '.echodata($data_fim)?>
                  </div>
                </header>
                <table class="table table-striped b-t text-small" style="font-size: 12px">
                  <thead>
                  <tr>
                    <th class="text-center" width="50" style="padding: 6px 0">Comp</th>
                    <th class="text-center" width="120" style="padding: 6px 0">Data</th>
                    <th width="150">Tipo</th>
                    <th>Clube</th>
                    <th class="text-right" width="120">Setup</th>
                    <th class="text-right" width="120">1ª Mens. (Rep)</th>
                    <th class="text-right" width="120">Mens. (PW)</th>
                    <th class="text-right" width="120">Valor</th>
                    <th class="text-right" width="120">Saldo</th>
                  </tr>
                  </thead>
                  <tbody>
                  <?php
                  $saldo_acumulado = $saldos_anteriores['valor'];?>
                  <tr class="linha_destaque">
                    <td colspan="8" style="font-weight: bold">Saldo Anterior (Até <?php echo date("d/m/Y", strtotime("-1 days", strtotime($data_inicio)))?>)</td>
                    <td class="text-right" style="font-weight: bold"><?php echo valorStyle($saldos_anteriores['valor'], 'moeda')?></td>
                  </tr>

                  <?php foreach($registros as $l){
                    $saldo_acumulado += $l['valor'];
                    ?>
                    <tr>
                      <td class="text-center" style="padding: 6px 0 0 0"><?php echo str_pad($l['periodo_mes'],2,'0',STR_PAD_LEFT).'/'.$l['periodo_ano']?></td>
                      <td class="text-center" style="padding: 6px 0 0 0"><?php echo $l['data_hora']?></td>
                      <td>
                        <?php
                          if($l['tipo']==0){echo 'Manual';}
                          elseif($l['tipo']==1){echo 'Venda';}
                          elseif($l['tipo']==2){echo 'Mensalidade';}
                        ?>
                      </td>
                      <td><?php echo $l['tipo']==0 ? $l['descricao'] : $l['clube']?></td>
                      <td class="text-right"><?php echo $l['tipo']==1 ? valorStyle($l['valor_setup'], 'moeda') : ''?></td>
                      <td class="text-right"><?php echo $l['tipo']==1 ? valorStyle($l['valor_mensalidade'], 'moeda') : ''?></td>
                      <td class="text-right"><?php echo $l['tipo']==2 ? valorStyle($l['valor_mensalidade'], 'moeda') : ''?></td>
                      <td class="text-right"><?php echo valorStyle($l['valor'], 'moeda')?></td>
                      <td class="text-right"><?php echo valorStyle($saldo_acumulado, 'moeda')?></td>
                    </tr>
                  <?php } ?>
                  <tr class="linha_destaque">
                    <td colspan="6" style="font-weight: bold">Saldo do Período</td>
                    <td class="text-right" colspan="3" style="font-weight: bold">
                      <?php echo valorStyle($saldos_periodo['entrada'], 'moeda')?> - <?php echo valorStyle($saldos_periodo['saida']*-1, 'moeda', null, null, '#8d0000', '#8d0000')?> = <?php echo valorStyle($saldos_periodo['valor'], 'moeda'); ?>
                    </td>
                  </tr>
                  </tbody>
                </table>
              </section>

              <!-- CATEGORIAS - Excluir Categoria -->
              <div id="confirmar_acao_multipla" class="modal fade bs-example-modal-sm">
                <div class="modal-dialog modal-sm" style="width: 450px;">
                  <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">Realizar Ações Multiplas</h4>
                    </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-inverse" data-loading-text="Realizar">Realizar</button>
                    </div>
                  </div>
                </div>
              </div>

            </form>
          </div>

        </div>
      <?php } ?>
    </div>
  </section>
</section>

<!-- FOOTER -->
<?php include('footer.php');?>
<?php include('scripts/financeiro/modals.php');?>

<!-- CATEGORIAS - Informações de Lançamento -->
<div id="modal_inf_lancamento" class="modal fade bs-example-modal-sm">
  <div class="modal-dialog modal-sm" style="width: 450px;">
    <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">Informações</h4>
      </div>
      <div class="modal-body"></div>
      <div class="modal-footer">
        <button type="button" class="btn btn-sm btn-default" data-dismiss="modal">Fechar</button>
      </div>
    </div>
  </div>
</div>

<!-- CATEGORIAS - Informações de Lançamento -->
<div id="modal_nota_fiscal" class="modal fade bs-example-modal-sm">
  <div class="modal-dialog modal-sm" style="width: 500px;">
    <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">Nota Fiscal</h4>
      </div>
      <div class="modal-body"></div>
      <div class="modal-footer">
        <button type="button" class="btn btn-sm btn-default" data-dismiss="modal">Fechar</button>
      </div>
    </div>
  </div>
</div>

<!-- CATEGORIAS - Informações de Lançamento -->
<div id="modal_anexos" class="modal fade bs-example-modal-sm">
  <div class="modal-dialog modal-sm" style="width: 550px;">
    <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">Anexos</h4>
      </div>
      <div class="modal-body"></div>
      <div class="modal-footer">
        <button type="button" class="btn btn-sm btn-default" data-dismiss="modal">Fechar</button>
      </div>
    </div>
  </div>
</div>

<!-- app -->
<script src="js/app.js"></script>
<script src="js/app.plugin.js"></script>
<script src="js/app.data.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.js"></script>
<!-- Flot -->
<script src="js/charts/flot/jquery.flot.min.js"></script>
<script src="js/charts/flot/jquery.flot.tooltip.min.js"></script>
<script src="js/charts/flot/jquery.flot.resize.js"></script>
<script src="js/charts/flot/jquery.flot.orderBars.js"></script>
<script src="js/charts/flot/jquery.flot.pie.min.js"></script>

<!-- Autocompletar -->
<script type="text/javascript" src="js/simpleAutoComplete.js?id=1"></script>

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