<?php
// consultores carregados de uma vez (antes era 1 query por linha)
$mapUsuarios = array();
try {
    $moUsuario = new Crm_Model_Usuario();
    foreach ($moUsuario->fetchAll() as $u) { $mapUsuarios[$u->id] = $u->nome; }
} catch (Exception $e) { $mapUsuarios = array(); }

// converte para float preservando centavos e milhares
$vlr = function($v) {
    if (is_numeric($v)) return (float)$v;
    $v = trim((string)$v);
    if ($v === '') return 0.0;
    if (strpos($v, ',') !== false) $v = str_replace(',', '.', str_replace('.', '', $v));
    return (float)$v;
};

$count = 0;
$iVTotal = 0;
$fFatTotal = 0;
$fFatSuporte = 0;
$fPtTotal = 0;
$iCTotal = 0;
$fCValor = 0;

$linhas = array();
foreach ($this->objs as $obj) :
    $aRaw = $obj->toArray();
    $rRow = $this->FormataInputsView($this->cols, $aRaw);

    if($rRow['produto_id'] == 2 and $rRow['tipo_visto_id'] != 75 and $rRow['valor_suporte'] > 0){
      $iVTotal++;
    }

    if($rRow['produto_id'] == 13){
      $iCTotal--;
      $fCValor -= 12;
    }

    $fFatTotal   += $vlr(isset($aRaw['valor'])         ? $aRaw['valor']         : $rRow['valor']);
    $fFatSuporte += $vlr(isset($aRaw['valor_suporte']) ? $aRaw['valor_suporte'] : $rRow['valor_suporte']);
    $fPtTotal    += $vlr(isset($aRaw['pontos'])        ? $aRaw['pontos']        : $rRow['pontos']);

    $linhas[] = array('r' => $rRow, 'raw' => $aRaw);
endforeach;

$iMetaVisto  = $this->meta->valor;
$pAtingV     = $iMetaVisto > 0 ? ($iVTotal + $iCTotal) / $iMetaVisto : 0;
$totalLinhas = count($linhas);
$LIMITE = 1500;

$dataCurta = function($raw, $fmt) {
    if (!empty($raw) && ($t = strtotime($raw)) !== false) return date('d/m/Y H:i', $t);
    return $fmt;
};
$nomeCurto = function($n) {
    $p = preg_split('/\s+/', trim((string)$n));
    return count($p) > 1 ? $p[0] . ' ' . $p[count($p) - 1] : (string)$n;
};
$moeda = function($v) { return (trim((string)$v) === '') ? '0,00' : $v; };
$fm = $this->form;
$ativos = array();
$rotSel = function($el) {
    $v = $el->getValue();
    if ($v === null || $v === '' || $v === '0') return null;
    $ops = $el->getMultiOptions();
    return isset($ops[$v]) && $ops[$v] !== '' ? $ops[$v] : null;
};
foreach (array('solicitante') as $c) {
    $v = trim((string)$fm->$c->getValue());
    if ($v !== '') $ativos[] = array('campo' => $c, 'txt' => 'Nome: ' . $v);
}
foreach (array('usuario_cadastro', 'cfs_id', 'produto_id', 'pais_id', 'parceiro_id', 'mes', 'ano') as $c) {
    if (!isset($fm->$c)) continue;
    $t = $rotSel($fm->$c);
    if ($t !== null) $ativos[] = array('campo' => $c, 'txt' => $fm->$c->getLabel() . ': ' . $t);
}
if ($this->tipoVistoSel) $ativos[] = array('campo' => 'tipo_visto_id', 'txt' => 'Tipo de Visto: ' . $this->tipoVistoNome);
$dI = trim((string)$fm->datacadastroi->getValue());
$dF = trim((string)$fm->datacadastrof->getValue());
if ($dI !== '' || $dF !== '')
    $ativos[] = array('campo' => 'datacadastro', 'txt' => 'Cadastro: ' . ($dI !== '' ? $dI : '…') . ' a ' . ($dF !== '' ? $dF : '…'));

$sortNum = function($v) { return htmlspecialchars(str_replace(array('.', ','), array('', '.'), (string)$v), ENT_QUOTES); };
?>
<style>
  @media (min-width: 1200px) { .container { width: 94%; max-width: 1400px; } }
  .rv-tbl { font-size: 85% !important; }
  .rv-tbl > thead > tr > th, .rv-tbl > tbody > tr > td, .rv-tbl > tbody > tr > th { padding: 5px 6px; }
  .rv-tbl .nw { white-space: nowrap; }
  .rv-tbl > thead > tr > th { cursor: pointer; white-space: nowrap; }
  .rv-tbl > thead > tr > th:after { content: ' \2195'; color: #ccc; font-size: 9px; font-weight: normal; }
  .rv-tbl > thead > tr > th.nosort { cursor: default; } .rv-tbl > thead > tr > th.nosort:after { content: ''; }
  .rv-tbl > thead > tr > th.asc:after  { content: ' \25B2'; color: #666; }
  .rv-tbl > thead > tr > th.desc:after { content: ' \25BC'; color: #666; }
  .rv-tbl > tbody > tr.rv-par > td, .rv-tbl > tbody > tr.rv-par > th { background-color: #f5f5f5; }
  .rv-tbl .num { text-align: right; white-space: nowrap; }
  .rv-ativos { margin-bottom: 10px; font-size: 12px; }
  .rv-ativos .tit { color: #888; margin-right: 6px; }
  .rv-ativos .chip { display: inline-block; background: #eaf1f0; border: 1px solid #cfdedc; color: #33514e;
                     padding: 2px 8px; margin: 0 4px 4px 0; border-radius: 2px; }
  .rv-ativos .chip.fixo { background: #f2f2f2; border-color: #e0e0e0; color: #777; }
  .rv-ativos .chip a { color: #8a6d3b; margin-left: 6px; font-weight: bold; text-decoration: none; }
  .rv-ativos .limpar { margin-left: 14px; font-size: 12px; color: #777; text-decoration: none; }
  .rv-ativos .limpar:hover { color: #a94442; text-decoration: underline; }
  .rv-par { display: table; width: 100%; table-layout: fixed; }
  .rv-par > div { display: table-cell; vertical-align: middle; padding-right: 6px; }
  .rv-par > div:last-child { padding-right: 0; }
  .rv-par > .ate { width: 36px; text-align: center; color: #888; font-size: 12px; padding-right: 0; }
  .rv-filtro-lbl, .panel-body label { font-weight: bold; margin-bottom: 5px; }
  .rv-acoes { margin-top: 18px; padding-top: 14px; border-top: 1px solid #eee; }
  .rv-barra { margin-bottom: 8px; overflow: hidden; }
  .rv-barra .contador { line-height: 30px; color: #888; font-size: 12px; }
  .rv-atalhos { font-size: 12px; color: #888; margin-left: 22px; }
  .rv-atalhos .btn { margin-right: 4px; }
  .rv-strip { display: table; width: 100%; table-layout: fixed; background: #f5f5f5; border: 1px solid #ddd; margin-bottom: 20px; }
  .rv-strip .cell { display: table-cell; padding: 12px 14px; border-left: 1px solid #ddd; vertical-align: top; }
  .rv-strip .cell:first-child { border-left: 0; }
  .rv-strip .lbl { display: block; font-size: 10px; font-weight: bold; text-transform: uppercase; letter-spacing: .04em; color: #5e5e5e; margin-bottom: 3px; }
  .rv-strip .val { font-size: 22px; font-weight: bold; color: #333; line-height: 1.2; }
  .rv-strip .sub { font-size: 11px; color: #999; margin-top: 2px; min-height: 14px; }
  .rv-strip .neg { color: #a94442; } .rv-strip .pos { color: #3c763d; }
  .rv-prog { height: 5px; background: #e6e6e6; margin-top: 6px; }
  .rv-prog i { display: block; height: 5px; background: #5cb85c; }
  .rv-prog i.baixo { background: #d9534f; } .rv-prog i.medio { background: #f0ad4e; }

  @media print {
    @page { size: A4 landscape; margin: 10mm; }
    .no-print, .navbar, nav, footer, #accordion, form { display: none !important; }
    body { padding-top: 0 !important; }
    .page-header { margin-top: 0; }
    .rv-strip { background: none !important; border: 0; border-top: 1pt solid #999; border-bottom: 1pt solid #999; }
    .rv-strip .cell { padding: 6px 8px; }
    .rv-tbl { font-size: 8.5px; }
    .rv-tbl > thead { display: table-header-group; }
    .rv-tbl > thead > tr > th:after { content: '' !important; }
    .rv-tbl > tbody > tr { page-break-inside: avoid; }
    table, table * { -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
    a[href]:after { content: none !important; }
  }
</style>

<div class="page-header">
  <h1>Relatório de Vendas</h1>
</div>
<div class="row"><div class="col-md-12">
<form action="" method="post" class="form-horizontal" role="form" id="rv_form">
    <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
      <div class="panel panel-default">
        <div class="panel-heading" role="tab" id="headingOne">
          <h4 class="panel-title"><a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          Pesquisa Avançada
          </a>
          </h4>
        </div>
        <div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
          <div class="panel-body">
            <div class="form-group col-md-12">
              <div class="col-md-3"><?= $this->form->solicitante ?></div>
              <div class="col-md-3"><?= $this->form->usuario_cadastro ?></div>
              <div class="col-md-3"><?= $this->form->cfs_id ?></div>
              <div class="col-md-3"><?= $this->form->produto_id ?></div>
            </div>
            <div class="form-group col-md-12">
              <div class="col-md-3"><?= $this->form->pais_id ?></div>
              <div class="col-md-3"><?= $this->form->tipo_visto_id ?></div>
              <div class="col-md-3"><?= $this->form->parceiro_id ?></div>
              <div class="col-md-3">
                <div class="rv-par">
                  <div><?= $this->form->mes ?></div>
                  <div><?= $this->form->ano ?></div>
                </div>
              </div>
            </div>
            <div class="form-group col-md-12">
              <div class="col-md-6">
                <label>Data de cadastro</label>
                <div class="rv-par">
                  <div><?= $this->form->datacadastroi->renderViewHelper() ?></div>
                  <div class="ate">até</div>
                  <div><?= $this->form->datacadastrof->renderViewHelper() ?></div>
                </div>
              </div>
            </div>
                      <div class="form-group col-md-12 rv-acoes">
                          <div class="col-md-12">
                            <input type="submit" class="btn btn-primary" value="Pesquisar">
                            <span class="rv-atalhos">
                            Período:
                            <button type="button" class="btn btn-xs btn-default" onclick="rvPeriodo('mes')">Este mês</button>
                            <button type="button" class="btn btn-xs btn-default" onclick="rvPeriodo('mes_anterior')">Mês anterior</button>
                            <button type="button" class="btn btn-xs btn-default" onclick="rvPeriodo('ano')">Este ano</button>
                            <button type="button" class="btn btn-xs btn-default" onclick="rvPeriodo('ano_anterior')">Ano anterior</button>
                            <button type="button" class="btn btn-xs btn-default" onclick="rvPeriodo('12m')">Últimos 12 meses</button>
                            </span>
                          </div>
                      </div>
          </div>
        </div>
      </div>
    </div>
</form>

<?php $lacuna = ($iVTotal + $iCTotal) - $iMetaVisto; ?>
<div class="rv-strip">
  <div class="cell">
    <span class="lbl">Meta</span>
    <span class="val"><?php echo $iMetaVisto ?></span>
    <div class="sub"><?php echo $this->Mes($this->meta->mes) ?></div>
  </div>
  <div class="cell">
    <span class="lbl">Real</span>
    <span class="val"><?php echo $iVTotal ?></span>
    <div class="sub">vistos vendidos</div>
  </div>
  <div class="cell">
    <span class="lbl">Canc.</span>
    <span class="val"><?php echo $iCTotal ?></span>
    <div class="sub">cancelamentos</div>
  </div>
  <div class="cell">
    <span class="lbl">Total</span>
    <span class="val"><?php echo $iVTotal + $iCTotal ?></span>
    <div class="sub">real − canc.</div>
  </div>
  <div class="cell">
    <span class="lbl">Atingimento</span>
    <span class="val"><?php echo str_replace('.', ',', round(100 * $pAtingV, 2)) ?>%</span>
    <div class="rv-prog"><i class="<?php echo $pAtingV < 0.7 ? 'baixo' : ($pAtingV < 1 ? 'medio' : '') ?>"
         style="width:<?php echo number_format(min(100, max(0, $pAtingV * 100)), 2, '.', '') ?>%"></i></div>
  </div>
  <div class="cell">
    <span class="lbl">Lacuna</span>
    <span class="val <?php echo $lacuna < 0 ? 'neg' : 'pos' ?>"><?php echo ($lacuna > 0 ? '+' : '') . $lacuna ?></span>
    <div class="sub">em relação à meta</div>
  </div>
</div>

<div class="rv-ativos no-print">
  <span class="tit">Filtros aplicados:</span>
  <?php if (!$ativos): ?><span class="chip fixo">nenhum — mês de referência</span><?php endif; ?>
  <?php foreach ($ativos as $a): ?>
  <span class="chip"><?php echo $a['txt'] ?>
    <a href="javascript:void(0)" onclick="rvRemover('<?php echo $a['campo'] ?>')" title="Remover este filtro">&times;</a>
  </span>
  <?php endforeach; ?>
  <a href="javascript:void(0)" class="limpar" onclick="rvLimpar()"><span class="glyphicon glyphicon-trash" style="font-size:10px"></span> Limpar filtros</a>
</div>

<div class="rv-barra no-print">
  <div class="col-md-5" style="padding-left:0">
    <input type="text" id="rv_busca" class="form-control input-sm" placeholder="Filtrar linhas exibidas (nome, país, consultor…)" onkeyup="rvBuscar()">
  </div>
  <div class="col-md-7 text-right contador" style="padding-right:0">
    <span id="rv_contador"></span>
    <?php if ($totalLinhas > $LIMITE): ?>
    <button type="button" class="btn btn-xs btn-default" id="rv_btn_todas" onclick="rvMostrarTodas()" style="margin-left:8px">
      Mostrar todas as <?php echo number_format($totalLinhas, 0, ',', '.') ?> linhas
    </button>
    <?php endif; ?>
    <button type="button" class="btn btn-xs btn-default" onclick="window.print()" style="margin-left:8px">
      <span class="glyphicon glyphicon-print"></span> Imprimir
    </button>
    <button type="button" class="btn btn-xs btn-default" onclick="rvCsv()">
      <span class="glyphicon glyphicon-download-alt"></span> CSV
    </button>
  </div>
</div>

<?php if ($totalLinhas > $LIMITE): ?>
<div class="alert alert-warning no-print" id="rv_aviso" style="padding:8px 12px;font-size:12px">
  Exibindo as primeiras <?php echo number_format($LIMITE, 0, ',', '.') ?> de
  <?php echo number_format($totalLinhas, 0, ',', '.') ?> linhas para não travar o navegador.
  <strong>Os totais consideram todas as linhas.</strong>
</div>
<?php endif; ?>

<table class="table table-hover rv-tbl" id="rv_tabela">
  <thead class="thead-default">
    <tr>
      <th class="nosort">#</th>
      <th data-t="s">NOME</th>
      <th data-t="s">PRODUTO</th>
      <th data-t="s">PAÍS</th>
      <th data-t="s">VISTO</th>
      <th data-t="n" class="num">VALOR</th>
      <th data-t="n" class="num">SUPORTE</th>
      <th data-t="s">CFS</th>
      <th data-t="s">AGÊNCIA</th>
      <th data-t="s">CONSULTOR</th>
      <th data-t="s">CADASTRO</th>
    </tr>
  </thead>
  <tbody>
  <?php foreach ($linhas as $i => $l):
    $rRow = $l['r']; $aRaw = $l['raw'];
    $consultor = isset($mapUsuarios[$rRow['usuario_cadastro']]) ? $mapUsuarios[$rRow['usuario_cadastro']] : '';
    $count++;
  ?>
    <tr<?php echo ($i >= $LIMITE) ? ' class="rv-oculta" style="display:none"' : '' ?>>
      <th scope="row"><?php echo $count ?></th>
      <td><a href="/crm/compra/editar/id/<?php echo $rRow['id']?>" title="Editar"><?php echo $rRow['solicitante'] ?></a></td>
      <td class="nw"><?php echo $rRow['produto'] ?></td>
      <td class="nw"><?php echo $rRow['pais_nome'] ?></td>
      <td><?php echo $rRow['tipo_visto'] ?></td>
      <td class="num" data-s="<?php echo $sortNum($rRow['valor']) ?>">R$ <?php echo $moeda($rRow['valor']) ?></td>
      <td class="num" data-s="<?php echo $sortNum($rRow['valor_suporte']) ?>">R$ <?php echo $moeda($rRow['valor_suporte']) ?></td>
      <td><?php echo $rRow['cfs_nome'] ?></td>
      <td><?php echo $rRow['parceiro_id'] != 0 ? $rRow['parceiro_nome'] : "" ?></td>
      <td title="<?php echo htmlspecialchars($consultor, ENT_QUOTES) ?>"><?php echo $nomeCurto($consultor) ?></td>
      <td class="nw" data-s="<?php echo htmlspecialchars(isset($aRaw['cadastro']) ? $aRaw['cadastro'] : '', ENT_QUOTES) ?>"><?php echo $dataCurta(isset($aRaw['cadastro']) ? $aRaw['cadastro'] : '', $rRow['cadastro']) ?></td>
    </tr>
  <?php endforeach; ?>
    <tr style="background-color: #373a3c; color: #fff">
        <td colspan="4"><strong>TOTAL</strong></td>
        <td><strong><?php echo $iVTotal?> VISTOS</strong></td>
        <td class="num"><strong><?php echo $this->Currency($fFatTotal)?></strong></td>
        <td class="num"><strong><?php echo $this->Currency($fFatSuporte)?></strong></td>
        <td colspan="4"></td>
    </tr>
  </tbody>
</table>
</div></div>

<script>
// tipos de visto conforme o pais (endpoint atual do CRM)
function rvCarregaTipos(manter) {
  var paisId = $('#pais_id').val();
  var atual  = manter ? $('#tipo_visto_id').val() : '';
  $('#tipo_visto_id').find('option').remove().end().append('<option value=""> </option>').val('');
  if (!paisId) return;
  jQuery.ajax({
    url: "/crm/visto/tipos/",
    dataType: "json",
    data: {pais: paisId},
    type: "GET",
    success: function (data) {
      jQuery.each(data, function (i, j) {
        $("#tipo_visto_id").append("<option value='" + data[i].tipo_visto_id + "'>" + data[i].tipo + "</option>");
      });
      if (atual) $('#tipo_visto_id').val(atual);
    },
    error: function () {}
  });
}
$(document).ready(function () {
  $("#pais_id").off('change').on('change', function () { rvCarregaTipos(false); });
  if ($('#pais_id').val()) rvCarregaTipos(true);
});

function rvData(dt) {
  var d = ('0' + dt.getDate()).slice(-2), m = ('0' + (dt.getMonth() + 1)).slice(-2);
  return d + '/' + m + '/' + dt.getFullYear();
}
function rvPeriodo(tipo) {
  var h = new Date(), y = h.getFullYear(), m = h.getMonth(), i, f;
  if      (tipo == 'mes')          { i = new Date(y, m, 1);      f = new Date(y, m + 1, 0); }
  else if (tipo == 'mes_anterior') { i = new Date(y, m - 1, 1);  f = new Date(y, m, 0); }
  else if (tipo == 'ano')          { i = new Date(y, 0, 1);      f = new Date(y, 11, 31); }
  else if (tipo == 'ano_anterior') { i = new Date(y - 1, 0, 1);  f = new Date(y - 1, 11, 31); }
  else                             { i = new Date(y, m - 11, 1); f = new Date(y, m + 1, 0); }
  var fm = document.getElementById('rv_form');
  fm.datacadastroi.value = rvData(i);
  fm.datacadastrof.value = rvData(f);
  if (fm.mes) fm.mes.value = '';
  if (fm.ano) fm.ano.value = '';
  fm.submit();
}
function rvRemover(campo) {
  var fm = document.getElementById('rv_form');
  if (fm[campo]) { if (fm[campo].tagName == 'SELECT') fm[campo].selectedIndex = 0; fm[campo].value = ''; }
  if (campo == 'datacadastro') { fm.datacadastroi.value = ''; fm.datacadastrof.value = ''; }
  fm.submit();
}
function rvLimpar() {
  var fm = document.getElementById('rv_form'), el = fm.elements;
  for (var k = 0; k < el.length; k++) {
    if (el[k].type == 'text') el[k].value = '';
    else if (el[k].tagName == 'SELECT') el[k].selectedIndex = 0;
  }
  fm.submit();
}
function rvCsv() {
  var fm = document.getElementById('rv_form'), acao = fm.action;
  fm.action = '/crm/relatorio/vendas-csv';
  fm.submit();
  fm.action = acao;
}
function rvMostrarTodas() {
  var l = document.querySelectorAll('#rv_tabela tbody tr.rv-oculta');
  for (var k = 0; k < l.length; k++) { l[k].style.display = ''; l[k].className = l[k].className.replace('rv-oculta', ''); }
  var b = document.getElementById('rv_btn_todas'), a = document.getElementById('rv_aviso');
  if (b) b.style.display = 'none';
  if (a) a.style.display = 'none';
  rvBuscar();
}
function rvReflow() {
  // renumera e aplica zebra apenas nas linhas visiveis, na ordem atual
  var tr = document.querySelectorAll('#rv_tabela tbody tr'), n = 0;
  for (var k = 0; k < tr.length - 1; k++) {
    tr[k].className = tr[k].className.replace(/\s*rv-par/g, '');
    if (tr[k].style.display == 'none') continue;
    n++;
    tr[k].cells[0].innerHTML = n;
    if (n % 2 == 0) tr[k].className += ' rv-par';
  }
  var c = document.getElementById('rv_contador');
  if (c) c.innerHTML = n + ' linha' + (n == 1 ? '' : 's') + ' exibida' + (n == 1 ? '' : 's');
}
function rvBuscar() {
  var q = (document.getElementById('rv_busca').value || '').toLowerCase();
  var tr = document.querySelectorAll('#rv_tabela tbody tr');
  for (var k = 0; k < tr.length - 1; k++) {
    if (tr[k].className.indexOf('rv-oculta') >= 0) continue;
    tr[k].style.display = (q === '' || tr[k].textContent.toLowerCase().indexOf(q) >= 0) ? '' : 'none';
  }
  rvReflow();
}
document.addEventListener('DOMContentLoaded', function () {
  rvBuscar();
  var ths = document.querySelectorAll('#rv_tabela thead th');
  for (var k = 0; k < ths.length; k++) {
    (function (th, idx) {
      if (th.className.indexOf('nosort') >= 0) return;
      th.onclick = function () {
        var asc = th.className.indexOf('asc') < 0;
        for (var j = 0; j < ths.length; j++) ths[j].className = ths[j].className.replace(/\s*(asc|desc)/g, '');
        th.className += asc ? ' asc' : ' desc';
        var tb = document.querySelector('#rv_tabela tbody');
        var rows = Array.prototype.slice.call(tb.querySelectorAll('tr'));
        var total = rows.pop();                 // linha de TOTAL fica sempre no fim
        var num = th.getAttribute('data-t') == 'n';
        rows.sort(function (a, b) {
          var ca = a.cells[idx], cb = b.cells[idx];
          var va = ca.getAttribute('data-s') !== null ? ca.getAttribute('data-s') : ca.textContent.trim();
          var vb = cb.getAttribute('data-s') !== null ? cb.getAttribute('data-s') : cb.textContent.trim();
          if (num) { va = parseFloat(va) || 0; vb = parseFloat(vb) || 0; return asc ? va - vb : vb - va; }
          return asc ? va.localeCompare(vb, 'pt-BR') : vb.localeCompare(va, 'pt-BR');
        });
        for (var j = 0; j < rows.length; j++) tb.appendChild(rows[j]);
        tb.appendChild(total);
        rvReflow();
      };
    })(ths[k], k);
  }
});
</script>
