<?php
session_start();
require_once("db.php");


$id_tela = $_REQUEST['id_tela'];

//buscar a cifra padrão do usuário
$paisDefault = $_SESSION['pais'];
$queryMoedaDefault = "SELECT a.moeda_sigla
				FROM regiao a
				WHERE 
				a.id_pais = '$paisDefault'
				AND a.status = 1";
$resultMoedaDefault = mysql_query($queryMoedaDefault) or die(mysql_error());
$rowListDefault = mysql_fetch_array($resultMoedaDefault);
$_SESSION['cifraoMoeda'] = $rowListDefault['moeda_sigla'];

function getApoios($id_user) {
    $apoio = array();
    $resultSocios = mysql_query("SELECT id FROM user "
            . " WHERE id_apoio = $id_user "
            . " AND status = 1");
    $apoio[] = $id_user;
    while ($rowSocios = mysql_fetch_array($resultSocios)) {
        $apoio[] = $rowSocios['id'];
    }
    return $apoio;
}

switch ($id_tela) {

    case 'Home':

        $nivel_necessario = 6;

        // Verifica se não há a variável da sessão que identifica o usuário
        if (!isset($_SESSION['UsuarioID']) OR ( $_SESSION['UsuarioNivel'] > $nivel_necessario)) {
            // Destrói a sessão por segurança
            session_destroy();
            // Redireciona o visitante de volta pro login
            header("Location: index.php");
            exit;
        }

        require_once("db.php");
        ?>


        <div class="panel-body">

            <div class="row">
                <div class="col-lg-12">

                    <div class="col-lg-3">
                        <a  href="javascript:void(0)" onclick="fLoadOptionScriptLeitura('Leitura', '<?php echo $_SESSION['pais'] ?>')" >
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <div class="row">
                                        <br>
                                        <div class="col-xs-4">
                                            <i class="fa fa-dashboard fa-5x blue"></i>
                                        </div>
                                        <div class="col-lg-8 text-center blue">
                                            <p class="announcement-heading-text"><h4>Painel Administrativo</h4></p>
                                            <br> 
                                        </div>
                                    </div>
                                </div>

                            </div>
                        </a>
                    </div>


                    <?php if ($_SESSION['UsuarioNivel'] == 1) { ?>

                        <div class="col-lg-3">
                            <a  href="javascript:void(0)" onclick="fLoadOptionScript('GerenciarFaturas')">
                                <div class="panel panel-default">
                                    <div class="panel-heading">
                                        <div class="row">
                                            <br>
                                            <div class="col-xs-4">												
                                                <i class="fa fa-barcode fa-5x blue" aria-hidden="true"></i>
                                            </div>
                                            <div class="col-lg-8 text-center blue">
                                                <p class="announcement-heading-text"><h4>Gerenciar Faturas</h4></p>
                                                <br> 
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </a>
                        </div>	

                        <div class="col-lg-3">
                            <a href="javascript:void(0)" onclick="fLoadOptionScript('GerenciarAdministradores')" >
                                <div class="panel panel-default">
                                    <div class="panel-heading">
                                        <div class="row">
                                            <br>
                                            <div class="col-xs-4">
                                                <i class="fa fa-user-secret fa-5x blue" aria-hidden="true"></i>
                                            </div>
                                            <div class="col-lg-8 text-center blue">
                                                <p class="announcement-heading-text"><h4>Administradores</h4></p>
                                                <br> 
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </a>
                        </div>				

                        <?php
                    }

                    if ($_SESSION['UsuarioNivel'] < 3) {
                        ?>

                        <div class="col-lg-3">
                            <a href="javascript:void(0)" onclick="fLoadOptionScript('Clientes')" >
                                <div class="panel panel-default">
                                    <div class="panel-heading">
                                        <div class="row">
                                            <br>
                                            <div class="col-xs-4">
                                                <i class="fa fa-users fa-5x blue"></i>
                                            </div>
                                            <div class="col-lg-8 text-center blue">
                                                <p class="announcement-heading-text"><h4>Gerenciar Clientes</h4></p>
                                                <br> 
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </a>
                        </div>


                        <?php
                    }

                    if ($_SESSION['UsuarioNivel'] < 5 || $_SESSION['UsuarioNivel'] == 6) { //MUDANÇA ANDRE
                        ?>

                        <div class="col-lg-3">
                            <a href="javascript:void(0)" onclick="fLoadOptionScript('ConsultarFaturas')" >
                                <div class="panel panel-default">
                                    <div class="panel-heading">
                                        <div class="row">
                                            <br>
                                            <div class="col-xs-4">			
                                                <i class="fa fa-credit-card-alt fa-5x blue" aria-hidden="true"></i>
                                            </div>
                                            <div class="col-lg-8 text-center blue">
                                                <p class="announcement-heading-text"><h4>Consultar Leituras</h4></p>
                                                <br> 
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </a>
                        </div>					
                        <div class="col-lg-3">
                            <a href="javascript:void(0)" onclick="fLoadOptionScript('ConsultarFaturasPeriodo')" >
                                <div class="panel panel-default">
                                    <div class="panel-heading">
                                        <div class="row">
                                            <br>
                                            <div class="col-xs-4">	
                                                <i class="fa fa-calendar fa-5x blue" aria-hidden="true"></i>
                                            </div>
                                            <div class="col-lg-8 text-center blue">
                                                <p class="announcement-heading-text"><h4>Faturas por Período</h4></p>
                                                <br> 
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </a>
                        </div>	
                        <?php if ($_SESSION['UsuarioNivel'] < 6) { ?>
                            <div class="col-lg-3">
                                <a href="javascript:void(0)" onclick="fLoadOptionScript('Socios')" >
                                    <div class="panel panel-default">
                                        <div class="panel-heading">
                                            <div class="row">
                                                <br>
                                                <div class="col-xs-4">
                                                    <i class="fa fa-briefcase fa-5x blue"></i>
                                                </div>
                                                <div class="col-lg-8 text-center blue">
                                                    <p class="announcement-heading-text"><h4>Gerenciar Sócios</h4></p>
                                                    <br> 
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </a>
                            </div>



                            <div class="col-lg-3">
                                <a href="javascript:void(0)" onclick="fLoadOptionScript('Operadores');">
                                    <div class="panel panel-default">
                                        <div class="panel-heading">
                                            <div class="row">
                                                <br>
                                                <div class="col-xs-4">					
                                                    <i class="fa fa-user fa-5x blue" aria-hidden="true"></i>
                                                </div>
                                                <div class="col-lg-8 text-center blue">
                                                    <p class="announcement-heading-text"><h4>Gerenciar Operadores</h4></p>
                                                    <br> 
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </a>
                            </div>
                            <?php
                        }
                        ?>	


                        <?php
                    }

                    if ($_SESSION['UsuarioNivel'] < 5) {
                        ?>


                        <div class="col-lg-3">
                            <a href="javascript:void(0)" onclick="fLoadOptionScript('Funcionarios')" >
                                <div class="panel panel-default">
                                    <div class="panel-heading">
                                        <div class="row">
                                            <br>
                                            <div class="col-xs-4">
                                                <i class="fa fa-user-plus fa-5x blue" aria-hidden="true"></i>
                                            </div>
                                            <div class="col-lg-8 text-center blue">
                                                <p class="announcement-heading-text"><h4>Gerenciar Funcionários</h4></p>
                                                <br> 
                                            </div>
                                        </div>
                                    </div>

                                </div>
                            </a>
                        </div>

                        <?php
                    }

                    if ($_SESSION['UsuarioNivel'] < 6) {
                        ?>

                        <div class="col-lg-3">
                            <a href="javascript:void(0)" onclick="fLoadOptionScript('Pontos')" >
                                <div class="panel panel-default">
                                    <div class="panel-heading">
                                        <div class="row">
                                            <br>
                                            <div class="col-xs-4">					
                                                <i class="fa fa-map-marker fa-5x blue" aria-hidden="true"></i>
                                            </div>
                                            <div class="col-lg-8 text-center blue">
                                                <p class="announcement-heading-text"><h4>Gerenciar Pontos</h4></p>
                                                <br> 
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </a>
                        </div>
                        <?php
                    }
                    ?>		

                    <div class="col-lg-3">
                        <a href="javascript:void(0);" onclick="fLoadOptionScript('Tablets')">
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <div class="row">
                                        <br>
                                        <div class="col-xs-4">
                                            <i class="fa fa-tablet fa-5x blue"></i>
                                        </div>
                                        <div class="col-lg-8 text-center blue">
                                            <p class="announcement-heading-text"><h4>Gerenciar Tablets</h4></p>
                                            <br> 
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </a>
                    </div>

                </div>
            </div>
        </div>




        <?php
        if ($_SESSION['UsuarioNivel'] <= 3) {

            if ($_SESSION['UsuarioNivel'] <= 2) {

                $queryGrafico = "SELECT a.periodo_prestacao, a.valor_total, a.tipo_cobranca
									FROM cobranca_agregado a
									WHERE 
									a.pago = 1
									AND a.ativo = 1
									GROUP BY a.periodo_prestacao";
            } else {

                $queryGrafico = "SELECT a.periodo_prestacao, a.valor_total, a.tipo_cobranca
									FROM cobranca_ponto a
									LEFT JOIN ponto c ON c.id = a.id_ponto
									WHERE 
									a.pago = 1
									AND a.ativo = 1
									AND c.id_apoio = '$_SESSION[UsuarioID]'
									GROUP BY a.periodo_prestacao";
            }
            $resultGrafico = mysql_query($queryGrafico) or die(mysql_error());
            $arrayMeses = array('1' => 'Janeiro', '2' => 'Fevereiro', '3' => 'Março', '4' => 'Abril', '5' => 'Maio', '6' => 'Junho', '7' => 'Julho', '8' => 'Agosto', '9' => 'Setembro', '10' => 'Outubro', '11' => 'Novembro', '12' => 'Dezembro');

            $dataMeses = '';
            $dataComissao = '';
            while ($rowGrafico = mysql_fetch_array($resultGrafico)) {

                if ($rowGrafico['tipo_cobranca'] == 'Mensal') {
                    $deAte = '01 a';
                } else {
                    if (substr($rowGrafico['periodo_prestacao'], -2) == '15') {
                        $deAte = '01 a';
                    } else {
                        $deAte = '15 a';
                    }
                }

                $mes = substr($rowGrafico['periodo_prestacao'], 5, 2);
                $dataMeses.= "'" . $arrayMeses[intval($mes)] . ' de ' . $deAte . ' ' . fConvData($rowGrafico['periodo_prestacao']) . ' (' . $_SESSION['cifraoMoeda'] . " " . $rowGrafico['valor_total'] . ")',";
                $dataComissao.= "'" . $rowGrafico['valor_total'] . "',";
            }
            if ($dataMeses) {
                $dataMeses = substr($dataMeses, 0, -1);
                $dataComissao = substr($dataComissao, 0, -1);
            }

            if ($dataComissao) {
                ?>

                <!-- BEGIN : ECHARTS -->
                <div class="row">
                    <div class="col-md-12">
                        <div class="panel panel-default">
                            <div class="panel-heading">
                                <div class="caption">
                                    <i class="fa fa-bar-chart" aria-hidden="true"></i>
                                    <span class="">Comissões</span>
                                </div>							
                            </div>
                            <div class="portlet-body">
                                <div id="echarts_bar" style="height:500px;"></div>
                            </div>
                        </div>
                    </div>
                </div>
                <script>
				
                    $(function () {

                        // ECHARTS
                        require.config({
                            paths: {
                                echarts: 'js/plugins/echarts/'
                            }
                        });

                        // DEMOS
                        require(
                                [
                                    'echarts',
                                    'echarts/chart/bar',
                                    'echarts/chart/chord',
                                    'echarts/chart/eventRiver',
                                    'echarts/chart/force',
                                    'echarts/chart/funnel',
                                    'echarts/chart/gauge',
                                    'echarts/chart/heatmap',
                                    'echarts/chart/k',
                                    'echarts/chart/line',
                                    'echarts/chart/map',
                                    'echarts/chart/pie',
                                    'echarts/chart/radar',
                                    'echarts/chart/scatter',
                                    'echarts/chart/tree',
                                    'echarts/chart/treemap',
                                    'echarts/chart/venn',
                                    'echarts/chart/wordCloud'
                                ],
                                function (ec) {
                                    //--- BAR ---
                                    var myChart = ec.init(document.getElementById('echarts_bar'));
                                    myChart.setOption({
                                        tooltip: {
                                            trigger: 'axis'
                                        },
                                        legend: {
                                            // data: ['Cost', 'Expenses']
                                            data: ['Comissão']
                                        },
                                        toolbox: {
                                            show: true,
                                            feature: {
                                                mark: {
                                                    show: true
                                                },
                                                magicType: {
                                                    show: true,
                                                    type: ['line', 'bar']
                                                },
                                                restore: {
                                                    show: true
                                                },
                                                saveAsImage: {
                                                    show: true
                                                }
                                            }
                                        },
                                        calculable: true,
                                        xAxis: [{
                                                type: 'category',
                                                data: [<?php echo $dataMeses ?>]
                                            }],
                                        yAxis: [{
                                                type: 'value',
                                                splitArea: {
                                                    show: true
                                                }
                                            }],
                                        series: [{
                                                name: 'Comissão',
                                                type: 'bar',
                                                data: [<?php echo $dataComissao ?>]
                                            }
                                            // , {
                                            // name: 'Expenses',
                                            // type: 'bar',
                                            // data: [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3]
                                            // }
                                        ]
                                    });
                                }
                        );
                    });

                </script>
                <?php
            }
        }
        ?>

        <?php
        break;

    case 'Leitura':
    case 'LeituraParcial':

        // $nivel_necessario = 4;
        $nivel_bloqueado = 5;


        // Verifica se não há a variável da sessão que identifica o usuário
        if (!isset($_SESSION['UsuarioID']) OR ( $_SESSION['UsuarioNivel'] == $nivel_bloqueado)) {
            // Destrói a sessão por segurança
            session_destroy();
            // Redireciona o visitante de volta pro login
            header("Location: index.php");
            exit;
        }

        require_once("db.php");

        $idPais = $_REQUEST['idPais'];

 

        if ($_SESSION['UsuarioNivel'] == 3 || $_SESSION['UsuarioNivel'] == 4) {

            //se deseja ver apenas leitura parcial
            if ($id_tela == 'LeituraParcial') {
                $titleConcat = '(<font color="red">Leitura Parcial</font>)';
            } else {
                $titleConcat = '(<font color="red">Leitura Acumulada</font>)';
            }
        }

        if ($_SESSION['UsuarioNivel'] <= 2) {

            $queryMoeda = "SELECT a.moeda_sigla
							FROM regiao a
							WHERE 
							a.id_pais = '$idPais'
							AND a.status = 1";
            $resultMoeda = mysql_query($queryMoeda);
            $rowList = mysql_fetch_array($resultMoeda);

            //buscar a cifra refente ao pais consultado
            $_SESSION['cifraoMoeda'] = $rowList['moeda_sigla'];
        }
        ?>
        <div class="panel-heading" style="min-height: 60px" >
            <strong>Painel Administrativo <?php echo $titleConcat ?></strong>
            <?php if ($_SESSION['UsuarioNivel'] <= 2) { ?>

                <div class="pull-right">	
                    <form role="form" method="POST" id="frmFecharFaturasCliente" class="form-horizontal" >
                        <div class="input-group">
                            <select name="idPais" id="idPais" class="form-control" required onchange="fLoadOptionScriptLeitura('Leitura', this.value)" >

                                <?php
                                $queryList = "SELECT a.id_pais, a.nome_pais, a.moeda_sigla
												FROM regiao a
												WHERE a.status = 1";
                                $resultList = mysql_query($queryList);

                                while ($rowList = mysql_fetch_array($resultList)) {
                                    if ($_REQUEST['idPais'] == $rowList['id_pais']) {
                                        $selecionado = 'selected';
                                    } else {
                                        $selecionado = '';
                                    }
                                    ?>
                                    <option <?php echo $selecionado ?> value ="<?php echo $rowList['id_pais'] ?>" ><?php echo $rowList['nome_pais'] ?></option>
                                    <?php
                                }
                                ?>
                            </select>					   
                        </div>
                    </form>
                </div>
                <?php
            }
            ?>
        </div>

        <!-- /.col-lg-12 -->
        <?php include 'zerar_modal.php'; ?>
        <?php include 'gerar_modal.php'; ?>

        <div class="panel-body">

            <!-- /.row -->
            <?php
            $first_quadrante = 'Locação a pagar';

            $queryCofig = "SELECT data_corte data FROM user WHERE id = " . $_SESSION['UsuarioID'] . "";
            $result3 = mysql_query($queryCofig);
            $rowc = mysql_fetch_array($result3);

            if ($_SESSION['UsuarioNivel'] == 1) {
                $first_quadrante = 'Comissão Clientes';
                //nova query para trazer os valores de comissão por Pais selecionado
//                $queryTop = "SELECT SUM(comissao_locacao) locacao,SUM(comissao_dono) dono, 
//                             SUM(comissao_ponto) ponto, SUM(saldo_total) saldo ,c.id_apoio ,acerto
//									FROM metricas a, ponto b, tablet c, user d, regiao e,cobranca_agregado ca, (
//										SELECT MAX(id) id
//										FROM metricas
//										GROUP BY idprod
//										ORDER BY id
//									) mx
//									WHERE 
//									a.idprod = c.idprod 
//									AND c.id_ponto = b.id 
//                                                                        AND ca.id_cobranca = a.id_cobranca 
//									AND a.id = mx.id
//									AND d.username = c.cliente
//									AND e.id_pais = d.id_pais
//									AND d.id_pais = '$idPais'
//									AND ca.lote_fechamento_hash IS NULL ";
//                $queryTop = "SELECT SUM(comissao_locacao) AS locacao, SUM(comissao_dono) AS dono, SUM(comissao_ponto) AS ponto, SUM(saldo_total) AS saldo
//								FROM metricas a
//								INNER JOIN tablet b ON b.idprod = a.idprod
//								INNER JOIN user c ON c.username = b.cliente
//								WHERE
//								a.dataorder > '$rowc[data]' 
//								AND a.ativo = 1 
//								AND b.ativo = 1
//								AND c.id_pais = '$idPais'
//								#AND a.status_leitura <> 2
//								#AND a.status <> 0
//								AND a.disponivel_painel_admin = 1";
                // Versão atual do android
//                $queryVersion = "SELECT versao FROM configuracao";
//                $resVersion = mysql_query($queryVersion);
//                $rowVersion = mysql_fetch_array($resVersion);
            } elseif ($_SESSION['UsuarioNivel'] == 2) {

                // $queryTop = "SELECT SUM(comissao_locacao) locacao,SUM(comissao_dono) dono, SUM(comissao_ponto) ponto, SUM(saldo_total) saldo 
                // FROM metricas c, tablet b, user a 
                // WHERE 
                // c.idprod = b.idprod 
                // AND b.cliente = a.username 
                // AND a.id_apoio = '$_SESSION[UsuarioID]' 		
                // AND c.dataorder > '$rowc[data]' 
                // AND c.ativo = 1 
                // AND b.ativo = 1


//                $queryTop = "SELECT SUM(comissao_locacao) AS locacao, SUM(comissao_dono) AS dono, SUM(comissao_ponto) AS ponto, SUM(saldo_total) AS saldo
//								FROM metricas a
//								INNER JOIN tablet b ON b.idprod = a.idprod
//								INNER JOIN user c ON c.username = b.cliente
//								WHERE
//								a.dataorder > '$rowc[data]' 
//								AND a.ativo = 1 
//								AND b.ativo = 1
//								AND c.afiliado = 1
//								AND c.id_pais = '$idPais'
//								AND a.status_leitura <> 2
//								AND a.status <> 0";

                // Versão atual do android
//                $queryVersion = "SELECT versao FROM configuracao";
//                $resVersion = mysql_query($queryVersion);
//                $rowVersion = mysql_fetch_array($resVersion);
            } elseif ($_SESSION['UsuarioNivel'] == 3) {
                $apoios = getApoios($_SESSION[UsuarioID]);
                //se deseja ver apenas leitura parcial
//                       if ($idPais == 33) {
//                            /**
//                             * BRASIL
//                             */
//                            $queryTop = "SELECT ca.id_cobranca,sum(comissao_locacao) locacao,sum(comissao_dono) dono, "
//                                    . " sum(comissao_ponto) ponto, sum(saldo_total) saldo "
//                                    . " FROM metricas,  tablet , cobranca_agregado ca "
//                                    . " WHERE metricas.idprod = tablet.idprod "
//                                    . " AND tablet.id_apoio IN (" . implode(',', $apoios) . ")  "
//                                  //  . " AND tablet.id_apoio = user.id  "
//                                    . " AND ca.id_cobranca = metricas.id_cobranca "
//                                  //  . " AND metricas.dataorder > '$rowc[data]' "
//                                    . " AND metricas.ativo = 1 "
//                                    . " AND ( (metricas.status_leitura  = 2  "
//                                    . "        AND ca.lote_fechamento_hash IS NOT NULL AND metricas.status = 0)"
//                                    . "        OR "
//                                    . "       (metricas.status_leitura <> 2  "
//                                    . "        AND ca.lote_fechamento_hash IS NULL AND metricas.status <> 0) ) "
//                                    . " AND metricas.cliente_fechamento IS NULL"
//                                    . "  ";
//                            
//                        } else {
//                                $queryTop = "SELECT SUM(comissao_locacao) locacao,SUM(comissao_dono) dono, "
//                                        . " SUM(comissao_ponto) ponto, SUM(saldo_total) saldo "
//                                        . " FROM metricas, tablet WHERE metricas.idprod = tablet.idprod "
//                                        . " AND tablet.id_apoio IN ( " . implode(',', $apoios) . ")"
//                                        . " AND metricas.dataorder > '$rowc[data]' 
//                                            AND metricas.ativo = 1 
//                                            AND tablet.ativo = 1 
//                                            AND metricas.status_leitura <> 2
//                                            AND metricas.status <> 0";
//                            }
            } elseif ($_SESSION['UsuarioNivel'] == 4) {

               
//                $queryu = "SELECT porcentagem FROM user WHERE id =  " . $_SESSION['UsuarioID'];
//                $result = mysql_query($queryu);
//                $rowU = mysql_fetch_array($result);

                //se deseja ver apenas leitura parcial
                if ($id_tela == 'LeituraParcial') {
//                    if ($rowU['porcentagem'] <> 0) {
//                        $colunm_locacao = "  IFNULL(round(SUM((select porcentagem from user where id = " . $_SESSION['UsuarioID'] . ") /100 * a.acerto)),0) locacao";
//                    } else {
//                        $colunm_locacao = " IFNULL(SUM(c.comissao_locacao),0) AS locacao";
//                    }

//                    $queryTop = "SELECT $colunm_locacao, SUM(c.comissao_dono) dono, SUM(c.comissao_ponto) ponto, SUM(c.saldo_total) saldo
//									FROM metricas a, tablet b, metrica_parcial c
//									WHERE 
//									a.idprod = b.idprod 
//									AND b.id_apoio = '$_SESSION[UsuarioID]' 
//									AND a.dataorder > '$rowc[data]' 
//									AND a.ativo = 1 
//									AND b.ativo = 1
//									AND c.id_metrica_fk = a.id
//									AND c.data_zerou_parcial IS NULL
//									AND a.status_leitura <> 2
//									AND a.status <> 0";
                } else {
//                    if ($rowU['porcentagem'] <> 0) {
//                        $colunm_locacao = "  IFNULL(round(SUM((select porcentagem from user where id = " . $_SESSION['UsuarioID'] . ") /100 * metricas.acerto)),0) locacao";
//                    } else {
//                        $colunm_locacao = " IFNULL(SUM(metricas.comissao_locacao),0) AS locacao";
//                    }
//                    $queryTop = "SELECT $colunm_locacao,SUM(comissao_dono) dono, SUM(comissao_ponto) ponto, "
//                            . " SUM(saldo_total) saldo FROM metricas, tablet "
//                            . " WHERE metricas.idprod = tablet.idprod "
//                            . " AND tablet.id_apoio = " . $_SESSION['UsuarioID'] . " "
//                            . " AND metricas.dataorder > '$rowc[data]' "
//                            . " AND metricas.ativo = 1 "
//                            . " AND tablet.ativo = 1 "
//                            . " AND metricas.status_leitura <> 2 "
//                            . " AND metricas.status <> 0";
                }
            } elseif ($_SESSION['UsuarioNivel'] == 6) {
                
//                 if ($idPais == 33) {
                     /**
                      * BRASIL
                      */
//                        $queryTop = "SELECT SUM(comissao_locacao) locacao,SUM(comissao_dono) dono, "
//                            . " SUM(comissao_ponto) ponto, SUM(saldo_total) saldo "
//                            . " FROM metricas, tablet, user a , cobranca_agregado ca"
//                            . " WHERE metricas.idprod = tablet.idprod "
//                            . " AND tablet.id_ponto = a.id_apoio "
//                            . " AND a.id = " . $_SESSION['UsuarioID']
//                            . " AND metricas.dataorder > '$rowc[data]' "
//                            . " AND metricas.ativo = 1 "
//                            . " AND ( (metricas.status_leitura  = 2  "
//                            . "        AND ca.lote_fechamento_hash IS NOT NULL AND metricas.status = 0)"
//                            . "        OR "
//                            . "       (metricas.status_leitura <> 2  "
//                            . "        AND ca.lote_fechamento_hash IS NULL AND metricas.status <> 0) ) "
//                            . " AND metricas.cliente_fechamento IS NULL"
//                            . " GROUP BY ca.id_cobranca";
        
//                    } else {
//                           $queryTop = "SELECT SUM(comissao_locacao) locacao,SUM(comissao_dono) dono, "
//                            . " SUM(comissao_ponto) ponto, SUM(saldo_total) saldo "
//                            . " FROM metricas, tablet, user a "
//                            . " WHERE metricas.idprod = tablet.idprod "
//                            . " AND tablet.id_ponto = a.id_apoio "
//                            . " AND a.id = " . $_SESSION['UsuarioID']
//                            . " AND metricas.dataorder > '$rowc[data]' "
//                            . " AND metricas.ativo = 1 "
//                            . " AND tablet.ativo = 1"
//                            . " AND metricas.status_leitura <> 2"
//                            . " AND metricas.status <> 0";
//                    }
            } else {

//                $queryTop = "SELECT SUM(comissao_locacao) locacao,SUM(comissao_dono) dono, SUM(comissao_ponto) ponto, SUM(saldo_total) saldo FROM metricas, tablet WHERE metricas.idprod = tablet.idprod AND tablet.id_apoio = " . $_SESSION['UsuarioApoio'] . " AND metricas.dataorder > '$rowc[data]' AND metricas.ativo = 1 AND tablet.ativo = 1
//									AND metricas.status_leitura <> 2
//									AND metricas.status <> 0";
            }

//            $result1 = mysql_query($queryTop);
//            $row = mysql_fetch_array($result1);
//            $totallocacao = $row['locacao'];
//            $totaldev = $row['locacao'] * 0.50;
//            $totalsistem = $row['locacao'] * 0.50;
//            $totaldono = $row['dono'];
//            $totalponto = $row['ponto'];
//            $totalsaldo = $row['saldo']; //($totallocacao+$totaldono+$totalponto); //

//            if ($_SESSION['UsuarioNivel'] == 4 && $rowU['porcentagem'] <> 0) {
//                /**
//                 * SÓCIO
//                 */
//               // $totaldono = $totalsaldo -($totallocacao + $totalponto);
//            }

            //if ($_SESSION['UsuarioNivel'] == 1) {
                /**
                 * ADMIN
                 */
//                $comissao_socio = 0;
           // $totallocacao = $row['dono'] + $comissao_socio ;
           // $totaldono = $row['locacao'];
                //$totalsaldo +=$comissao_socio;
           // }

            if ($id_tela == 'LeituraParcial') {
                if ($totallocacao <= 0) {
                    $disableButtonLeitura = 'disabled';
                } else {
                    $disableButtonLeitura = '';
                }
            } else {
                $disableButtonLeitura = 'disabled';
            }

            if (empty($row['dono'])) {
               // $totaldono = 0;
                //$totalponto = 0;
                //$totalsaldo = 0;
                //$totallocacao = 0;
            }
            if ($_SESSION['UsuarioNivel'] == 3) {
                $with_quadrante = '20%';
                $with_quadrante = '2';
            }else {
                $with_quadrante = '25%';
                $with_quadrante = '3';
            }
            ?>

            <div class="row">
                <div id="leituraTopo">

                    <?php if ($_SESSION['UsuarioNivel'] < 6) { ?>

                        <div class="col-lg-<?= $with_quadrante?>" >
                            <div class="panel panel-info">
                                <div class="panel-heading">
                                    <div class="row">
                                        <div class="col-xs-3">
                                            <i class="fa fa-tablet fa-3x"></i>
                                        </div>
                                        <div class="col-lg-9 text-center">
                                            <p class="announcement-text"><?= $first_quadrante ?></p>
                                        </div>
                                        <div class="col-lg-9 text-center">
                                            <p class="announcement-heading-text"><h3><?php echo $_SESSION['cifraoMoeda']  /*$totallocacao*/ ; ?></h3></p>
                                        </div>
                                    </div>
                                </div>

                            </div>
                        </div>			

                        <div class="col-lg-<?= $with_quadrante?>">
                            <div class="panel panel-success">
                                <div class="panel-heading">
                                    <div class="row">
                                        <div class="col-xs-3">
                                            <i class="fa fa-user fa-3x"></i>
                                        </div>
                                        <div class="col-lg-9 text-center">
                                            <p class="announcement-text">Minha Comissão</p>
                                        </div>
                                         <div class="col-lg-9 text-center">
                                            <p class="announcement-heading-text"><h3><?php echo $_SESSION['cifraoMoeda'] /*. $totaldono*/; ?></h3></p>
                                        </div>
                                    </div>
                                </div>

                            </div>
                        </div>
                        <?php
                    }
                    ?>
                    <?php if ($_SESSION['UsuarioNivel'] == 3) { ?>
                    <div class="col-lg-<?= $with_quadrante?>">
                        <div class="panel panel-warning">
                            <div class="panel-heading">
                                <div class="row">
                                    <div class="col-xs-3">
                                        <i class="fa fa-user fa-3x"></i>
                                    </div>
                                    <div class="col-lg-9 text-center">
                                        <p class="announcement-text"><?= 'Comissão Sócio' ?></p>
                                    </div>
                                    <div class="col-lg-9 text-center">
                                        <p class="announcement-heading-text"><h3><?php echo $_SESSION['cifraoMoeda']; ?></h3></p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                     <?php } ?>

                    <div class="col-lg-<?= $with_quadrante?>">
                        <div class="panel panel-danger">
                            <div class="panel-heading">
                                <div class="row">
                                    <div class="col-xs-3">
                                        <i class="fa fa-home fa-3x"></i>
                                    </div>
                                    <div class="col-lg-9 text-center">
                                        <p class="announcement-text">Comissão Pontos</p>
                                    </div>
                                    <div class="col-lg-9 text-center">
                                       <p class="announcement-heading-text"><h3><?php echo $_SESSION['cifraoMoeda'] /*. $totalponto*/ ; ?></h3></p>
                                    </div>
                                </div>
                            </div>

                        </div>
                    </div>

                    <div class="col-lg-<?= $with_quadrante?>">
                        <div class="panel panel-info">
                            <div class="panel-heading">
                                <div class="row">
                                    <div class="col-xs-3">
                                        <i class="fa fa-adjust fa-3x"></i>
                                    </div>
                                    <div class="col-lg-9 text-center">
                                        <p class="announcement-text">Total de Saldos</p>
                                    </div>
                                    <div class="col-lg-9 text-center">
                                        <p class="announcement-heading-text"><h3><?php echo $_SESSION['cifraoMoeda'] /*. $totalsaldo */; ?></h3></p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div><!-- /.row -->

            <div class="row">

                <?php
                
                if ($_SESSION['UsuarioNivel'] <> 6) {
                    

                    $myfile = fopen('update/' . 'changelog.txt', "r") or die("Impossível abrir o ficheiro changelog.txt!");
                    $lines = count(file('update/' . 'changelog.txt'));
                    $quebra = explode(PHP_EOL, fread($myfile, filesize('update/' . 'changelog.txt')));
                    $changelog = explode(":", $quebra[$lines - 1]);
                    fclose($myfile);
                    
                    ?>  
                    <div class="panel-body">
                        <form role="form" id="frmVersaoApk" method="POST">
                            <div class="row">
                                <div class="col-lg-3"> 
                                    <div class="input-group custom-search-form" style="">
                                        <span class="input-group-addon">Versão APK</span>
                                        <input type="text" maxlength="5"  name="versao" id="versao" class="form-control text-center" value="<?php echo $changelog[1] ?>" <?php echo ($_SESSION['UsuarioNivel'] <> 1) ? 'readonly' : ''; ?>>
                                    </div>
                                </div>
                                <div class="col-lg-3"> 
                                    <div class="input-group custom-search-form" style="">
                                        <span class="input-group-addon">Nome APK</span>
                                        <input type="text" maxlength="50" style="font-size: 12px"  name="nome" class="form-control text-left" value="<?php echo $changelog[0] ?>" readonly="">
                                    </div>
                                </div>
                                <div class="col-lg-3" style="margin-left:-3px;"> 
                                    <div class="input-group custom-search-form" style="margin-bottom: 5px;">
                                        <span class="input-group-addon">Data APK</span>
                                        <input type="text" maxlength="10"  name="data" class="form-control text-center" value="<?php echo $changelog[2] ?>" readonly="">
                                    </div>
                                </div>
                                <div> 
                                    <?php
                                    
                                    if (($_SESSION['UsuarioNivel'] != 6) && ($_SESSION['UsuarioNivel'] != 2)) {
                                        $fileAPK = array_map('basename', glob('./update/' . "*.{apk}", GLOB_BRACE))[0];
                                        if ($fileAPK) {
                                            $nomeArquivoApk = 'http://' . $_SERVER['HTTP_HOST'] . str_replace($_SERVER['DOCUMENT_ROOT'], '', dirname($_SERVER['SCRIPT_FILENAME'])) . '/update/' . $fileAPK;
                                        }
                                        ?>	

                                        <div class="col-lg-3">
                                            <a href="<?php echo $nomeArquivoApk ?>"  class="list-group-item btn btn-green btn-block" >
                                                <i class="fa fa-cloud-download" aria-hidden="true"></i> Baixar APK do Jogo
                                <!--                            <span class="pull-right text-muted small"><em>Download</em></span>-->
                                            </a>
                                        </div>
                                        <?php
                                    }
                                    ?>
                                </div>
                            </div>
                            <?php
                            
                            if ($_SESSION['UsuarioNivel'] == 1) {
                                ?>
                                <div class="row">
                                    <div class="col-lg-9"> 
                                        <div class="input-group custom-search-form" style="margin-bottom: 5px;">
                                            <span class="input-group-addon">Changelog</span>
                                            <textarea name="changelog" class="form-control text-left" rows="2" cols="50"><?php echo str_replace(",", PHP_EOL, $changelog[3]) ?></textarea> 
                                        </div>
                                    </div>
                                    <div class="text-right col-sm-3" style="margin-top:15px">
                                        <span class="input-group-btn">
                                            <button class="btn btn-block" style="" id="btnAtualizaVersaoApk" type="submit">
                                                <i class="fa fa-refresh"></i>
                                            </button>
                                        </span>
                                    </div>
                                </div>
                            </form>
                        </div>
                        <?php
                    }
                }
                ?>

                <?php
                
                require_once './sealed/utils/FUNCOES.php';
               
                //opção de zerar leitura parcial, disponivel para clientes
                if ($_SESSION['UsuarioNivel'] == 'nenhum') {

                    if ($id_tela == 'LeituraParcial') {
                        ?>				

                        
                        <?php
                    }
                    if ($id_tela == 'Leitura') {
                        ?>			  
                        <div class="row">
                            <div class="col-lg-3">
                                <a href="javascript: void(0);"	onclick="fLoadOptionScriptLeitura('LeituraParcial', '<?php echo $_SESSION['pais'] ?>')" class='btn btn-brown btn-block' role='button'><i class="fa fa-info" aria-hidden="true"></i>&nbsp; Ver Leitura Parcial</a> 
                            </div>
                        </div>

                    <?php } else {
                        ?>			   
                        <div class="row">
                            <div class="col-lg-3">
                                <a href="javascript: void(0);"	onclick="fLoadOptionScriptLeitura('Leitura', '<?php echo $_SESSION['pais'] ?>')" class='btn btn-green btn-block' role='button' ><i class="fa fa-info-circle" aria-hidden="true"></i>&nbsp; Ver Leitura Acumulada</a> 
                            </div>
                        </div>
                        <?php
                    }
                }
                //echo $_SESSION['pais'];
                ?> 						
            </div><!-- /.row -->

            <br>

            <!-- Consulta de Métricas -- >
            <?php
             
            if ($_SESSION['UsuarioNivel'] == 1) {

                $queryList = "SELECT nome, username FROM user WHERE nivel = 3 ORDER BY nome DESC";

                $arrayMetricas = array();
                $query0 = "SELECT MAX(id) id FROM metricas GROUP BY idprod";
                $result = mysql_query($query0);
                while($rowU = mysql_fetch_array($result)){
                    $arrayMetricas[] = $rowU['id'];
                }
                //AND a.status_leitura <> 2 AND a.status <> 0
                if ($idPais == 33){
                $queryResumo = "SELECT a.id AS id, b.nome AS nome, c.idprod, c.cliente, comissao_dono, comissao_locacao, comissao_ponto, acerto, saldo_total AS saldo, 
										DATE_FORMAT(a.dataorder,'%d/%m/%Y %H:%i') AS dataorder, d.id_pais, e.moeda_sigla,c.id_apoio
										FROM metricas a, ponto b, tablet c, user d, regiao e, cobranca_agregado ca
									WHERE a.idprod = c.idprod 
									AND c.id_ponto = b.id 
                                                                        AND ca.id_cobranca = a.id_cobranca 
                                                                        AND a.id IN (" . implode(',', $arrayMetricas) . ")
									AND d.username = c.cliente
									AND e.id_pais = d.id_pais
									AND d.id_pais = '$idPais'"
                                                                       . " AND a.dataorder > '".date("Y-m-01 00:00:00")."' "
                                                                       .FUNCOES::returnSqlStatus('a', 'BR');
                $query = "SELECT a.id AS id, c.cliente AS nome, c.idprod, comissao_dono, comissao_locacao, comissao_ponto, acerto, saldo_total AS saldo, 
									DATE_FORMAT(a.dataorder,'%d/%m/%Y %H:%i') dataorder, d.id_pais, e.moeda_sigla ,c.id_apoio
									FROM metricas a, ponto b, tablet c, user d, regiao e,cobranca_agregado ca
									WHERE 
									a.idprod = c.idprod 
									AND c.id_ponto = b.id 
                                                                        AND ca.id_cobranca = a.id_cobranca 
                                                                        AND a.id IN (" . implode(',', $arrayMetricas) . ")
									AND d.username = c.cliente
									AND e.id_pais = d.id_pais
									AND d.id_pais = '$idPais'"
                                                                        . " AND a.dataorder > '".date("Y-m-01 00:00:00")."' "
								        .FUNCOES::returnSqlStatus('a', 'BR');
                }else{
                    
                    $queryResumo = "SELECT a.id AS id, b.nome AS nome, c.idprod, c.cliente, comissao_dono, comissao_locacao, comissao_ponto, acerto, saldo_total AS saldo, 
										DATE_FORMAT(a.dataorder,'%d/%m/%Y %H:%i') AS dataorder, d.id_pais, e.moeda_sigla,c.id_apoio
										FROM metricas a, ponto b, tablet c, user d, regiao e, cobranca_agregado ca
									WHERE a.idprod = c.idprod 
									AND c.id_ponto = b.id 
                                                                        AND ca.id_cobranca = a.id_cobranca 
                                                                        AND a.id IN (" . implode(',', $arrayMetricas) . ")
									AND d.username = c.cliente
									AND e.id_pais = d.id_pais
									AND d.id_pais = '$idPais'"
                                                                        .FUNCOES::returnSqlStatus('a')."
                                                                        AND a.dataorder > '".date("Y-m-01 00:00:00")."' 
                                                                        ";
                $query = "SELECT a.id AS id, c.cliente AS nome, c.idprod, comissao_dono, comissao_locacao, comissao_ponto, acerto, saldo_total AS saldo, 
									DATE_FORMAT(a.dataorder,'%d/%m/%Y %H:%i') dataorder, d.id_pais, e.moeda_sigla ,c.id_apoio
									FROM metricas a, ponto b, tablet c, user d, regiao e,cobranca_agregado ca
									WHERE 
									a.idprod = c.idprod 
									AND c.id_ponto = b.id 
                                                                        AND ca.id_cobranca = a.id_cobranca 
                                                                        AND a.id IN (" . implode(',', $arrayMetricas) . ")
									AND d.username = c.cliente
									AND e.id_pais = d.id_pais
									AND d.id_pais = '$idPais'"
                                                                        .FUNCOES::returnSqlStatus('a')."
                                                                        AND a.dataorder > '".date("Y-m-01 00:00:00")."'
									";
                    
                }
             

//                $queryFatura = "SELECT tablet.cliente nome,MAX(metricas.id) numero,"
//                        . " MAX(DATE_ADD(expiracao,INTERVAL validade DAY)) data FROM metricas, "
//                        . " tablet "
//                        . " WHERE metricas.status = 1 "
//                        . " AND metricas.idprod = tablet.idprod "
//                        . " AND DATEDIFF((DATE_ADD(expiracao,INTERVAL validade DAY)),SYSDATE()) <= 0 "
//                        . " AND status_leitura = 1 "
//                        . " GROUP BY tablet.cliente "
//                        . " ORDER BY data DESC";
            } elseif ($_SESSION['UsuarioNivel'] == 2) {

                $queryList = "SELECT nome, username FROM user a WHERE nivel = 3 AND a.id_apoio = " . $_SESSION['UsuarioID'] . " ORDER BY nome DESC";

                // $queryResumo= "select metricas.id id,ponto.nome nome,tablet.idprod ,tablet.cliente,comissao_dono,comissao_locacao ,comissao_ponto, acerto, saldo_total saldo, DATE_FORMAT(metricas.dataorder,'%d/%m/%Y %H:%i') dataorder from metricas,ponto,tablet,user a, (select MAX(id) id from metricas group by idprod) mx WHERE metricas.idprod = tablet.idprod AND tablet.id_ponto = ponto.id AND tablet.cliente = a.username AND a.id_apoio = ". $_SESSION['UsuarioID'] ." AND metricas.ID = mx.id";

                $queryResumo = "SELECT a.id AS id, b.nome AS nome, c.idprod, c.cliente, comissao_dono, comissao_locacao, comissao_ponto, acerto, saldo_total AS saldo, 
										DATE_FORMAT(a.dataorder,'%d/%m/%Y %H:%i') AS dataorder, d.id_pais, e.moeda_sigla ,tablet.id_apoio
										FROM metricas a, ponto b, tablet c, user d, regiao e, (
										SELECT MAX(id) id
										FROM metricas
										GROUP BY idprod
									) mx
									WHERE a.idprod = c.idprod 
									AND c.id_ponto = b.id 
									AND a.id = mx.id
									AND d.username = c.cliente
									AND e.id_pais = d.id_pais
									AND d.id_pais = '$idPais'
									AND d.id_apoio = '$_SESSION[UsuarioID]'
									AND a.status_leitura <> 2
									AND a.status <> 0";

                // $query = "SELECT metricas.id id,tablet.cliente nome,tablet.idprod ,comissao_dono,comissao_locacao ,comissao_ponto, acerto, saldo_total saldo, DATE_FORMAT(metricas.dataorder,'%d/%m/%Y %H:%i') dataorder  FROM metricas,ponto,tablet,user a, (select MAX(id) id from metricas group by idprod ORDER BY metricas.id) mx WHERE metricas.idprod = tablet.idprod AND tablet.id_ponto = ponto.id AND tablet.cliente = a.username AND a.id_apoio = ". $_SESSION['UsuarioID'] ." AND metricas.id = mx.id";

                $query = "SELECT a.id AS id, c.cliente AS nome, c.idprod, comissao_dono, comissao_locacao, comissao_ponto, acerto, saldo_total AS saldo, 
									DATE_FORMAT(a.dataorder,'%d/%m/%Y %H:%i') dataorder, d.id_pais, e.moeda_sigla , tablet.id_apoio
									FROM metricas a, ponto b, tablet c, user d, regiao e, (
										SELECT MAX(id) id
										FROM metricas
										GROUP BY idprod
										ORDER BY id
									) mx
									WHERE 
									a.idprod = c.idprod 
									AND c.id_ponto = b.id 
									AND a.id = mx.id
									AND d.username = c.cliente
									AND e.id_pais = d.id_pais
									AND d.id_pais = '$idPais'
									AND d.id_apoio = '$_SESSION[UsuarioID]'
									AND a.status_leitura <> 2
									AND a.status <> 0";

               // $queryFatura = "SELECT tablet.cliente nome,MAX(metricas.id) numero, MAX(DATE_ADD(tablet.expiracao,INTERVAL tablet.validade DAY)) data FROM metricas, tablet, user a WHERE metricas.status = 1 AND metricas.idprod = tablet.idprod AND tablet.cliente = a.username AND a.id_apoio = " . $_SESSION['UsuarioID'] . " AND DATEDIFF((DATE_ADD(expiracao,INTERVAL validade DAY)),SYSDATE()) <= 0 AND status_leitura = 1 GROUP BY tablet.cliente ORDER BY data DESC";
            } elseif ($_SESSION['UsuarioNivel'] == 3) {

                $apoios = getApoios($_SESSION['UsuarioID']);
                
                $query0 = "SELECT MAX(id) id FROM metricas GROUP BY idprod";
                $result = mysql_query($query0);
                while($rowU = mysql_fetch_array($result)){
                    $arrayMetricas[] = $rowU['id'];
                }
                
                 $query = "SELECT metricas.id id,ponto.nome nome,tablet.idprod ,"
                        . " comissao_dono,comissao_locacao ,comissao_ponto, acerto, "
                        . " saldo_total saldo, DATE_FORMAT(metricas.dataorder,'%d/%m/%Y %H:%i') dataorder,tablet.id_apoio  "
                        . " FROM metricas,ponto,tablet,cobranca_agregado ca "
                        . " WHERE metricas.idprod = tablet.idprod "
                        . " AND tablet.id_ponto = ponto.id "
                        . " AND tablet.id_apoio IN (" . implode(',', $apoios) . ')'
                        . " AND metricas.id IN (" . implode(',', $arrayMetricas) . ')'
                        . " AND metricas.dataorder > '$rowc[data]' "
                        . " AND ca.id_cobranca = metricas.id_cobranca "
			. " AND ( (metricas.status_leitura  = 2  "
                        . "        AND ca.lote_fechamento_hash IS NOT NULL AND metricas.status = 0)"
                        . "        OR "
                        . "       (metricas.status_leitura <> 2  "
                        . "        AND ca.lote_fechamento_hash IS NULL AND metricas.status <> 0) ) "
                        . " AND metricas.cliente_fechamento IS NULL
				";
                 
                 $queryResumo = "SELECT a.id AS id, b.nome AS nome, c.idprod, c.cliente, comissao_dono, comissao_locacao, comissao_ponto, acerto, saldo_total AS saldo, 
                        DATE_FORMAT(a.dataorder,'%d/%m/%Y %H:%i') AS dataorder, d.id_pais, e.moeda_sigla,c.id_apoio
                        FROM metricas a, ponto b, tablet c, user d, regiao e, cobranca_agregado ca
                        WHERE a.idprod = c.idprod 
                        AND c.id_ponto = b.id 
                        AND ca.id_cobranca = a.id_cobranca 
                        AND a.id IN (" . implode(',', $arrayMetricas) . ")
                        AND d.username = c.cliente
                        AND e.id_pais = d.id_pais
                        AND c.id_apoio IN (" . implode(',', $apoios) . ')'
                       . " AND a.dataorder > '$rowc[data]' "
                       ." AND ( (a.status_leitura  = 2  "
                       . "        AND ca.lote_fechamento_hash IS NOT NULL AND a.status = 0)"
                       . "        OR "
                       . "       (a.status_leitura <> 2  "
                       . "        AND ca.lote_fechamento_hash IS NULL AND a.status <> 0) ) "
                       . " AND a.cliente_fechamento IS NULL";
                 
                if ($idPais != 33){
                    $query = "SELECT metricas.id id,ponto.nome nome,tablet.idprod ,"
                        . " comissao_dono,comissao_locacao ,comissao_ponto, acerto, "
                        . " saldo_total saldo, DATE_FORMAT(metricas.dataorder,'%d/%m/%Y %H:%i') dataorder,tablet.id_apoio  "
                        . " FROM metricas,ponto,tablet,cobranca_agregado ca"
                        . " WHERE metricas.idprod = tablet.idprod "
                        . " AND tablet.id_ponto = ponto.id "
                        . " AND tablet.id_apoio IN (" . implode(',', $apoios) . ')'
                        . " AND metricas.id IN (" . implode(',', $arrayMetricas) . ')'
                        . " AND metricas.dataorder > '$rowc[data]' "
                        . " AND ca.id_cobranca = metricas.id_cobranca "
			.FUNCOES::returnSqlStatus('metricas');
                    
                    $queryResumo = "SELECT a.id AS id, b.nome AS nome, c.idprod, c.cliente, comissao_dono, comissao_locacao, comissao_ponto, acerto, saldo_total AS saldo, 
                        DATE_FORMAT(a.dataorder,'%d/%m/%Y %H:%i') AS dataorder, d.id_pais, e.moeda_sigla,c.id_apoio
                        FROM metricas a, ponto b, tablet c, user d, regiao e, cobranca_agregado ca
                        WHERE a.idprod = c.idprod 
                        AND c.id_ponto = b.id 
                        AND ca.id_cobranca = a.id_cobranca 
                        AND a.id IN (" . implode(',', $arrayMetricas) . ")
                        AND d.username = c.cliente
                        AND e.id_pais = d.id_pais
                        AND c.id_apoio IN (" . implode(',', $apoios) . ')'
                        . " AND a.dataorder > '$rowc[data]' "
                        . FUNCOES::returnSqlStatus('a');
                }

                $queryList = "SELECT nome, nome username FROM ponto "
                        . " WHERE id_apoio IN (" . implode(',', $apoios) . ')'
                        . " ORDER BY nome DESC";
            } elseif ($_SESSION['UsuarioNivel'] == 4) {
                
             
                /**
                 * SÓCIO
                 */
                
                $queryu = "SELECT porcentagem FROM user WHERE id =  " . $_SESSION['UsuarioID'];
                $result = mysql_query($queryu) or die(mysql_errno());
                $rowU = mysql_fetch_array($result);
                
                
                if ($rowU['porcentagem'] <> 0) {
                    $colunm_locacao = " round((select porcentagem from user where id = " . $_SESSION['UsuarioID'] . ") /100 * acerto)comissao_locacao";
                } else {
                    $colunm_locacao = " comissao_locacao ";
                }
                 
                $query0 = "SELECT MAX(id) id FROM metricas GROUP BY idprod";
                $arrayMetricas = array();
                $result0 =  mysql_query($query0) or die(mysql_errno());
                
                while($rowX = mysql_fetch_array($result0)){
                    $arrayMetricas[] = $rowX['id'];
                }

                $queryList = "SELECT nome, nome username FROM ponto WHERE id_apoio = " . $_SESSION['UsuarioID'] . " ORDER BY nome DESC";

                $query = "SELECT metricas.id id,ponto.nome nome,tablet.idprod ,"
                        . " comissao_dono,$colunm_locacao ,comissao_ponto, acerto, "
                        . " saldo_total saldo, DATE_FORMAT(metricas.dataorder,'%d/%m/%Y %H:%i') dataorder,tablet.id_apoio  "
                        . " FROM metricas,ponto,tablet,cobranca_agregado ca "
                        . " WHERE metricas.idprod = tablet.idprod "
                        . " AND tablet.id_ponto = ponto.id "
                        . " AND tablet.id_apoio IN (" . $_SESSION['UsuarioID']. ')'
                        . " AND metricas.id IN (" . implode(',', $arrayMetricas) . ')'
                        . " AND metricas.dataorder > '$rowc[data]' "
                        . " AND ca.id_cobranca = metricas.id_cobranca "
			. " AND ( (metricas.status_leitura  = 2  "
                        . "        AND ca.lote_fechamento_hash IS NOT NULL AND metricas.status = 0)"
                        . "        OR "
                        . "       (metricas.status_leitura <> 2  "
                        . "        AND ca.lote_fechamento_hash IS NULL AND metricas.status <> 0) ) "
                        . " AND metricas.cliente_fechamento IS NULL
				";
                 
                 $queryResumo = "SELECT a.id AS id, b.nome AS nome, c.idprod, c.cliente, comissao_dono, comissao_locacao, comissao_ponto, acerto, saldo_total AS saldo, 
                        DATE_FORMAT(a.dataorder,'%d/%m/%Y %H:%i') AS dataorder, d.id_pais, e.moeda_sigla,c.id_apoio
                        FROM metricas a, ponto b, tablet c, user d, regiao e, cobranca_agregado ca
                        WHERE a.idprod = c.idprod 
                        AND c.id_ponto = b.id 
                        AND ca.id_cobranca = a.id_cobranca 
                        AND a.id IN (" . implode(',', $arrayMetricas) . ")
                        AND d.username = c.cliente
                        AND e.id_pais = d.id_pais
                        AND c.id_apoio = " . $_SESSION['UsuarioID'] 
                       . " AND a.dataorder > '$rowc[data]' "
                       . " AND ( (a.status_leitura  = 2  "
                       . "        AND ca.lote_fechamento_hash IS NOT NULL AND a.status = 0)"
                       . "        OR "
                       . "       (a.status_leitura <> 2  "
                       . "        AND ca.lote_fechamento_hash IS NULL AND a.status <> 0) ) "
                       . " AND a.cliente_fechamento IS NULL";
                 
                if ($idPais != 33){
                        $queryResumo = "select metricas.id id,ponto.nome nome,tablet.idprod ,tablet.cliente,comissao_dono,$colunm_locacao ,comissao_ponto, acerto, saldo_total saldo, DATE_FORMAT(metricas.dataorder,'%d/%m/%Y %H:%i') dataorder,tablet.id_apoio "
                                . " from metricas,ponto,tablet"
                                //. ", (select MAX(id) id from metricas group by idprod ORDER BY metricas.id) mx "
                                . " WHERE metricas.idprod = tablet.idprod "
                                . " AND tablet.id_ponto = ponto.id "
                                //. " AND metricas.ID = mx.id "
                                . " AND metricas.id IN (" . implode(',', $arrayMetricas) . ')'
                                . " AND tablet.id_apoio = " . $_SESSION['UsuarioID'] 
                                . " AND metricas.status_leitura <> 2 "
                                . " AND metricas.dataorder > '$rowc[data]' "
                                . " AND metricas.status <> 0";

                        $query = "SELECT metricas.id id,ponto.nome nome,tablet.idprod ,comissao_dono,$colunm_locacao ,"
                                . " comissao_ponto, acerto, saldo_total saldo, DATE_FORMAT(metricas.dataorder,'%d/%m/%Y %H:%i') dataorder,"
                                . "tablet.id_apoio  FROM metricas,ponto,tablet"
                                //. ",(select MAX(id) id from metricas group by idprod) mx "
                                . " WHERE metricas.idprod = tablet.idprod "
                                . " AND tablet.id_ponto = ponto.id "
                                . " AND tablet.id_apoio = " . $_SESSION['UsuarioID'] 
                                //. " AND metricas.id = mx.id "
                                . " AND metricas.id IN (" . implode(',', $arrayMetricas) . ')'
                                . " AND metricas.status_leitura <> 2 "
                                . " AND metricas.dataorder > '$rowc[data]' "
                                . " AND metricas.status <> 0 "
                               // . " ORDER BY mx.id DESC"
                                . "";
                }

               // $queryFatura = "SELECT ponto.nome nome,MAX(metricas.id) numero, MAX(DATE_ADD(expiracao,INTERVAL validade DAY)) data FROM metricas, tablet, ponto WHERE metricas.status = 1 AND metricas.idprod = tablet.idprod AND tablet.id_apoio = " . $_SESSION['UsuarioID'] . " AND tablet.id_ponto = ponto.id AND DATEDIFF((DATE_ADD(expiracao,INTERVAL validade DAY)),SYSDATE()) <= 0 AND status_leitura = 1 GROUP BY ponto.nome ORDER BY data DESC";
            } elseif ($_SESSION['UsuarioNivel'] == 6) {

                $queryList = "SELECT ponto.nome, ponto.nome username "
                        . " FROM ponto, user a "
                        . " WHERE ponto.id = a.id_apoio "
                        . " AND a.id = " . $_SESSION['UsuarioID'] . " ORDER BY nome DESC";
                
                $query0 = "SELECT MAX(id) id FROM metricas GROUP BY idprod";
                $result0 =  mysql_query($query0);
                while($rowX = mysql_fetch_array($result0)){
                    $arrayMetricas[] = $rowX['id'];
                }
                 $queryResumo = "select metricas.id id,ponto.nome nome,tablet.idprod ,"
                        . " tablet.cliente,comissao_dono,comissao_locacao ,comissao_ponto, "
                        . " acerto, saldo_total saldo, "
                        . " DATE_FORMAT(metricas.dataorder,'%d/%m/%Y %H:%i') dataorder,tablet.id_apoio"
                        . " FROM metricas,ponto,tablet,user a "
                        . " WHERE metricas.idprod = tablet.idprod "
                        . " AND tablet.id_ponto = ponto.id "
                        . " AND a.id IN (" . implode(',', $arrayMetricas) . ")"
                        . " AND ponto.id = a.id_apoio "
                        . " AND a.id = " . $_SESSION['UsuarioID']
                        . " AND a.dataorder > '".date("Y-m-01 00:00:00")."' "
                        . " AND ( (a.status_leitura  = 2  "
                        . "        AND ca.lote_fechamento_hash IS NOT NULL AND a.status = 0)"
                        . "        OR "
                        . "       (a.status_leitura <> 2  "
                        . "        AND ca.lote_fechamento_hash IS NULL AND a.status <> 0) ) "
                        . " AND a.cliente_fechamento IS NULL";
                

                 $query = "SELECT metricas.id id,ponto.nome nome,tablet.idprod ,comissao_dono,comissao_locacao ,"
                        . " comissao_ponto, acerto, saldo_total saldo, "
                        . " DATE_FORMAT(metricas.dataorder,'%d/%m/%Y %H:%i') dataorder,tablet.id_apoio"
                        . "    FROM metricas,ponto,tablet, user a , cobranca_agregado ca"
                        . " WHERE metricas.idprod = tablet.idprod "
                        . " AND tablet.id_ponto = ponto.id "
                        . " AND ponto.id = a.id_apoio "
                        . " AND ca.id_cobranca = metricas.id_cobranca "
                        . " AND a.id = " . $_SESSION['UsuarioID']  
                        . " AND metricas.dataorder > '".date("Y-m-01 00:00:00")."' "
                        . FUNCOES::returnSqlStatus('metricas')
                        . " ORDER BY metricas.id DESC";
                
                if ($idPais != 33){
                    $queryResumo = "select metricas.id id,ponto.nome nome,tablet.idprod ,"
                        . " tablet.cliente,comissao_dono,comissao_locacao ,comissao_ponto, "
                        . " acerto, saldo_total saldo, "
                        . " DATE_FORMAT(metricas.dataorder,'%d/%m/%Y %H:%i') dataorder,tablet.id_apoio"
                        . " FROM metricas,ponto,tablet,user a "
                        . " WHERE metricas.idprod = tablet.idprod "
                        . " AND tablet.id_ponto = ponto.id "
                       // . " AND metricas.id IN (" . implode(',', $arrayMetricas) . ")"
                        . " AND ponto.id = a.id_apoio "
                        . " AND a.id = " . $_SESSION['UsuarioID']
                        . " AND metricas.dataorder > '".date("Y-m-01 00:00:00")."' "
                        . " AND metricas.status_leitura <> 2 "
                        . " AND metricas.status <> 0";
//                 FUNCOES::logMsg($queryResumo, 'info');
                   
                        $query = "SELECT metricas.id id,ponto.nome nome,tablet.idprod ,comissao_dono,comissao_locacao ,"
                        . " comissao_ponto, acerto, saldo_total saldo, "
                        . " DATE_FORMAT(metricas.dataorder,'%d/%m/%Y %H:%i') dataorder,tablet.id_apoio"
                        . "    FROM metricas,ponto,tablet, user a , cobranca_agregado ca"
                        . " WHERE metricas.idprod = tablet.idprod "
                        . " AND tablet.id_ponto = ponto.id "
                        . " AND ponto.id = a.id_apoio "
                        . " AND ca.id_cobranca = metricas.id_cobranca "
                        . " AND a.id = " . $_SESSION['UsuarioID']  
                        . " AND metricas.dataorder > '".date("Y-m-01 00:00:00")."' "
                        . FUNCOES::returnSqlStatus('metricas');
                }

               // $queryFatura = "SELECT ponto.nome nome,MAX(metricas.id) numero, MAX(DATE_ADD(expiracao,INTERVAL validade DAY)) data FROM metricas, tablet, ponto, user a WHERE metricas.status = 1 AND metricas.idprod = tablet.idprod AND  tablet.id_ponto = ponto.id ponto.id = a.id_apoio AND a.id = " . $_SESSION['UsuarioID'] . " AND DATEDIFF((DATE_ADD(expiracao,INTERVAL validade DAY)),SYSDATE()) <= 0 AND status_leitura = 1 GROUP BY ponto.nome ORDER BY data DESC";
            } else {

                $queryList = "SELECT nome, nome username FROM ponto WHERE id_apoio = " . $_SESSION['UsuarioApoio'] . " ORDER BY nome DESC";

                $queryResumo = "select metricas.id id,ponto.nome nome,tablet.idprod ,tablet.cliente,comissao_dono,comissao_locacao ,comissao_ponto, acerto, saldo_total saldo, DATE_FORMAT(metricas.dataorder,'%d/%m/%Y %H:%i') dataorder,tablet.id_apoio from metricas,ponto,tablet, (select MAX(id) id from metricas group by idprod) mx WHERE metricas.idprod = tablet.idprod AND tablet.id_ponto = ponto.id AND metricas.ID = mx.id AND tablet.id_apoio = " . $_SESSION['UsuarioApoio'] . " 
			   AND metricas.status_leitura <> 2
				AND metricas.status <> 0";

                $query = "SELECT metricas.id id,ponto.nome nome,tablet.idprod ,comissao_dono,comissao_locacao "
                        . ",comissao_ponto, acerto, saldo_total saldo, "
                        . " DATE_FORMAT(metricas.dataorder,'%d/%m/%Y %H:%i') dataorder,tablet.id_apoio"
                        . " FROM metricas,ponto,tablet "
                        . " WHERE metricas.idprod = tablet.idprod AND tablet.id_ponto = ponto.id AND tablet.id_apoio = " . $_SESSION['UsuarioApoio'] . " 
			   AND metricas.status_leitura <> 2 AND metricas.status <> 0 ORDER BY metricas.id DESC";

                //$queryFatura = "SELECT ponto.nome nome,MAX(metricas.id) numero, MAX(DATE_ADD(expiracao,INTERVAL validade DAY)) data FROM metricas, tablet WHERE metricas.status = 1 AND metricas.idprod = tablet.idprod AND tablet.id_apoio = " . $_SESSION['UsuarioApoio'] . " AND tablet.id_ponto = ponto.id AND DATEDIFF((DATE_ADD(expiracao,INTERVAL validade DAY)),SYSDATE()) <= 0 AND status_leitura = 1  GROUP BY ponto.nome ORDER BY data DESC";
            }
            
          try{
            $resultList = mysql_query($queryList) or die (mysql_error());
            // $resultListF = mysql_query($queryList);
            
            $resultResumo = mysql_query($queryResumo) or die (mysql_error());
            
            // $resultFatura = mysql_query($queryFatura);
            $result = mysql_query($query) or die (mysql_error());
          }  catch (Exception $err){
              FUNCOES::logMsg(print_r($err->getMessage()), 'error');
          }

            if (mysql_num_rows($result) > 0) {
                
               
                ?>

                <!-- BEGIN : ECHARTS -->
                <div class="row">
                    <div class="col-md-12">
                        <div class="panel panel-default">
                            <div class="panel-heading">
                                <div class="caption">
                                    <i class="fa fa-bar-chart" aria-hidden="true"></i>
                                    <span class="">Leituras</span>
                                </div>
                            </div>
                            <!-- /.panel-heading -->
                            <div class="panel-body">

                                <div class="table-responsive">
                                    <table class="table table-striped table-bordered table-hover" id="dataTables-example">
                                        <thead>
                                            <tr>
                                                <?php
                                                if ($_SESSION['UsuarioNivel'] <= 2) {
                                                    echo '<th>Cliente</th>';
                                                } else {
                                                    echo '<th>Ponto</th>';
                                                }
                                                
                                                ?>
                                                <th>Tablet</th>
                                                <?php if ($_SESSION['UsuarioNivel'] < 6 && $_SESSION['UsuarioNivel'] != 1) { ?>
                                                    <th class="hidden-xs">Locação a pagar</th>
                                                    <th class="hidden-xs">Minha Comissão</th>
                                                    <?php
                                                } else if ($_SESSION['UsuarioNivel'] == 1) {
                                                    ?>
                                                    <th class="hidden-xs">Minha Comissão</th>
                                                    <th class="hidden-xs">Comissão Clientes</th>
                                                <?php } ?>
                                                <th class="hidden-xs">Comissão Ponto</th>
                                                <?php if ($_SESSION['UsuarioNivel'] < 6) { ?>
                                                    <th class="hidden-xs">Acerto</th>
                                                    <?php
                                                }
                                                ?>
                                                <th class="hidden-xs">Saldo</th>
                                                <th>Última Movimentação</th>
                                                <th>Ações</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                             
                                            while ($rowMetrica = mysql_fetch_array($result)) {
                                                if ($_SESSION['UsuarioNivel'] == 1) {
                                                    $queryuser = "SELECT nivel,porcentagem FROM user "
                                                            . " WHERE id =  " . $rowMetrica['id_apoio']
                                                            .  " AND nivel = 4";
                                                    $resultuser3 = mysql_query($queryuser);
                                                    $rowUser3 = mysql_fetch_array($resultuser3);
                                                    if ($rowUser3['porcentagem']) {
                                                        
                                                         $comissoes = $rowMetrica['comissao_dono'] + $rowMetrica['comissao_locacao'] + $rowMetrica['comissao_ponto'];
                                                         $rowMetrica['comissao_dono'] += $rowMetrica['acerto'] - $comissoes;
                                                    }
                                                    
                                                    $siglaMoeda = $rowMetrica['moeda_sigla'];
                                                } else {
                                                    $siglaMoeda = $_SESSION['cifraoMoeda'];
                                                }

//                                                $rowMetrica['comissao_sócio'] = $rowResumo['acerto'] - $comissao_socio;



                                                echo "<tr class='gradeA'><td>" . $rowMetrica['nome'] . "</td>"
                                                . "<td>" . $rowMetrica['idprod'] . "</td>";

                                                if ($_SESSION['UsuarioNivel'] < 6) {
                                                    if ($_SESSION['UsuarioNivel'] == 4 && $rowU['porcentagem'] <> 0) {
                                                        /**
                                                         * SÓCIO
                                                         */
                                                        $rowMetrica['comissao_dono'] = $rowMetrica['saldo'] - ($rowMetrica['comissao_ponto'] + $rowMetrica['comissao_locacao'] );
                                                    }
                                                    echo "<td class='hidden-xs'>" . $siglaMoeda . ' ' . $rowMetrica['comissao_locacao'] . ",00</td>
                                                          <td class='hidden-xs'>" . $siglaMoeda . ' ' . $rowMetrica['comissao_dono'] . ",00</td>";
                                                }

                                                if ($_SESSION['UsuarioNivel'] < 6) {
                                                    echo "<td class='center hidden-xs'>" . $siglaMoeda . ' ' . $rowMetrica['comissao_ponto'] . ",00</td>";
                                                }

                                                if ($_SESSION['UsuarioNivel'] != 6) {
                                                    echo "<td class='center hidden-xs'>" . $siglaMoeda . ' ' . $rowMetrica['acerto'] . ",00</td>";
                                                } else {
                                                    echo "<td class='center hidden-xs'>" . $siglaMoeda . ' ' . $rowMetrica['comissao_ponto'] . ",00</td>";
                                                }
                                                echo "<td>" . $rowMetrica['saldo'] . "</td>";
                                                echo "<td>" . ' ' . $rowMetrica['dataorder'] . "</td>";
                                                ?>
                                            <td class='center'>  
                                                <?php if (!isset($_SESSION['UsuarioID']) OR ( $_SESSION['UsuarioNivel'] <= 3)) { ?>
                                                    <a href='detalhamento_leitura.php?id=<?php echo $rowMetrica['id'] ?>' class='btn btn-primary' role='button' data-toggle="modal" data-target="#myModalDetalhesLeitura<?php echo $rowMetrica['id'] ?>"><i class='fa fa-info fa-fw'></i></a>
                                                    <?php
                                                }
                                                ?>
                                            </td>

                                            <!-- Modal HTML -->
                                            <div id="myModalDetalhesLeitura<?php echo $rowMetrica['id'] ?>" class="modal fade">
                                                <div class="modal-dialog modal-lg">
                                                    <div class="modal-content modal-lg">
                                                        <!-- Content will be loaded here from "remote.php" file -->
                                                    </div>
                                                </div>
                                            </div>

                                            <?php
                                            echo "</tr>";
                                        }
                                        
                                        ?>
                                        </tbody>
                                    </table>
                                </div>
                                <!-- /.table-responsive --> 
                            </div>

                            <!-- Lista de metricas atuais -->
                            <?php if ($_SESSION['UsuarioNivel'] <> 6) { ?>
                                <div class="panel panel-default">
                                    <div class="panel-heading" style="min-height: 60px">
                                        <strong>Resumo</strong>
                                        <div class="pull-right">
                                            <select class="form-control" name="input-search" id="input-search"  <?php if ($_SESSION['UsuarioNivel'] == 6) echo 'hidden' ?>  >
                                                <option value ="" >
                                                    <?php
                                                    if ($_SESSION['UsuarioNivel'] <= 2) {
                                                        echo 'Todos os clientes';
                                                    } else {
                                                        echo 'Todos os pontos';
                                                    }
                                                    ?>
                                                </option>
                                                <?php while ($rowList = mysql_fetch_array($resultList)) { ?>
                                                    <option value ="<?php echo $rowList['username'] ?>" ><?php echo $rowList['nome'] ?></option>
                                                    <?php
                                                }
                                                ?>
                                            </select>
                                        </div>
                                    </div>
                                    <!-- /.panel-heading -->
                                    <div class="panel-body">					
                                        <div class="searchable-container">
                                            <?php
                                            
                                            while ($rowResumo = mysql_fetch_array($resultResumo)) {
                                                

                                                if ($_SESSION['UsuarioNivel'] == 4 && $rowU['porcentagem'] <> 0) {
                                                    /**
                                                     * SÓCIO
                                                     */
                                                    $rowResumo['comissao_dono'] = $rowResumo['saldo']-($rowResumo['comissao_ponto'] + $rowResumo['comissao_locacao']) ;
                                                }

                                                if ($_SESSION['UsuarioNivel'] == 3) {
                                                    /**
                                                     * CLIENTES
                                                     */
                                                    $queryuser = "SELECT porcentagem FROM user WHERE id =  " . $_SESSION['UsuarioID']; //locação a pagar
                                                    $resultuser2 = mysql_query($queryuser);
                                                    $rowUser2 = mysql_fetch_array($resultuser2);
                                                    $rowResumo['comissao_locacao'] = round($rowUser2['porcentagem'] / 100, 2) * $rowResumo['saldo'];


                                                    $queryuser = "SELECT nivel,porcentagem FROM user "
                                                            . " WHERE id =  " . $rowResumo['id_apoio'];
                                                    $resultuser3 = mysql_query($queryuser);
                                                    $rowUser3 = mysql_fetch_array($resultuser3);
                                                    if ($rowUser3['porcentagem']) {
                                                        if ($rowUser3['nivel'] == 4) { //caso comissao_sócio
                                                            $comissoes = $rowResumo['comissao_dono'] + $rowResumo['comissao_locacao'] + $rowResumo['comissao_ponto'];
                                                            $rowResumo['comissao_sócio'] = $rowResumo['acerto'] - $comissoes;
                                                        }
                                                    }
                                                }

                                                if ($_SESSION['UsuarioNivel'] == 1) {
                                                    /**
                                                     * ADMIN
                                                     */
                                                    $queryuser = "SELECT nivel,porcentagem FROM user "
                                                            . " WHERE id =  " . $rowResumo['id_apoio'];
                                                    $resultuser3 = mysql_query($queryuser);
                                                    $rowUser3 = mysql_fetch_array($resultuser3);
                                                    if ($rowUser3['porcentagem']) {

                                                        if ($rowUser3['nivel'] == 4) { //caso comissao_sócio
                                                            $comissoes = $rowResumo['comissao_dono'] + $rowResumo['comissao_locacao'] + $rowResumo['comissao_ponto'];
                                                            $rowResumo['comissao_socio'] = $rowResumo['acerto'] - $comissoes;
                                                        }
                                                    }
                                                }

                                                if ($_SESSION['UsuarioNivel'] == 1) {
                                                    $siglaMoeda = $rowResumo['moeda_sigla'];
                                                } else {
                                                    $siglaMoeda = $_SESSION['cifraoMoeda'];
                                                }
                                                ?>

                                                <div class="items col-xs-12 col-sm-12 col-md-6 col-lg-6">
                                                    <div class="info-block block-info clearfix">
                                                        <div class="square-box pull-left">
                                                            <i class="fa fa-tablet fa-5x" aria-hidden="true"></i>
                                                            <h5><?php echo $rowResumo['idprod'] ?></h5>
                                                        </div>
                                                        <p>Último cálculo: <?php echo $rowResumo['dataorder'] ?></p>
                                                        <p>Saldo: <?php echo $siglaMoeda . " " . $rowResumo['saldo'] ?></p>
                                                        <?php if ($_SESSION['UsuarioNivel'] < 6 && $_SESSION['UsuarioNivel'] != 1) { ?>
                                                            <p>Locação a pagar: <?php echo $siglaMoeda . " " . $rowResumo['comissao_locacao']; ?></p>
                                                            <p>Minha Comissão: <?php echo $siglaMoeda . " " . $rowResumo['comissao_dono'] ?></p>
                                                            <?php
                                                        } elseif ($_SESSION['UsuarioNivel'] == 1) {
                                                            ?>
                                                            <p>Minha Comissão: <?php echo $siglaMoeda . " " . $rowResumo['comissao_locacao']; ?></p>
                                                            <p>Comissão Clientes: <?php echo $siglaMoeda . " " . $rowResumo['comissao_dono'] ?></p>
                                                        <?php } ?>
                                                        <p>Ponto: <?php echo $siglaMoeda . " " . $rowResumo['comissao_ponto'] ?></p>
                                                        <?php if (!empty($rowResumo['comissao_sócio'])) { ?>
                                                            <p>Sócio: <?php echo $siglaMoeda . " " . $rowResumo['comissao_sócio']; ?></p>
                                                        <?php } ?>
                                                        <p class='hidden'><?php echo $rowResumo['nome'] ?></p>
                                                        <p class='hidden'><?php echo $rowResumo['cliente'] ?></p>
                                                    </div>
                                                </div>
                                                <?php
                                            }
                                            ?>
                                        </div>
                                    </div> 
                                </div> 
                            <?php } ?>
                            <!-- /.Lista-->
                        </div>
                    </div>
                </div>
                <?php
            }
           
            ?>
        </div>

        <input type="hidden" id="idTela" value="<?php echo $id_tela ?>">

        <!-- Page-Level Demo Scripts - Blank - Use for reference -->
        <script>
            $(document).ready(function () {
                $('#dataTables-example').dataTable({sortList: [[5, 0]]});
            });

            $(document).ready(function () {
                $('#dataTables-fatura').dataTable({sortList: [[5, 0]]});
            });

            $(function () {
                $('#input-search').change('keyup', function () {
                    var rex = new RegExp($(this).val(), 'i');
                    $('.searchable-container .items').hide();
                    $('.searchable-container .items').filter(function () {
                        return rex.test($(this).text());
                    }).show();
                });
            });


            $(function () {
                $('#input-search-fatura').change('keyup', function () {
                    var rex = new RegExp($(this).val(), 'i');
                    $('.searchable-container-fatura .items').hide();
                    $('.searchable-container-fatura .items').filter(function () {
                        return rex.test($(this).text());
                    }).show();
                });
            });


            $('#frmVersaoApk').on('submit', function (ev) {
                ev.preventDefault();

                $.ajax({
                    type: 'POST',
                    url: "edita_versao.php",
                    dataType: 'json',
                    data: $("#frmVersaoApk").serialize(),
                    beforeSend: function () {
                        $('#btnAtualizaVersaoApk').attr('disabled', true);
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        $('#btnAtualizaVersaoApk').attr('disabled', false);
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {
                        if (data.success) {
                            var priority = 'success';
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                        fLoadOptionScriptLeitura('Leitura', '<?php echo $_SESSION['pais'] ?>');
                    }
                });
            });

            fInitAutoLoad();

        </script>

        <?php
        break;

    case 'ConsultarFaturas':

        $nivel_necessario = 6;

        // Verifica se não há a variável da sessão que identifica o usuário
        if (!isset($_SESSION['UsuarioID']) OR ( $_SESSION['UsuarioNivel'] > $nivel_necessario)) {
            // Destrói a sessão por segurança
            session_destroy();
            // Redireciona o visitante de volta pro login
            header("Location: index.php");
            exit;
        }

        if (isset($_REQUEST['id_ponto'])) {
            $username = $_REQUEST['id_ponto'];
        }

        require_once("db.php");
        ?>

        <div class="panel-heading">
            <strong>Consultar Leituras</strong>
        </div>
        <div class="panel-body">
            <div class="row">				
                <div class="col-md-12">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <div class="row">
                                <form id="frmBuscaFaturas" name="formfaturas" onsubmit="return pesquisarFaturas()">
                                    <div class="col-lg-4">
                                        <div class="form-group input-group">    
                                            <span class="input-group-addon"> <?php
                                                if ($_SESSION['UsuarioNivel'] <= 2)
                                                    echo 'Cliente';
                                                else
                                                    echo 'Ponto'
                                                    ?> </span>                                             
                                            <select name="cliente" id="cliente" class="form-control">

                                                <?php
                                                if ($_SESSION['UsuarioNivel'] == 1) {
                                                    $resultUser = mysql_query("SELECT username, nome FROM user WHERE nivel = 3 ORDER BY username ASC");
                                                } elseif ($_SESSION['UsuarioNivel'] == 2) {
                                                    $resultUser = mysql_query("SELECT username, nome FROM user a WHERE nivel = 3 AND a.id_apoio = " . $_SESSION['UsuarioID'] . " ORDER BY username ASC");
                                                } elseif ($_SESSION['UsuarioNivel'] == 3) {
                                                    $apoios = getApoios($_SESSION['UsuarioID']);
                                                    $resultUser = mysql_query("SELECT ponto.nome username, ponto.nome "
                                                            . " FROM ponto "
                                                            . " WHERE ponto.id_apoio IN ( " . implode(',', $apoios) . ")"
                                                            . " ORDER BY ponto.nome ASC");
                                                } elseif ($_SESSION['UsuarioNivel'] == 4) {
                                                    $resultUser = mysql_query("SELECT ponto.nome username, ponto.nome FROM ponto WHERE ponto.id_apoio = " . $_SESSION['UsuarioID'] . " ORDER BY ponto.nome ASC");
                                                } elseif ($_SESSION['UsuarioNivel'] == 6) {
                                                    $resultUser = mysql_query("SELECT ponto.nome, ponto.nome username FROM ponto, user a WHERE ponto.id = a.id_apoio AND a.id = " . $_SESSION['UsuarioID'] . " ORDER BY nome DESC");
                                                } else {
                                                    $resultUser = mysql_query("SELECT ponto.nome username, ponto.nome FROM ponto WHERE ponto.id_apoio = " . $_SESSION['UsuarioApoio'] . " ORDER BY ponto.nome ASC");
                                                }

                                                $totalRegitros = mysql_num_rows($resultUser);
                                                if ($totalRegitros > 1) {
                                                    echo '<option value ="" >Todos</option>';
                                                }

                                                while ($rowUser = mysql_fetch_array($resultUser)) {
                                                    if ($rowUser['username'] == $cliente_edit OR $totalRegitros == 1) {
                                                        $selected = 'selected';
                                                    } else {
                                                        $selected = '';
                                                    }


                                                    if ($_SESSION['UsuarioNivel'] == 4 && $username AND $rowUser['id_ponto'] == $username) {
                                                        $selected = 'selected';
                                                    }

                                                    echo '<option value="' . $rowUser['username'] . '" ' . $selected . '  >' . $rowUser['nome'] . '</option>';
                                                }
                                                ?>
                                            </select>
                                        </div>
                                    </div><!-- /.col-lg-4 -->
                                    <div class="col-lg-3">                                             
                                        <div class="form-group input-group">    
                                            <span class="input-group-addon"> Status Leitura</span>
                                            <select name="status" id="status" class="form-control" required>
                                                <option value ="" >Selecione</option>
                                                <?php
                                                if ($status_edit == 1) {
                                                    $aberta = 'selected';
                                                } elseif ($status_edit == 2 || $username) {
                                                    $fechada = 'selected';
                                                } else {
                                                    $aberta = '';
                                                    $fechada = '';
                                                }
                                                echo '<option $selecionado value ="1" ' . $aberta . '>Aberta</option>';
                                                echo '<option $selecionado value ="2" ' . $fechada . '>Fechada</option>';
                                                ?>
                                            </select>                                                
                                        </div>
                                    </div><!-- /.col-lg-4 -->
                                    <div class="col-lg-2">
                                        <button type="submit" id="btnPesquisarFaturas" class="btn btn-primary" data-loading-text="Carregando..." >Pesquisar</button>
                                    </div><!-- /.col-lg-6 -->
                                </form>
                            </div> 
                        </div>

                        <div class="panel-body">
                            <span id="divResultPesquisaFaturas"></span>
                            <span id="divErrosPesquisaFaturas"></span>
                        </div>
                    </div>
                </div>
                <!-- Fatura -->
                <style>
                    .height {
                        min-height: 200px;
                    }

                    .icon {
                        font-size: 30px;
                        color: #5CB85C;
                    }

                    .iconbig {
                        font-size: 50px;
                        color: #08C;
                    }

                    .table > tbody > tr > .emptyrow {
                        border-top: none;
                    }

                    .table > thead > tr > .emptyrow {
                        border-bottom: none;
                    }

                    .table > tbody > tr > .highrow {
                        border-top: 3px solid;
                    }
                </style>
                <!-- /#wrapper -->
            </div>
        </div>

        <!-- Page-Level Demo Scripts - Blank - Use for reference -->
        <script>
            $(document).ready(function () {
                $('#dataTables-example').dataTable();
            });
        </script>
        <script type="text/javascript">

            $(function () {
                $(".btn").click(function () {
                    $(this).button('loading').delay(10000).queue(function () {
                        //$(this).button('reset');
                    });
                });
            });

            $('#cliente').change(function () {
                $(".btn").button('reset');
            });

            $('#status').change(function () {
                $(".btn").button('reset');
            });

        </script>	
        <?php
        break;

    case 'ConsultarFaturasPeriodo':

        $nivel_necessario = 6;

        // Verifica se não há a variável da sessão que identifica o usuário
        if (!isset($_SESSION['UsuarioID']) OR ( $_SESSION['UsuarioNivel'] > $nivel_necessario)) {
            // Destrói a sessão por segurança
            session_destroy();
            // Redireciona o visitante de volta pro login
            header("Location: index.php");
            exit;
        }

        require_once("db.php");
        ?>
        <div class="panel-heading">
            <strong>Faturas por Período</strong>
        </div>
        <div class="panel-body">
            <div class="row">
                <div class="col-md-12">
                    <div class="panel panel-default">
                        <div class="panel-heading">

                            <div class="row">
                                <form name="frmBuscaFaturasPeriodo" id="frmBuscaFaturasPeriodo" method="post" onsubmit="return pesquisarFaturasPeriodo()"> 

                                    <div class="col-lg-4">
                                        <div class="form-group input-group">    
                                            <span class="input-group-addon"> <?php
                                                if ($_SESSION['UsuarioNivel'] <= 2)
                                                    echo 'Cliente';
                                                else
                                                    echo 'Ponto'
                                                    ?> </span>                                             
                                            <select name="cliente" id="cliente" class="form-control">



                                                <?php
                                                if ($_SESSION['UsuarioNivel'] == 1) {
                                                    $resultUser = mysql_query("SELECT username, nome FROM user WHERE nivel = 3 ORDER BY username ASC");
                                                } elseif ($_SESSION['UsuarioNivel'] == 2) {
                                                    $resultUser = mysql_query("SELECT username, nome FROM user a WHERE nivel = 3 AND a.id_apoio = " . $_SESSION['UsuarioID'] . " ORDER BY username ASC");
                                                } elseif ($_SESSION['UsuarioNivel'] == 3) {
                                                    $apoios = getApoios($_SESSION['UsuarioID']);
                                                    $resultUser = mysql_query("SELECT ponto.nome username, ponto.nome "
                                                            . " FROM ponto "
                                                            . " WHERE ponto.id_apoio IN (" . implode(',', $apoios) . ')'
                                                            . " ORDER BY ponto.nome ASC");
                                                } elseif ($_SESSION['UsuarioNivel'] == 4) {
                                                    $resultUser = mysql_query("SELECT ponto.nome username, ponto.nome FROM ponto WHERE ponto.id_apoio = " . $_SESSION['UsuarioID'] . " ORDER BY ponto.nome ASC");
                                                } elseif ($_SESSION['UsuarioNivel'] == 6) {
                                                    $resultUser = mysql_query("SELECT ponto.nome, ponto.nome username FROM ponto, user a WHERE ponto.id = a.id_apoio AND a.id = " . $_SESSION['UsuarioID'] . " ORDER BY nome DESC");
                                                } else {
                                                    $resultUser = mysql_query("SELECT ponto.nome username, ponto.nome FROM ponto WHERE ponto.id_apoio = " . $_SESSION['UsuarioApoio'] . " ORDER BY ponto.nome ASC");
                                                }

                                                $totalRegitros = mysql_num_rows($resultUser);
                                                if ($totalRegitros > 1) {
                                                    echo '<option value ="" >Todos</option>';
                                                }

                                                while ($rowUser = mysql_fetch_array($resultUser)) {
                                                    if ($rowUser['username'] == $cliente_edit OR $totalRegitros == 1) {
                                                        $selected = 'selected';
                                                    } else {
                                                        $selected = '';
                                                    }
                                                    echo '<option $selecionado value="' . $rowUser['username'] . '" ' . $selected . '  >' . $rowUser['nome'] . '</option>';
                                                }
                                                ?>

                                            </select>
                                        </div>
                                    </div><!-- /.col-lg-4 -->

                                    <div class="col-lg-5">                                             
                                        <div class="form-group input-group" id="datafatura"  > 
                                            <span class="input-group-addon"> Data Leitura</span>  
                                            <div class="input-daterange input-group" id="datepicker" data-provide="datepicker" >
                                                <input type="text" class="form-control" name="start" id="start" <?php if (!empty($_POST['start'])) echo 'value="' . $_POST['start'] . '"' ?> required />
                                                <span class="input-group-addon">a</span>
                                                <input type="text" class="form-control" name="end" id="end" <?php if (!empty($_POST['end'])) echo 'value="' . $_POST['end'] . '"' ?> required />
                                            </div>
                                        </div>
                                    </div><!-- /.col-lg-4 -->

                                    <div class="col-lg-2">
                                        <button type="submit" class="btn btn-primary" id="btnPersquisarFaturaPeriodo" data-loading-text="Carregando...">Pesquisar</button>
                                    </div><!-- /.col-lg-6 -->
                                </form>
                            </div> 
                        </div>

                        <div class="panel-body">
                            <span id="divResultPesquisaFaturasPeriodo"></span>
                            <span id="divErrosPesquisaFaturasPeriodo"></span>
                        </div>

                    </div>
                </div>
            </div>			
            <!-- /. Fatura -->

            <!-- Fatura -->
            <style>
                .height {
                    min-height: 200px;
                }

                .icon {
                    font-size: 30px;
                    color: #5CB85C;
                }

                .iconbig {
                    font-size: 50px;
                    color: #08C;
                }

                .table > tbody > tr > .emptyrow {
                    border-top: none;
                }

                .table > thead > tr > .emptyrow {
                    border-bottom: none;
                }

                .table > tbody > tr > .highrow {
                    border-top: 3px solid;
                }
            </style>

            <!-- Page-Level Demo Scripts - Blank - Use for reference -->
            <script>
                $(document).ready(function () {
                    $('#dataTables-example').dataTable();
                });


                $(function () {
                    $(".btn").click(function () {
                        $(this).button('loading').delay(10000).queue(function () {
                            //$(this).button('reset');
                        });
                    });
                });

                $('#cliente').change(function () {
                    $(".btn").button('reset');
                });

                $('#datepicker').change(function () {
                    $(".btn").button('reset');
                });

                $('#datafatura .input-daterange').datepicker({
                    format: "dd/mm/yyyy",
                    todayBtn: "linked",
                    language: "pt-BR"
                });
            </script> 

            <?php
            break;

        case 'GerenciarFaturas':

            $nivel_necessario = 1;

            // Verifica se não há a variável da sessão que identifica o usuário
            if (!isset($_SESSION['UsuarioID']) OR ( $_SESSION['UsuarioNivel'] > $nivel_necessario)) {
                // Destrói a sessão por segurança
                session_destroy();
                // Redireciona o visitante de volta pro login
                header("Location: index.php");
                exit;
            }

            require_once("db.php");
            ?>
            <style>
                .checkbox label:after, 
                .radio label:after {
                    content: '';
                    display: table;
                    clear: both;
                }

                .checkbox .cr,
                .radio .cr {
                    position: relative;
                    display: inline-block;
                    border: 1px solid #a9a9a9;
                    border-radius: .25em;
                    width: 1.3em;
                    height: 1.3em;
                    float: left;
                    margin-right: .5em;
                }

                .radio .cr {
                    border-radius: 50%;
                }

                .checkbox .cr .cr-icon,
                .radio .cr .cr-icon {
                    position: absolute;
                    font-size: .8em;
                    line-height: 0;
                    top: 50%;
                    left: 20%;
                }

                .radio .cr .cr-icon {
                    margin-left: 0.04em;
                }

                .checkbox label input[type="checkbox"],
                .radio label input[type="radio"] {
                    display: none;
                }

                .checkbox label input[type="checkbox"] + .cr > .cr-icon,
                .radio label input[type="radio"] + .cr > .cr-icon {
                    transform: scale(3) rotateZ(-20deg);
                    opacity: 0;
                    transition: all .3s ease-in;
                }

                .checkbox label input[type="checkbox"]:checked + .cr > .cr-icon,
                .radio label input[type="radio"]:checked + .cr > .cr-icon {
                    transform: scale(1) rotateZ(0deg);
                    opacity: 1;
                }

                .checkbox label input[type="checkbox"]:disabled + .cr,
                .radio label input[type="radio"]:disabled + .cr {
                    opacity: .5;
                }	

            </style>

            <?php
            if ($_SESSION['UsuarioNivel'] <= 2) {
                $result = mysql_query("SELECT tablet.cliente nome,metricas.id id, tablet.idprod, comissao_ponto,comissao_dono, comissao_locacao, 
												saldo_total,DATE_FORMAT(metricas.dataorder,'%d/%m/%Y')  data_expiracao, metricas.status_leitura 
												FROM metricas, tablet 
												WHERE  metricas.idprod = tablet.idprod 
												AND metricas.status = 0 
												AND metricas.status_leitura = 1 
												ORDER BY metricas.dataorder DESC") or die(mysql_error());
            }

            if (mysql_num_rows($result) > 0) {
                ?>

                <div class="panel-heading" style="min-height: 60px">
                    <strong>Leituras</strong>
                    <div class="pull-right col-md-4" >	
                        <form role="form" method="POST" id="frmFecharFaturasCliente" class="form-horizontal" >
                            <div class="input-group">
                                <select name="cliente" id="cliente" class="form-control" required >
                                    <option value ="" >Selecione o cliente</option>
                                    <?php
                                    $queryList = "SELECT nome, username FROM user WHERE nivel = 3 ORDER BY nome DESC";
                                    $resultList = mysql_query($queryList);

                                    while ($rowList = mysql_fetch_array($resultList)) {
                                        ?>
                                        <option value ="<?php echo $rowList['username'] ?>" ><?php echo $rowList['nome'] ?></option>
                                    <?php } ?>
                                </select>			

                                <span class="input-group-btn">
                                    <button type="submit" id="btnFecharFaturasCliente" class="btn btn-primary" type="button">Fechar Leituras!</button>
                                </span>
                            </div>
                        </form>
                    </div>
                </div>
                <!-- /.panel-heading -->
                <div class="panel-body">
                    <div class="table-responsive">
                        <form role="form" method="POST" id="frmFecharFaturasSelecionadas" >
                            <table class="table table-striped table-bordered table-hover" id="dataTables-example">
                                <thead>
                                    <tr>
                                        <th class="hidden-xs">#</th>
                                        <th>Descrição acerto</th>
                                        <th>Cliente</th>
                                        <th>Comissão Locação</th>
                                        <th class="hidden-xs">Comissão Dono</th>
                                        <th class="hidden-xs">Comissão Ponto</th>
                                        <th class="hidden-xs">Saldo Total</th>
                                        <th>Status</th>
                                        <th style="min-width: 40px; width: 45px" >
                                            <div class="checkbox">
                                                <label style="font-size: 1.5em">
                                                    <input type="checkbox" value="" id="checkall" name="checkall" >
                                                    <span class="cr"><i class="cr-icon fa fa-check"></i></span>						
                                                </label>
                                            </div>
                                        </th>
                                    </tr>
                                </thead>
                                <tbody>

                                    <?php
                                    $i = 1;
                                    while ($row = mysql_fetch_array($result)) {

                                        echo "<tr class='gradeA'><td class='hidden-xs'>" . $row['id'] . "</td><td>Tablet " . $row['idprod'] . " - Leitura de " . $row['data_expiracao'] . "</td>"
                                        . "<td>" . $row['nome'] . "</td><td> " . $_SESSION['cifraoMoeda'] . " " . $row['comissao_locacao'] . "</td>"
                                        . "<td class='hidden-xs'> " . $_SESSION['cifraoMoeda'] . " " . $row['comissao_dono'] . "</td>"
                                        . "<td class='hidden-xs'> " . $_SESSION['cifraoMoeda'] . " " . $row['comissao_ponto'] . "</td>"
                                        . "<td class='hidden-xs'> " . $_SESSION['cifraoMoeda'] . " " . $row['saldo_total'] . "</td>";

                                        if ($row['status_leitura'] == 1) {
                                            // echo '<td class="center"><a href="javascript:void(0);" onclick="alterarStatusFatura('.$row['id'].', 2);" class="btn btn-success btn-bg" role="button">ABERTA&nbsp</a></td>';
                                            echo '<td class="center"><font class="text-success" >ABERTA&nbsp</font></td>';
                                        } else {
                                            // echo '<td class="center"><a href="javascript:void(0);" onclick="alterarStatusFatura('.$row['id'].', 1);" class="btn btn-success btn-bg" role="button">FECHADA&nbsp</a></td>';
                                            echo '<td class="center"><a href="javascript:void(0);" class="btn btn-success btn-bg" role="button">FECHADA&nbsp</a></td>';
                                        }
                                        ?>

                                    <td>
                                        <div class="checkbox">
                                            <label style="font-size: 1.5em">
                                                <input type="checkbox" value="<?php echo $row['id'] ?>" name="id[]" >
                                                <span class="cr"><i class="cr-icon fa fa-check"></i></span>						
                                            </label>
                                        </div>
                                    </td>
                                    <?php
                                    echo "</tr>";

                                    $i++;
                                }
                                ?>

                                </tbody>

                            </table>
                            <input type="hidden" name="opt" value="2">
                            <br>
                            <div class="pull-right">
                                <button id="btnFecharFaturasSelecionadas" type="submit" class="btn btn-primary">Fechar Leituras Selecionadas!</button>											
                            </div>			
                        </form>
                    </div>
                    <!-- /.table-responsive -->
                    <!-- /#page-wrapper -->
                    <?php include 'newmaquina.php'; ?>
                </div>
            <?php } else {
                ?>						
                <div class='alert alert-warning'>Nenhum Registro encontrado.</div>
                <?php
            }
            ?>
            <!-- /#wrapper -->


            <script>
                $(document).ready(function () {
                    var table = $('#dataTables-example').dataTable({
                        "columnDefs": [{
                                "targets": 8,
                                "orderable": false
                            }]
                    });

                    $('#checkall').click(function () {
                        $(':checkbox').prop('checked', this.checked);
                    });

                    // Handle form submission event
                    $('#frmFecharFaturasSelecionadas').on('submit', function (ev) {
                        ev.preventDefault();


                        if (!$('input:checkbox:checked').length) {
                            toastr['warning']('Nenhuma Leitura selecionada!');
                            return;
                        }


                        $.ajax({
                            type: 'POST',
                            url: "estado_fatura.php",
                            dataType: 'json',
                            data: $("#frmFecharFaturasSelecionadas").serialize(),
                            beforeSend: function () {
                                $('#btnFecharFaturasSelecionadas').attr('disabled', true);
                                $.blockUI({
                                    message: $("#loading-indicator"),
                                    css: {
                                        border: 'none',
                                        padding: '15px',
                                        background: '',
                                        color: '#fff'
                                    }
                                });
                            },
                            complete: function () {
                                $('#btnFecharFaturasSelecionadas').attr('disabled', false);
                                setTimeout($.unblockUI, 500);
                            },
                            success: function (data) {
                                if (data.success) {
                                    var priority = 'success';
                                } else {
                                    var priority = 'error';
                                }
                                toastr[priority](data.msg);
                                fLoadOptionScript('GerenciarFaturas');
                            }
                        });

                    });
                });





                $('#frmFecharFaturasCliente').on('submit', function (ev) {
                    ev.preventDefault();

                    $.ajax({
                        type: 'POST',
                        url: "estado_fatura.php",
                        dataType: 'json',
                        data: $("#frmFecharFaturasCliente").serialize(),
                        beforeSend: function () {
                            $('#btnFecharFaturasCliente').attr('disabled', true);
                            $.blockUI({
                                message: $("#loading-indicator"),
                                css: {
                                    border: 'none',
                                    padding: '15px',
                                    background: '',
                                    // opacity: 0.8, 
                                    color: '#fff'
                                }
                            });
                        },
                        complete: function () {
                            $('#btnFecharFaturasCliente').attr('disabled', false);
                            setTimeout($.unblockUI, 500);
                        },
                        success: function (data) {
                            if (data.success) {
                                var priority = 'success';
                            } else {
                                var priority = 'error';
                            }
                            toastr[priority](data.msg);
                            fLoadOptionScript('GerenciarFaturas');
                        }
                    });
                });
            </script>
            <?php
            break;

        case 'TransacaoPeriodo':

            $nivel_necessario = 6;

            // Verifica se não há a variável da sessão que identifica o usuário
            if (!isset($_SESSION['UsuarioID']) OR ( $_SESSION['UsuarioNivel'] > $nivel_necessario)) {
                // Destrói a sessão por segurança
                session_destroy();
                // Redireciona o visitante de volta pro login
                header("Location: index.php");
                exit;
            }

            require_once("db.php");
            ?>
            <div class="panel-heading">
                <strong>Entradas e Saidas</strong>
            </div>
            <div class="panel-body">
                <div class="row">
                    <div class="col-md-12">
                        <div class="panel panel-default">
                            <div class="panel-heading">
                                <div class="row">
                                    <form id="frmBuscaTransacoes" onsubmit="return pesquisarTransacoesPeriodo()" > 
                                        <div class="col-lg-3">
                                            <div class="form-group input-group">    
                                                <span class="input-group-addon">Tablet</span>                                             
                                                <select name="tablet" id="tablet" class="form-control">
                                                    <option value ="" >Todos</option>
                                                    <?php
                                                    if ($_SESSION['UsuarioNivel'] == 1) {

                                                        $resultUser = mysql_query("SELECT idprod FROM tablet ORDER BY idprod ASC");
                                                    } elseif ($_SESSION['UsuarioNivel'] == 2) {
                                                        $resultUser = mysql_query("SELECT idprod FROM tablet, user a WHERE tablet.cliente = a.username AND a.id_apoio = " . $_SESSION['UsuarioID'] . " ORDER BY idprod ASC");
                                                    } elseif ($_SESSION['UsuarioNivel'] == 3) {
                                                        $apoios = getApoios($_SESSION['UsuarioID']);
                                                        $resultUser = mysql_query("SELECT idprod FROM tablet "
                                                                . " WHERE id_apoio IN ( " . implode(',', $apoios) . ')'
                                                                . " ORDER BY idprod ASC");
                                                        //$resultUser = mysql_query("SELECT idprod FROM tablet WHERE cliente =  '" . $_SESSION['UsuarioUser'] . "' AND id_apoio = " . $_SESSION['UsuarioID'] . "  ORDER BY idprod ASC");
                                                    } elseif ($_SESSION['UsuarioNivel'] == 4) {
                                                        $resultUser = mysql_query("SELECT idprod FROM tablet WHERE cliente =  '" . $_SESSION['UsuarioUser'] . "' AND id_apoio = " . $_SESSION['UsuarioID'] . "  ORDER BY idprod ASC");
                                                    } elseif ($_SESSION['UsuarioNivel'] == 6) {
                                                        // $resultUser = mysql_query("SELECT ponto.nome, ponto.nome username FROM ponto, user a WHERE ponto.id = a.id_apoio AND a.id = " . $_SESSION['UsuarioID'] . " ORDER BY nome DESC");					
                                                        $resultUser = mysql_query("SELECT tablet.id,tablet.idprod,tablet.cliente,ponto.nome ponto,tablet.cadastro cadastro, tablet.validade, tablet.ligado, tablet.dificuldade, tablet.expiracao, tablet.ativo,tablet.id_ponto
														FROM tablet,ponto, user a 
														WHERE tablet.id_ponto = ponto.id AND ponto.id = a.id_apoio AND a.id = " . $_SESSION['UsuarioID'] . " AND tablet.ativo = 1 ORDER BY idprod ASC");
                                                    } else {
                                                        $resultUser = mysql_query("SELECT ponto.nome username, ponto.nome FROM ponto WHERE ponto.id_apoio = " . $_SESSION['UsuarioApoio'] . " ORDER BY ponto.nome ASC");
                                                    }
                                                    while ($rowUser = mysql_fetch_array($resultUser)) {
                                                        if ($rowUser['idprod'] == $tablet_edit) {
                                                            $selected = 'selected';
                                                        } else {
                                                            $selected = '';
                                                        }
                                                        echo '<option $selecionado value="' . $rowUser['idprod'] . '" ' . $selected . '  >' . $rowUser['idprod'] . '</option>';
                                                    }
                                                    ?>
                                                </select>
                                            </div>
                                        </div><!-- /.col-lg-4 -->

                                        <div class="col-lg-4">                                             
                                            <div class="form-group input-group" id="datafatura"> 
                                                <span class="input-group-addon"> Data Transação</span>  
                                                <div class="input-daterange input-group" id="datepicker">
                                                    <input type="text" class="form-control" name="start" id="start" <?php if (!empty($_POST['start'])) echo 'value="' . $_POST['start'] . '"' ?> required />
                                                    <span class="input-group-addon">a</span>
                                                    <input type="text" class="form-control" name="end" id="end" <?php if (!empty($_POST['end'])) echo 'value="' . $_POST['end'] . '"' ?> required />
                                                </div>
                                            </div>
                                        </div><!-- /.col-lg-4 -->

                                        <div class="col-lg-3">                                             
                                            <div class="form-group input-group">    
                                                <span class="input-group-addon"> Tipo</span>
                                                <select name="tipo" id="tipo" class="form-control" required>
                                                    <option value ="" >Selecione</option>
                                                    <?php
                                                    if ($status_edit == 1) {
                                                        $entrada = 'selected';
                                                    } elseif ($status_edit == 2) {
                                                        $saida = 'selected';
                                                    } else {
                                                        $entrada = '';
                                                        $saida = '';
                                                    }

                                                    echo '<option $selecionado value ="1" ' . $entrada . '>Entrada</option>';
                                                    echo '<option $selecionado value ="2" ' . $saida . '>Saida</option>';
                                                    ?>

                                                </select>

                                            </div>
                                        </div><!-- /.col-lg-4 -->
                                        <div class="col-lg-2">
                                            <button type="submit" class="btn btn-primary" data-loading-text="Loading...">Pesquisar</button>
                                        </div><!-- /.col-lg-6 -->
                                    </form>
                                </div> 
                            </div>							
                            <div class="panel-body">
                                <span id="divResultPesquisaTransacaoPeriodo"></span>
                                <span id="divErrosPesquisaTransacaoPeriodo"></span>
                            </div>							
                        </div>
                    </div>
                </div>
                <!-- Fatura -->
                <style>
                    .height {
                        min-height: 200px;
                    }

                    .icon {
                        font-size: 30px;
                        color: #5CB85C;
                    }

                    .iconbig {
                        font-size: 50px;
                        color: #08C;
                    }

                    .table > tbody > tr > .emptyrow {
                        border-top: none;
                    }

                    .table > thead > tr > .emptyrow {
                        border-bottom: none;
                    }

                    .table > tbody > tr > .highrow {
                        border-top: 3px solid;
                    }
                </style>
                <!-- /#wrapper -->
            </div>
        </div>	

        <script>
            $(document).ready(function () {
                $('#dataTables-example').dataTable();
            });

            $(function () {
                $(".btn").click(function () {
                    $(this).button('loading').delay(10000).queue(function () {
                        //$(this).button('reset');
                    });
                });
            });

            $('#tablet').change(function () {
                $(".btn").button('reset');
            });

            $('#tipo').change(function () {
                $(".btn").button('reset');
            });

            $('#datepicker').change(function () {
                $(".btn").button('reset');
            });


            $('#datafatura .input-daterange').datepicker({
                format: "dd/mm/yyyy",
                todayBtn: "linked",
                language: "pt-BR"
            });

        </script> 	

        <?php
        break;

    case 'MovimentacaoPeriodo':

        $nivel_necessario = 6;

        // Verifica se não há a variável da sessão que identifica o usuário
        if (!isset($_SESSION['UsuarioID']) OR ( $_SESSION['UsuarioNivel'] > $nivel_necessario)) {
            // Destrói a sessão por segurança
            session_destroy();
            // Redireciona o visitante de volta pro login
            header("Location: index.php");
            exit;
        }

        require_once("db.php");
        ?>
        <div class="panel-heading">
            <strong>Movimentações por Período</strong>
        </div>
        <div class="panel-body">
            <div class="row">
                <div class="col-md-12">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <div class="row">
                                <form name="frmBusca" id="frmPesquisarMovimentacoes" method="post" onsubmit="return perquisarMovimentacao();" > 

                                    <div class="col-lg-3">
                                        <div class="form-group input-group">    
                                            <span class="input-group-addon"> <?php
                                                if ($_SESSION['UsuarioNivel'] <= 2) {
                                                    echo 'Cliente';
                                                } else {
                                                    echo 'Ponto';
                                                }
                                                ?>
                                            </span>                                             
                                            <select name="user" id="user" class="form-control">
                                                <option value ="" >Todos</option>
                                                <?php
                                                if ($_SESSION['UsuarioNivel'] <= 2) {
                                                    $resultUser = mysql_query("SELECT username idprod, nome "
                                                            . " FROM user WHERE nivel = 3 "
                                                            . " ORDER BY username ASC");
                                                } elseif ($_SESSION['UsuarioNivel'] == 3) {
                                                    $apoios = getApoios($_SESSION['UsuarioID']);
                                                    $resultUser = mysql_query("SELECT ponto.nome, ponto.nome idprod "
                                                            . " FROM ponto "
                                                            . " WHERE ponto.id_apoio IN ( " . implode(',', $apoios) . ")"
                                                            . " ORDER BY ponto.nome ASC");
                                                //    $resultUser = mysql_query("SELECT username idprod, nome "
                                                //            . " FROM user a "
                                                //            . " WHERE nivel = 3 "
                                                //            . " AND a.id_apoio = " . $_SESSION['UsuarioID'] 
                                                //            . " ORDER BY username ASC");
                                                } elseif ($_SESSION['UsuarioNivel'] == 4) {
                                                    $resultUser = mysql_query("SELECT ponto.nome, ponto.nome idprod FROM ponto WHERE ponto.id_apoio = " . $_SESSION['UsuarioID'] . " ORDER BY ponto.nome ASC");
                                                } elseif ($_SESSION['UsuarioNivel'] == 6) {
                                                    $resultUser = mysql_query("SELECT ponto.nome, ponto.nome username FROM ponto, user a WHERE ponto.id = a.id_apoio AND a.id = " . $_SESSION['UsuarioID'] . " ORDER BY nome DESC");
                                                } else {
                                                    $resultUser = mysql_query("SELECT ponto.nome username, ponto.nome FROM ponto WHERE ponto.id_apoio = " . $_SESSION['UsuarioApoio'] . " ORDER BY ponto.nome ASC");
                                                }


                                                while ($rowUser = mysql_fetch_array($resultUser)) {
                                                    if ($rowUser['idprod'] == $tablet_edit) {
                                                        $selected = 'selected';
                                                    } else {
                                                        $selected = '';
                                                    }
                                                    echo '<option $selecionado value="' . $rowUser['idprod'] . '" ' . $selected . '  >' . $rowUser['nome'] . '</option>';
                                                }
                                                ?>

                                            </select>
                                        </div>
                                    </div><!-- /.col-lg-4 -->

                                    <div class="col-lg-5">                                             
                                        <div class="form-group input-group" id="datafatura"> 
                                            <span class="input-group-addon"> Data Movimentação</span>  
                                            <div class="input-daterange input-group" id="datepicker">
                                                <input type="text" class="form-control" name="start" id="start" <?php if (!empty($_POST['start'])) echo 'value="' . $_POST['start'] . '"' ?> required />
                                                <span class="input-group-addon">a</span>
                                                <input type="text" class="form-control" name="end" id="end" <?php if (!empty($_POST['end'])) echo 'value="' . $_POST['end'] . '"' ?> required />
                                            </div>
                                        </div>
                                    </div><!-- /.col-lg-4 -->

                                    <div class="col-lg-2">
                                        <button type="submit" class="btn btn-primary" data-loading-text="Loading...">Pesquisar</button>
                                    </div><!-- /.col-lg-6 -->
                                </form>
                            </div> 
                        </div>						
                        <div class="panel-body">
                            <span id="divResultPesquisaMovimentacaoPeriodo"></span>
                            <span id="divErrosPesquisaMovimentacaoPeriodo"></span>
                        </div>
                    </div>
                </div>	
            </div>
        </div> 
        <!-- Fatura -->
        <style>
            .height {
                min-height: 200px;
            }

            .icon {
                font-size: 30px;
                color: #5CB85C;
            }

            .iconbig {
                font-size: 50px;
                color: #08C;
            }

            .table > tbody > tr > .emptyrow {
                border-top: none;
            }

            .table > thead > tr > .emptyrow {
                border-bottom: none;
            }

            .table > tbody > tr > .highrow {
                border-top: 3px solid;
            }
        </style>

        <!-- Page-Level Demo Scripts - Blank - Use for reference -->
        <script>
            $(document).ready(function () {
                $('#dataTables-example').dataTable();
            });

            $(function () {
                $(".btn").click(function () {
                    $(this).button('loading').delay(10000).queue(function () {
                        //$(this).button('reset');
                    });
                });
            });

            $('#user').change(function () {
                $(".btn").button('reset');
            });


            $('#datepicker').change(function () {
                $(".btn").button('reset');
            });


            $('#datafatura .input-daterange').datepicker({
                format: "dd/mm/yyyy",
                todayBtn: "linked",
                language: "pt-BR"
            });

        </script>

        <?php
        break;

    case 'GerenciarAdministradores':

        $nivel_necessario = 1;

        // Verifica se não há a variável da sessão que identifica o usuário
        if (!isset($_SESSION['UsuarioID']) OR ( $_SESSION['UsuarioNivel'] > $nivel_necessario)) {
            // Destrói a sessão por segurança
            session_destroy();
            // Redireciona o visitante de volta pro login
            header("Location: index.php");
            exit;
        }

        require_once("db.php");
        ?>

        <div class="panel-heading" style="min-height:60px" >
            <strong>Administradores</strong>
            <div class="pull-right">
                <button class="btn btn-primary btn-xg pull-right"  data-toggle="modal" data-target="#newuserAdmin">
                    Novo administrador
                </button>
            </div>
        </div>
        <!-- /.panel-heading -->
        <div class="panel-body">

            <div class="table-responsive">
                <table class="table table-striped table-bordered table-hover" id="dataTables-example">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Nome</th>
                            <th>Perfil</th>
                            <th>Login</th>
                            <th>Data Registro</th>
                            <?php
                            if ($_SESSION['UsuarioNivel'] == 1) {
                                echo "<th>Ações</th>";
                            }
                            ?> 

                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        if ($_SESSION['UsuarioNivel'] <= 2) {
                            $resultUser = mysql_query("SELECT id,nome,username,DATE_FORMAT(cadastro,'%d/%m/%Y %H:%i') cadastro,nivel FROM user WHERE nivel IN (1,2) AND status = 1 ORDER BY id DESC");
                        }

                        global $perfil;
                        $i = 1;
                        while ($rowUser = mysql_fetch_array($resultUser)) {
                            if (($rowUser['nivel']) == 1) {
                                $perfil = 'Administrador';
                            }
                            if ($rowUser['nivel'] == 2) {
                                $perfil = 'Sub Admnistrador';
                            }


                            echo "<tr class='gradeA'><td>" . $rowUser['id'] . "</td><td>" . $rowUser['nome'] . "</td><td>" . $perfil . "</td><td>" . $rowUser['username'] . "</td><td>" . $rowUser['cadastro'] . "</td>";
                            if ($_SESSION['UsuarioNivel'] == 1) {
                                ?>

                            <td class='center' style="min-width:146px; width:146px" >
                                <a href="javascript:void(0)" data-id="<?php echo $rowUser['id'] ?>" data-nome="<?php echo $rowUser['nome'] ?>" data-nivel="<?php echo $rowUser['nivel'] ?>" data-login="<?php echo $rowUser['username'] ?>" data-nivel="<?php echo $rowUser['nivel'] ?>" data-toggle="modal" data-target="#edituserAdmin" class='btn btn-success btn-bg' role='button'>
                                    <i class='fa fa-edit fa-fw'></i>
                                </a> 

                                <a class="btn btn-danger btn-bg" data-id="<?php echo $rowUser['id'] ?>" data-toggle="modal" data-target="#deleteAdmin" role='button'><i class='fa fa-times fa-fw' title="Excluir Administrador"></i></a>
                            </td>
                            <?php
                        }
                        $i++;
                    }
                    ?>
                    </tbody>
                </table>
            </div>
        </div>
        <!-- /#wrapper -->

        <!-- /.table-responsive -->
        <!-- /#page-wrapper -->

        <?php include 'newadministrador.php'; ?>
        <?php include 'edit_admin_modal.php'; ?>

        <!-- Modal -->
        <div class="modal fade" id="deleteAdmin" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content modal-lg">							
                    <div class="modal-header bg-danger">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h4 class="modal-title" id="myModalLabel">Deletar Administrador</h4>
                    </div>								
                    <div class="modal-body">    
                        <form id="frmDeleteAdmmin" method="POST">
                            <input type="hidden" name="id" id="id">
                        </form>
                        <h5>Você realmente deseja deletar este Administrador?</h5>											
                    </div>
                    <div class="modal-footer">
                        <button type="button" id="btnCancelDeleteAdmin" class="btn btn-default" data-dismiss="modal">Não</button>
                        <button type="button" id="btnSalvarDeleteAdmin" class="btn btn-danger">Sim</button>                
                    </div>							
                </div>
                <!-- /.modal-content -->
            </div>
            <!-- /.modal-dialog -->
        </div>
        <!-- /.modal -->

        <script>
            $(document).ready(function () {
                $('#dataTables-example').dataTable();
            });

            //triggered when modal is about to be shown
            $('#edituserAdmin').on('show.bs.modal', function (e) {

                //get data-id attribute of the clicked element
                var nome = $(e.relatedTarget).data('nome');
                var id = $(e.relatedTarget).data('id');
                var perfil = $(e.relatedTarget).data('nivel');
                var login = $(e.relatedTarget).data('login');
                var clientId = $(e.relatedTarget).data('client_id');
                var secretID = $(e.relatedTarget).data('secret_id');

                //populate the textbox
                $(e.currentTarget).find('input[name="nome"]').val(nome);
                $(e.currentTarget).find('input[name="id"]').val(id);
                $(e.currentTarget).find('select[name="perfil"]').val(perfil);
                $(e.currentTarget).find('input[name="login"]').val(login);
                $(e.currentTarget).find('input[name="client_id"]').val();
                $(e.currentTarget).find('input[name="secret_id"]').val(login);
            });

            $('#edituserAdmin').on('submit', function (ev) {
                ev.preventDefault();

                $.ajax({
                    type: 'POST',
                    url: "edita_user.php",
                    dataType: 'json',
                    data: $("#edituserAdmin").serialize(),
                    beforeSend: function () {
                        $('#btnSalvarEditClient').attr('disabled', true);
                        $('#btnCancelEditClient').attr('disabled', true);
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        $('#btnSalvarEditClient').attr('disabled', false);
                        $('#btnCancelEditClient').attr('disabled', false);
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {

                        if (data.success) {
                            var priority = 'success';
                            $('#editclient').modal('toggle'); //fechar o modal
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });

            //triggered when modal is about to be shown
            $('#deleteAdmin').on('show.bs.modal', function (e) {

                //get data-id attribute of the clicked element				
                var id = $(e.relatedTarget).data('id');

                //populate the textbox				
                $(e.currentTarget).find('input[name="id"]').val(id);
            });


            $("#btnSalvarDeleteAdmin").click(function (e) {

                $.ajax({
                    type: 'POST',
                    url: "deleta_user.php",
                    dataType: 'json',
                    data: $("#frmDeleteAdmmin").serialize(),
                    beforeSend: function () {
                        $('#btnSalvarDeleteAdmin').attr('disabled', true);
                        $('#btnCancelDeleteAdmin').attr('disabled', true);
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        $('#btnSalvarDeleteAdmin').attr('disabled', false);
                        $('#btnCancelDeleteAdmin').attr('disabled', false);
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {

                        if (data.success) {
                            var priority = 'success';
                            $('#deleteAdmin').modal('toggle'); //fechar o modal
                            fLoadOptionScript('GerenciarAdministradores');
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });
        </script>

        <?php
        break;

    case 'Clientes':

        $nivel_necessario = 2;

        // Verifica se não há a variável da sessão que identifica o usuário
        if (!isset($_SESSION['UsuarioID']) OR ( $_SESSION['UsuarioNivel'] > $nivel_necessario)) {
            // Destrói a sessão por segurança
            session_destroy();
            // Redireciona o visitante de volta pro login
            header("Location: index.php");
            exit;
        }

        require_once("db.php");
        ?>


        <div class="panel-heading" style="min-height:60px">
            <strong>Clientes</strong> 			
            <?php if ($_SESSION['UsuarioNivel'] <= 2) { ?>						
                <button class="btn btn-primary btn-xg pull-right"  data-toggle="modal" data-target="#newuser">
                    Novo cliente
                </button>						
                <?php
            }
            ?>
        </div>
        <!-- /.panel-heading -->
        <div class="panel-body">
            <?php
            if ($_SESSION['UsuarioNivel'] == 1) {
                $resultUser = mysql_query("SELECT id,nome,email, username,porcentagem,telefone,cpf,chave_pix, DATE_FORMAT(cadastro,'%d/%m/%Y %H:%i') cadastro,
										nivel,id_pais, a.status, b.status_txt
										FROM user a
										INNER JOIN user_status b ON b.id_user_status = a.status
										WHERE nivel = 3
										ORDER BY id DESC");
            }
            if ($_SESSION['UsuarioNivel'] == 2) {
                $resultUser = mysql_query("SELECT id,nome, email, username,porcentagem,telefone,cpf,chave_pix, DATE_FORMAT(cadastro,'%d/%m/%Y %H:%i') cadastro,
										nivel,id_pais, status, b.status_txt  
										FROM user a
										INNER JOIN user_status b ON b.id_user_status = a.`status`
										WHERE nivel = 3 AND status IN (1) AND a.id_apoio = " . $_SESSION['UsuarioID'] . "
										ORDER BY id DESC");
            }

            if (mysql_num_rows($resultUser) > 0) {
                ?>


                <div class="table-responsive">
                    <table class="table table-striped table-bordered table-hover" id="dataTables-example">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Nome</th>
                                <th>E-mail</th>
                                <th>Telefone</th>
                                <th>Login</th>
                                <th>%</th>
                                <th>Data Registro</th>
                                <th>Status</th>
                                <?php
                                if ($_SESSION['UsuarioNivel'] == 1) {
                                    echo "<th>Ações</th>";
                                }
                                ?> 

                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            global $perfil;
                            $i = 1;
                            while ($rowUser = mysql_fetch_array($resultUser)) {

                                $disabledButton = "";
                                $disabledButton2 = "";
                                if ($rowUser['status'] == 1) {
                                    $statusTexto = '<span class="text-success" >' . $rowUser['status_txt'] . '</span>';
                                } else if ($rowUser['status'] == 2) {
                                    $statusTexto = '<span class="text-warning" >' . $rowUser['status_txt'] . '</span>';
                                } else {
                                    $statusTexto = '<span style="opacity: 0.80 !important; color: #5C3333;" >' . $rowUser['status_txt'] . '</span>';
                                    if ($_SESSION['UsuarioNivel'] != 1) {
                                        $disabledButton = 'disabled';
                                    }
                                    $disabledButton2 = 'disabled';
                                }
                                // 
                                echo "<tr class='gradeA'>"
                                . "<td>" . $rowUser['id'] . "</td><td>" . $rowUser['nome'] . "</td>"
                                . "<td>" . $rowUser['email'] . "</td>"
                                . "<td>" . $rowUser['telefone'] . "</td>"
                                . "<td>" . $rowUser['username'] . "</td><td>" . $rowUser['porcentagem'] . "</td><td>" . $rowUser['cadastro'] . "Hs</td><td>" . $statusTexto . "</td>";
                                if ($_SESSION['UsuarioNivel'] == 1) {
                                    ?>																
                                <td class='center' style="min-width:166px; width:166px">												
                                    <a class='btn btn-primary btn-bg <?php echo $disabledButton ?>' 
                                       data-perfil="<?php echo $rowUser['nivel'] ?>" 
                                       data-id="<?php echo $rowUser['id'] ?>" 
                                       data-nome="<?php echo $rowUser['nome'] ?>" 
                                       data-telefone="<?php echo $rowUser['telefone'] ?>" 
                                       data-email="<?php echo $rowUser['email'] ?>" 
                                       data-id_pais="<?php echo $rowUser['id_pais'] ?>" 
                                       data-status="<?php echo $rowUser['status'] ?>" 
                                       data-porcent="<?php echo $rowUser['porcentagem'] ?>" 
                                       data-client="<?php echo $rowUser['cpf'] ?>" 
                                       data-secret="<?php echo $rowUser['chave_pix'] ?>" 
                                       data-toggle="modal" 
                                       data-target="#editclient" role='button' title="Alterar dados pessoais"><i class='fa fa-edit fa-fw' ></i>
                                    </a>
																	
                                    <a class="btn btn-success btn-bg <?php echo $disabledButton2 ?>" data-login="<?php echo $rowUser['username'] ?>" data-id="<?php echo $rowUser['id'] ?>" data-nome="<?php echo $rowUser['nome'] ?>"  data-client="<?php echo $rowUser['cpf'] ?>"  data-secret="<?php echo $rowUser['chave_pix'] ?>"  data-toggle="modal" data-target="#editcredentialsuser" role='button'><i class='fa fa-unlock-alt fa-fw' title="Alterar dados de acesso"></i></a>											

                                    <a class="btn btn-danger btn-bg <?php echo $disabledButton2 ?>" data-id="<?php echo $rowUser['id'] ?>" data-toggle="modal" data-target="#deleteclient" role='button'><i class='fa fa-times fa-fw' title="Excluir Cliente"></i></a>												

                                </td>										
                                <?php
                            }
                            ?>
                            </tr>
                            <?php
                            $i++;
                        }
                        ?>
                        </tbody>
                    </table>
                </div>
                <!-- /.table-responsive -->
                <!-- /#page-wrapper -->
                <?php include 'newcliente.php'; ?>
                <?php include 'edit_credentials_client_modal.php'; ?>
                <?php include 'edit_client_modal.php'; ?>						
                <!-- Modal -->
                <div class="modal fade" id="deleteclient" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                    <div class="modal-dialog">
                        <div class="modal-content">							
                            <div class="modal-header bg-danger">
                                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                                <h4 class="modal-title" id="myModalLabel">Deletar Cliente</h4>
                            </div>								
                            <div class="modal-body">    
                                <form id="frmDeleteClient" method="POST">
                                    <input type="hidden" name="id" id="id">
                                </form>

                                <h5>Você realmente deseja deletar este Cliente?</h5>

                            </div>
                            <div class="modal-footer">
                                <button type="button" id="btnCancelDeleteClient" class="btn btn-default" data-dismiss="modal">Não</button>
                                <button type="button" id="btnSalvarDeleteClient" class="btn btn-danger">Sim</button>                
                            </div>							
                        </div>
                        <!-- /.modal-content -->
                    </div>
                    <!-- /.modal-dialog -->
                </div>
                <!-- /.modal -->
            <?php } else {
                ?>
                <div class='alert alert-warning'>Nenhum Cliente Cadastrado.</div>
                <?php
            }
            ?>

        </div>
        <!-- /#wrapper -->


        <script>
            $(document).ready(function () {
                $('#dataTables-example').dataTable();
            });

            //triggered when modal is about to be shown
            $('#editcredentialsuser').on('show.bs.modal', function (e) {


                //get data-id attribute of the clicked element
                var nome = $(e.relatedTarget).data('nome');
                var id = $(e.relatedTarget).data('id');
                var login = $(e.relatedTarget).data('login');
                var porcentagem = $(e.relatedTarget).data('porcentagem');
								var client = $(e.relatedTarget).data('client');
                var secret = $(e.relatedTarget).data('secret');


                //populate the textbox
                $(e.currentTarget).find('input[name="nome"]').val(nome);
                $(e.currentTarget).find('input[name="id"]').val(id);
                $(e.currentTarget).find('input[name="login"]').val(login);
                $(e.currentTarget).find('input[name="pocentagem"]').val(porcentagem);
								$(e.currentTarget).find('input[name="client_id"]').val(client);
                $(e.currentTarget).find('input[name="secret_id"]').val(secret);
            });


            //triggered when modal is about to be shown
            $('#editclient').on('show.bs.modal', function (e) {

                //get data-id attribute of the clicked element
                var nome = $(e.relatedTarget).data('nome');
                var email = $(e.relatedTarget).data('email');
                var id = $(e.relatedTarget).data('id');
                var perfil = $(e.relatedTarget).data('perfil');
                var id_pais = $(e.relatedTarget).data('id_pais');
                var status = $(e.relatedTarget).data('status');
                var porcent = $(e.relatedTarget).data('porcent');
                var telefone = $(e.relatedTarget).data('telefone');
                var client = $(e.relatedTarget).data('client');
                var secret = $(e.relatedTarget).data('secret');

                //populate the textbox
                $(e.currentTarget).find('input[name="nome"]').val(nome);
                $(e.currentTarget).find('input[name="telefone"]').val(telefone);
                $(e.currentTarget).find('input[name="email"]').val(email);
                $(e.currentTarget).find('input[name="id"]').val(id);
                $(e.currentTarget).find('input[name="perfil"]').val(perfil);
                $(e.currentTarget).find('select[name="id_pais"]').val(id_pais);
                $(e.currentTarget).find('select[name="status"]').val(status);
                $(e.currentTarget).find('input[name="porcent"]').val(porcent);
                $(e.currentTarget).find('input[name="client_id"]').val(client);
                $(e.currentTarget).find('input[name="secret_id"]').val(secret);
            });


            //triggered when modal is about to be shown
            $('#deleteclient').on('show.bs.modal', function (e) {

                //get data-id attribute of the clicked element				
                var id = $(e.relatedTarget).data('id');

                //populate the textbox				
                $(e.currentTarget).find('input[name="id"]').val(id);
            });


            $("#btnSalvarDeleteClient").click(function (e) {

                $.ajax({
                    type: 'POST',
                    url: "deleta_user.php",
                    dataType: 'json',
                    data: $("#frmDeleteClient").serialize(),
                    beforeSend: function () {
                        $('#btnSalvarEditClient').attr('disabled', true);
                        $('#btnCancelEditClient').attr('disabled', true);
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        $('#btnSalvarEditClient').attr('disabled', false);
                        $('#btnCancelEditClient').attr('disabled', false);
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {

                        if (data.success) {
                            var priority = 'success';
                            $('#deleteclient').modal('toggle'); //fechar o modal
                            fLoadOptionScript('Clientes');
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });


            $('#frmEditClient').on('submit', function (ev) {
                ev.preventDefault();

                $.ajax({
                    type: 'POST',
                    url: "edita_user.php",
                    dataType: 'json',
                    data: $("#frmEditClient").serialize(),
                    beforeSend: function () {
                        $('#btnSalvarEditClient').attr('disabled', true);
                        $('#btnCancelEditClient').attr('disabled', true);
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        $('#btnSalvarEditClient').attr('disabled', false);
                        $('#btnCancelEditClient').attr('disabled', false);
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {

                        if (data.success) {
                            var priority = 'success';
                            $('#editclient').modal('toggle'); //fechar o modal
                            fLoadOptionScript('Clientes');
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });


            $('#frmNewClient').on('submit', function (ev) {
                ev.preventDefault();

                $.ajax({
                    type: 'POST',
                    url: "add_user.php",
                    dataType: 'json',
                    data: $("#frmNewClient").serialize(),
                    beforeSend: function () {
                        $('#btnSalvarEditClient').attr('disabled', true);
                        $('#btnCancelEditClient').attr('disabled', true);
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        $('#btnSalvarEditClient').attr('disabled', false);
                        $('#btnCancelEditClient').attr('disabled', false);
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {

                        if (data.success) {
                            var priority = 'success';
                            $('#newuser').modal('toggle'); //fechar o modal
                            fLoadOptionScript('Clientes');
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });

            $('#frmCredentialsClient').on('submit', function (ev) {
                ev.preventDefault();

                $.ajax({
                    type: 'POST',
                    url: "edit_credentials_user_db.php",
                    dataType: 'json',
                    data: $("#frmCredentialsClient").serialize(),
                    beforeSend: function () {
                        $('#btnSalvarEditCredentials').attr('disabled', true);
                        $('#btnCancelEditCredentials').attr('disabled', true);
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        $('#btnSalvarEditCredentials').attr('disabled', false);
                        $('#btnCancelEditCredentials').attr('disabled', false);
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {

                        if (data.success) {
                            var priority = 'success';
                            $('#editcredentialsuser').modal('toggle'); //fechar o modal
                            fLoadOptionScript('Clientes');
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });
        </script>
        <?php
        break;

    case 'Socios':
        $nivel_necessario = 3;
        //$nivel_necessario = 4;
        // Verifica se não há a variável da sessão que identifica o usuário
        if (!isset($_SESSION['UsuarioID']) OR ( $_SESSION['UsuarioNivel'] > $nivel_necessario)) {
            // Destrói a sessão por segurança
            session_destroy();
            // Redireciona o visitante de volta pro login
            header("Location: index.php");
            exit;
        }

        require_once("db.php");
        ?>

        <div class="panel-heading" style="min-height:60px" >
            <strong>Sócios</strong>						
            <?php if (($_SESSION['UsuarioNivel'] == 1) OR ( $_SESSION['UsuarioNivel'] == 3)) { ?>							
                <div class="pull-right">
                    <button class="btn btn-primary btn-bg"  data-toggle="modal" data-target="#newsocio">
                        Novo sócio
                    </button>
                </div>
                <?php
            }
            ?>
        </div>
        <!-- /.panel-heading -->
        <div class="panel-body">

            <div class="table-responsive">
                <table class="table table-striped table-bordered table-hover" id="dataTables-example">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Nome</th>
                            <th>Login</th>
                            <?php
                            if ($_SESSION['UsuarioNivel'] <= 2) {
                                echo "<th>Cliente</th>";
                            }
                            ?> 
                            <th>Data Registro</th>
                            <?php
                            if (($_SESSION['UsuarioNivel'] == 1) OR ( $_SESSION['UsuarioNivel'] == 3)OR ( $_SESSION['UsuarioNivel'] == 4)) {
                                echo "<th>Ações</th>";
                            }
                            ?> 

                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        if ($_SESSION['UsuarioNivel'] == 1) {
                            $resultUser = mysql_query("SELECT s.id id,s.nome nome,s.username username,u.username apoio,s.porcentagem,"
                                    . " DATE_FORMAT(s.cadastro,'%d/%m/%Y %H:%i') cadastro,s.nivel nivel, s.id_apoio ,s.status "
                                    . " FROM user s, user u WHERE s.nivel = 4 "
                                    . " AND s.id_apoio = u.id "
                                    . " AND s.status = 1 "
                                    . " ORDER BY s.id DESC"); //
                        }
                        if ($_SESSION['UsuarioNivel'] == 2) {
                            //
                            $resultUser = mysql_query("SELECT s.id id,s.nome nome,s.username username,u.username apoio,s.porcentagem"
                                    . " DATE_FORMAT(s.cadastro,'%d/%m/%Y %H:%i') cadastro,s.nivel nivel, s.id_apoio , s.status"
                                    . " FROM user s, user u "
                                    . " WHERE s.nivel = 4 AND s.id_apoio = u.id "
                                    . " AND u.id_apoio = " . $_SESSION['UsuarioID'] . " AND s.status = 1  ORDER BY s.id DESC");
                        }
                        if ($_SESSION['UsuarioNivel'] == 3) {
                            $resultUser = mysql_query("SELECT s.id id,s.nome nome,s.username username,s.porcentagem,cpf,chave_pix"
                                    . " DATE_FORMAT(s.cadastro,'%d/%m/%Y %H:%i') cadastro,s.nivel nivel, s.id_apoio ,s.status "
                                    . " FROM user s "
                                    . " WHERE s.nivel = 4 "
                                    . " AND s.id_apoio = " . $_SESSION['UsuarioID']
                                    . " ORDER BY s.id DESC"); //AND s.status = 1
                        }
                        // global $perfil;
                        // print_r(mysql_fetch_array($resultUser));

                        $i = 1;
                        while ($rowUser = mysql_fetch_array($resultUser)) {

                            echo "<tr class='gradeA'><td>" . $rowUser['id'] . "</td><td>" . $rowUser['nome'] . "</td><td>" . $rowUser['username'] . "</td>";
                            if ($_SESSION['UsuarioNivel'] <= 2) {
                                echo "<td>" . $rowUser['apoio'] . "</td>";
                            }
                            echo " <td>" . $rowUser['cadastro'] . "</td>";


                            if (($_SESSION['UsuarioNivel'] == 1) OR ( $_SESSION['UsuarioNivel'] == 3) || $_SESSION['UsuarioNivel'] == 4) {

                                echo '<td style="min-width: 165px; width: 165px">';
                                ?>

                            <a class="btn btn-success btn-bg" 
                               data-apoio="<?php echo $rowUser['id_apoio'] ?>" 
                               data-login="<?php echo $rowUser['username'] ?>" 
                               data-porcent="<?php echo $rowUser['porcentagem'] ?>"
                               data-id="<?php echo $rowUser['id'] ?>" 
                               data-nome="<?php echo $rowUser['nome'] ?>" 
                               data-status="<?php echo $rowUser['status'] ?>"

                               data-toggle="modal" data-target="#editsociomodal" role='button'><i class='fa fa-unlock-alt fa-fw' title="Alterar dados do Socio"></i>
                            </a>											

                            <a class="btn btn-danger btn-bg" data-id="<?php echo $rowUser['id'] ?>" data-toggle="modal" data-target="#deletesocio" role='button'><i class='fa fa-times fa-fw' title="Excluir Socio"></i></a>												
                            <?php
                            echo "</td>";
                        }


                        $i ++;
                    }
                    ?>
                    </tbody>
                </table>
            </div>
            <!-- /.table-responsive -->
            <!-- /#page-wrapper -->
        </div>
        <!-- /#wrapper -->

        <?php include 'newsocio.php'; ?>
        <?php include 'editsocio.php'; ?>

        <!-- Modal -->
        <div class="modal fade" id="deletesocio" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">							
                    <div class="modal-header bg-danger">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h4 class="modal-title" id="myModalLabel">Deletar Sócio</h4>
                    </div>								
                    <div class="modal-body">    
                        <form id="frmDeleteSocio" method="POST">
                            <input type="hidden" name="id" id="id">
                        </form>

                        <h5>Você realmente deseja deletar este Sócio?</h5>

                    </div>
                    <div class="modal-footer">
                        <button type="button" id="btnCancelDeleteSocio" class="btn btn-default" data-dismiss="modal">Não</button>
                        <button type="button" id="btnSalvarDeleteSocio" class="btn btn-danger">Sim</button>                
                    </div>							
                </div>
                <!-- /.modal-content -->
            </div>
            <!-- /.modal-dialog -->
        </div>
        <!-- /.modal -->
        <script>

            $(document).ready(function () {
                $('#dataTables-example').dataTable();
            });

            $('#frmNewSocio').on('submit', function (ev) {
                ev.preventDefault();

                $.ajax({
                    type: 'POST',
                    url: "add_user.php",
                    dataType: 'json',
                    data: $("#frmNewSocio").serialize(),
                    beforeSend: function () {
                        $('#btnSalvarNewSocio').attr('disabled', true);
                        $('#btnCancelarNewSocio').attr('disabled', true);
                        $.blockUI({
                            message: $("#loading-indicator"),
                            // css: { 
                            // top:  ($(window).height() - 25) /2 + 'px', 
                            // left: ($(window).width() - 25) /2 + 'px', 
                            // width: '25px',
                            // border: 0
                            // } 
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        $('#btnSalvarNewSocio').attr('disabled', false);
                        $('#btnCancelarNewSocio').attr('disabled', false);
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {

                        if (data.success) {
                            var priority = 'success';
                            $('#newsocio').modal('toggle'); //fechar o modal
                            fLoadOptionScript('Socios');
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });


            //triggered when modal is about to be shown
            $('#editsociomodal').on('show.bs.modal', function (e) {

                //get data-id attribute of the clicked element
                var nome = $(e.relatedTarget).data('nome');
                var id = $(e.relatedTarget).data('id');
                var login = $(e.relatedTarget).data('login');
                var apoio = $(e.relatedTarget).data('apoio');
                var porcentagem = $(e.relatedTarget).data('porcent');
                var status = $(e.relatedTarget).data('status');

                //populate the textbox
                $(e.currentTarget).find('input[name="nome"]').val(nome);
                $(e.currentTarget).find('input[name="id"]').val(id);
                $(e.currentTarget).find('input[name="login"]').val(login);
                $(e.currentTarget).find('select[name="apoio"]').val(apoio);
                $(e.currentTarget).find('input[name="porcent"]').val(porcentagem);
                $(e.currentTarget).find('select[name="status"]').val(status);

            });





            //triggered when modal is about to be shown
            $('#deletesocio').on('show.bs.modal', function (e) {

                //get data-id attribute of the clicked element				
                var id = $(e.relatedTarget).data('id');

                //populate the textbox				
                $(e.currentTarget).find('input[name="id"]').val(id);
            });


            $("#btnSalvarDeleteSocio").click(function (e) {

                $.ajax({
                    type: 'POST',
                    url: "deleta_user.php",
                    dataType: 'json',
                    data: $("#frmDeleteSocio").serialize(),
                    beforeSend: function () {
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {

                        if (data.success) {
                            var priority = 'success';
                            $('#deletesocio').modal('toggle'); //fechar o modal
                            fLoadOptionScript('Socios');
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });


            $('#frmEditSocio').on('submit', function (ev) {
                ev.preventDefault();

                $.ajax({
                    type: 'POST',
                    url: "edita_socio.php",
                    dataType: 'json',
                    data: $("#frmEditSocio").serialize(),
                    beforeSend: function () {
                        $('#btnSalvarEditClient').attr('disabled', true);
                        $('#btnCancelEditClient').attr('disabled', true);
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        $('#btnSalvarEditClient').attr('disabled', false);
                        $('#btnCancelEditClient').attr('disabled', false);
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {

                        if (data.success) {
                            var priority = 'success';
                            $('#editsociomodal').modal('toggle'); //fechar o modal
                            fLoadOptionScript('Socios');
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });
        </script>

        <?php
        break;

    case 'Operadores':

        //$nivel_necessario = 3;
        $nivel_necessario = 4;
        // Verifica se não há a variável da sessão que identifica o usuário
        if (!isset($_SESSION['UsuarioID']) OR ( $_SESSION['UsuarioNivel'] > $nivel_necessario)) {
            // Destrói a sessão por segurança
            session_destroy();
            // Redireciona o visitante de volta pro login
            header("Location: index.php");
            exit;
        }

        require_once("db.php");
        ?>


        <div class="panel-heading" style="min-height:60px">
            <strong>Operadores</strong>						
            <?php if (($_SESSION['UsuarioNivel'] == 1) OR ( $_SESSION['UsuarioNivel'] == 3) OR ( $_SESSION['UsuarioNivel'] == 4)) { ?>							
                <div class="pull-right" >
                    <button class="btn btn-primary"  data-toggle="modal" data-target="#newoperador">
                        Novo operador
                    </button>
                </div>
            <?php }
            ?>
        </div>
        <!-- /.panel-heading -->
        <div class="panel-body">

            <div class="table-responsive">
                <table class="table table-striped table-bordered table-hover" id="dataTables-example">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Nome</th>
                            <th>Login</th>
                            <?php
                            if ($_SESSION['UsuarioNivel'] <= 2) {
                                echo "<th>Ponto</th>";
                            }
                            ?> 
                            <th>Data Registro</th>
                            <?php
                            if (($_SESSION['UsuarioNivel'] == 1) OR ( $_SESSION['UsuarioNivel'] == 3) OR ( $_SESSION['UsuarioNivel'] == 4)) {
                                echo "<th>Ações</th>";
                            }
                            ?> 

                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        if ($_SESSION['UsuarioNivel'] == 1) {
                            $resultUser = mysql_query("SELECT u.id id,u.nome nome,u.username username,"
                                    . " p.nome apoio,DATE_FORMAT(u.cadastro,'%d/%m/%Y %H:%i') cadastro,"
                                    . " u.nivel nivel, u.id_apoio, fechar_faturas_ponto FROM user u, ponto p "
                                    . " WHERE u.nivel = 6 AND u.id_apoio = p.id AND u.status = 1 ORDER BY u.id DESC");
                        }
                        if ($_SESSION['UsuarioNivel'] == 2) {
                            $resultUser = mysql_query("SELECT u.id id,u.nome nome,u.username username,p.nome apoio,DATE_FORMAT(u.cadastro,'%d/%m/%Y %H:%i') cadastro,u.nivel nivel, u.id_apoio, fechar_faturas_ponto FROM user u, ponto p, user x WHERE u.nivel = 6 AND u.id_apoio = p.id AND p.id_apoio = x.id AND x.id_apoio = " . $_SESSION['UsuarioID'] . " AND u.status = 1 ORDER BY u.id DESC");
                        }
                        if ($_SESSION['UsuarioNivel'] == 3) {
                            $apoios = getApoios($_SESSION['UsuarioID']);
//                            echo "SELECT u.id id,u.nome nome,u.username username,p.nome apoio,DATE_FORMAT(u.cadastro,'%d/%m/%Y %H:%i') cadastro,u.nivel nivel, u.id_apoio, fechar_faturas_ponto
//							FROM user u, ponto p 
//							WHERE u.nivel = 6 
//							AND u.id_apoio = p.id
//							AND p.id_apoio IN ( " . implode(',', $apoios) . ") 
//							AND u.status = 1 ORDER BY u.id DESC";exit;
                            $resultUser = mysql_query("SELECT u.id id,u.nome nome,u.username username,p.nome apoio,DATE_FORMAT(u.cadastro,'%d/%m/%Y %H:%i') cadastro,u.nivel nivel, u.id_apoio, fechar_faturas_ponto
							FROM user u, ponto p 
							WHERE u.nivel = 6 
							AND u.id_apoio = p.id
							AND p.id_apoio IN ( " . implode(',', $apoios) . ") 
							AND u.status = 1 ORDER BY u.id DESC");
                        }
                        if ($_SESSION['UsuarioNivel'] == 4) {

                            $resultUser = mysql_query("SELECT u.id id,u.nome nome,u.username username,p.nome apoio,DATE_FORMAT(u.cadastro,'%d/%m/%Y %H:%i') cadastro,u.nivel nivel, u.id_apoio, fechar_faturas_ponto
							FROM user u, ponto p 
							WHERE u.nivel = 6 
							AND u.id_apoio = p.id
							AND p.id_apoio = " . $_SESSION['UsuarioID'] . " 
							AND u.status = 1 ORDER BY u.id DESC");
                        }
                        global $perfil;
                        $i = 1;
                        while ($rowUser = mysql_fetch_array($resultUser)) {

                            echo "<tr class='gradeA'><td>" . $rowUser['id'] . "</td><td>" . $rowUser['nome'] . "</td><td>" . $rowUser['username'] . "</td>";
                            if ($_SESSION['UsuarioNivel'] <= 2) {
                                echo "<td>" . $rowUser['apoio'] . "</td>";
                            }
                            echo " <td>" . $rowUser['cadastro'] . "</td>";

                            echo '<td style="min-width: 165px; width: 165px">';
                            if (($_SESSION['UsuarioNivel'] == 1) OR ( $_SESSION['UsuarioNivel'] == 3) OR ( $_SESSION['UsuarioNivel'] == 4)) {
                                ?>

                            <a class="btn btn-success btn-bg" 
                               data-apoio="<?php echo $rowUser['id_apoio'] ?>" 
                               data-fechar="<?php echo $rowUser['fechar_faturas_ponto'] ?>" 
                               data-login="<?php echo $rowUser['username'] ?>" 
                               data-id="<?php echo $rowUser['id'] ?>" 
                               data-nome="<?php echo $rowUser['nome'] ?>" 

                               data-toggle="modal" data-target="#editoperadormodal" role='button'><i class='fa fa-unlock-alt fa-fw' title="Alterar dados do Operador"></i>
                            </a>											

                            <a class="btn btn-danger btn-bg" data-id="<?php echo $rowUser['id'] ?>" data-toggle="modal" data-target="#deletoperador" role='button'><i class='fa fa-times fa-fw' title="Excluir Operador"></i></a>												
                            <?php
                        }
                        echo "</td>";

                        $i ++;
                    }
                    ?>
                    </tbody>
                </table>
            </div>
            <!-- /.table-responsive -->
            <!-- /#page-wrapper -->

            <?php include 'newoperador.php'; ?>
            <?php include 'editoperador.php'; ?>
            <!-- Modal -->
            <div class="modal fade" id="deletoperador" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">							
                        <div class="modal-header bg-danger">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                            <h4 class="modal-title" id="myModalLabel">Deletar Operador</h4>
                        </div>								
                        <div class="modal-body">    
                            <form id="frmDeleteOperador" method="POST">
                                <input type="hidden" name="id" id="id">
                            </form>

                            <h5>Você realmente deseja deletar este Operador?</h5>

                        </div>
                        <div class="modal-footer">
                            <button type="button" id="btnCancelDeleteOperador" class="btn btn-default" data-dismiss="modal">Não</button>
                            <button type="button" id="btnSalvarDeleteOperador" class="btn btn-danger">Sim</button>                
                        </div>							
                    </div>
                    <!-- /.modal-content -->
                </div>
                <!-- /.modal-dialog -->
            </div>
            <!-- /.modal -->
        </div>
        <!-- /#wrapper -->					
        <script>
            $(document).ready(function () {
                $('#dataTables-example').dataTable();
            });

            $('#frmNewOperador').on('submit', function (ev) {
                ev.preventDefault();

                $.ajax({
                    type: 'POST',
                    url: "add_user.php",
                    dataType: 'json',
                    data: $("#frmNewOperador").serialize(),
                    beforeSend: function () {
                        $('#btnSalvarNewOperador').attr('disabled', true);
                        $('#btnCancelarNewOperador').attr('disabled', true);
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        $('#btnSalvarNewOperador').attr('disabled', false);
                        $('#btnCancelarNewOperador').attr('disabled', false);
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {

                        if (data.success) {
                            var priority = 'success';
                            $('#newoperador').modal('toggle'); //fechar o modal
                            fLoadOptionScript('Operadores');
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });

            //triggered when modal is about to be shown
            $('#editoperadormodal').on('show.bs.modal', function (e) {

                //get data-id attribute of the clicked element
                var nome = $(e.relatedTarget).data('nome');
                var id = $(e.relatedTarget).data('id');
                var login = $(e.relatedTarget).data('login');
                var apoio = $(e.relatedTarget).data('apoio');
                var fechar = $(e.relatedTarget).data('fechar');

                console.log(fechar);


                //populate the textbox
                $(e.currentTarget).find('input[name="nome"]').val(nome);
                $(e.currentTarget).find('input[name="id"]').val(id);
                $(e.currentTarget).find('input[name="login"]').val(login);
                $(e.currentTarget).find('select[name="apoio"]').val(apoio);
                $(e.currentTarget).find('select[name="fecharFaturasPonto"]').val(fechar);
            });


            //triggered when modal is about to be shown
            $('#deletoperador').on('show.bs.modal', function (e) {

                //get data-id attribute of the clicked element				
                var id = $(e.relatedTarget).data('id');

                //populate the textbox				
                $(e.currentTarget).find('input[name="id"]').val(id);
            });


            $("#btnSalvarDeleteOperador").click(function (e) {

                $.ajax({
                    type: 'POST',
                    url: "deleta_user.php",
                    dataType: 'json',
                    data: $("#frmDeleteOperador").serialize(),
                    beforeSend: function () {
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {

                        if (data.success) {
                            var priority = 'success';
                            $('#deletoperador').modal('toggle'); //fechar o modal
                            fLoadOptionScript('Operadores');
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });


            $('#frmEditarOperador').on('submit', function (ev) {
                ev.preventDefault();

                $.ajax({
                    type: 'POST',
                    url: "edita_socio.php",
                    dataType: 'json',
                    data: $("#frmEditarOperador").serialize(),
                    beforeSend: function () {
                        $('#btnSalvarEditOperador').attr('disabled', true);
                        $('#btnCancelEditOperador').attr('disabled', true);
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        $('#btnSalvarEditOperador').attr('disabled', false);
                        $('#btnCancelEditOperador').attr('disabled', false);
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {

                        if (data.success) {
                            var priority = 'success';
                            $('#editoperadormodal').modal('toggle'); //fechar o modal
                            fLoadOptionScript('Operadores');
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });

        </script>
        <?php
        break;

    case 'Funcionarios':

        //$nivel_necessario = 3;
        $nivel_necessario = 4;
        // Verifica se não há a variável da sessão que identifica o usuário
        if (!isset($_SESSION['UsuarioID']) OR ( $_SESSION['UsuarioNivel'] > $nivel_necessario)) {
            // Destrói a sessão por segurança
            session_destroy();
            // Redireciona o visitante de volta pro login
            header("Location: index.php");
            exit;
        }

        require_once("db.php");
        ?>

        <div class="panel-heading" style="min-height:60px" >
            <strong>Funcionários</strong>

            <?php if (($_SESSION['UsuarioNivel'] == 1) OR ( $_SESSION['UsuarioNivel'] == 3)OR ( $_SESSION['UsuarioNivel'] == 4)) { ?>

                <div class="pull-right">
                    <button class="btn btn-primary"  data-toggle="modal" data-target="#newfuncionario">
                        Novo Funcionário
                    </button>
                </div>
            <?php } ?>
        </div>
        <!-- /.panel-heading -->
        <div class="panel-body">

            <div class="table-responsive">
                <table class="table table-striped table-bordered table-hover" id="dataTables-example">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Nome</th>
                            <th>Login</th>
                            <?php
                            if ($_SESSION['UsuarioNivel'] <= 2) {
                                echo "<th>Ponto</th>";
                            }
                            ?> 
                            <th>Data Registro</th>
                            <?php
                            if (($_SESSION['UsuarioNivel'] == 1) OR ( $_SESSION['UsuarioNivel'] == 3) OR ( $_SESSION['UsuarioNivel'] == 4)) {
                                echo "<th>Ações</th>";
                            }
                            ?> 

                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        if ($_SESSION['UsuarioNivel'] == 1) {
                            $resultUser = mysql_query("SELECT u.id id_func,u.nome nome,u.username username, p.id, p.nome apoio,DATE_FORMAT(u.cadastro,'%d/%m/%Y %H:%i') cadastro,u.nivel nivel, p.id as id_ponto FROM user u, ponto p WHERE u.nivel = 5 AND u.id_apoio = p.id AND u.status = 1 ORDER BY u.id DESC");
                        }
                        if ($_SESSION['UsuarioNivel'] == 2) {
                            $resultUser = mysql_query("SELECT u.id id_func,u.nome nome,u.username username, p.id, p.nome apoio,DATE_FORMAT(u.cadastro,'%d/%m/%Y %H:%i') cadastro,u.nivel nivel, p.id as id_ponto FROM user u, ponto p, user x WHERE u.nivel = 5 AND u.id_apoio = p.id AND p.id_apoio = x.id AND x.id_apoio = " . $_SESSION['UsuarioID'] . " AND u.status = 1 ORDER BY u.id DESC");
                        }
                        if ($_SESSION['UsuarioNivel'] == 3 || $_SESSION['UsuarioNivel'] == 4) {
                            $resultUser = mysql_query("SELECT u.id id_func,u.nome nome,u.username username, p.id, p.nome apoio,DATE_FORMAT(u.cadastro,'%d/%m/%Y %H:%i') cadastro,u.nivel nivel, p.id as id_ponto FROM user u, ponto p WHERE u.nivel = 5 AND u.id_apoio = p.id AND p.id_apoio = " . $_SESSION['UsuarioID'] . " AND u.status = 1 ORDER BY u.id DESC");
                        }
                        global $perfil;
                        $i = 1;
                        while ($rowUser = mysql_fetch_array($resultUser)) {

                            echo "<tr class='gradeA'><td>" . $rowUser['id_func'] . "</td><td>" . $rowUser['nome'] . "</td><td>" . $rowUser['username'] . "</td>";
                            if ($_SESSION['UsuarioNivel'] <= 2) {
                                echo "<td>" . $rowUser['apoio'] . "</td>";
                            }

                            echo " <td>" . $rowUser['cadastro'] . "</td>";
                            echo '<td style="min-width: 15px; width: 165px">';

                            if (($_SESSION['UsuarioNivel'] == 1) OR ( $_SESSION['UsuarioNivel'] == 3) OR ( $_SESSION['UsuarioNivel'] == 4)) {
                                ?>

                            <a class="btn btn-success btn-bg" 
                               data-apoio="<?php echo $rowUser['id_ponto'] ?>" 
                               data-login="<?php echo $rowUser['username'] ?>" 
                               data-id="<?php echo $rowUser['id_func'] ?>" 
                               data-nome="<?php echo $rowUser['nome'] ?>" 
                               data-toggle="modal" data-target="#editfuncionariomodal" role='button'><i class='fa fa-unlock-alt fa-fw' title="Alterar dados do Funcionário"></i>
                            </a>											

                            <a class="btn btn-danger btn-bg" data-id="<?php echo $rowUser['id_func'] ?>" data-toggle="modal" data-target="#deletfuncionario" role='button'><i class='fa fa-times fa-fw' title="Excluir Funcionário"></i></a>												
                            <?php
                        }
                        echo "</td>";

                        $i ++;
                    }
                    ?>
                    </tbody>
                </table>
            </div>
            <!-- /.table-responsive -->
            <!-- /#page-wrapper -->
            <?php include 'newfuncionario.php'; ?>
            <?php include 'editfuncionario.php'; ?>

            <!-- Modal -->
            <div class="modal fade" id="deletfuncionario" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">							
                        <div class="modal-header bg-danger">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                            <h4 class="modal-title" id="myModalLabel">Deletar Operador</h4>
                        </div>								
                        <div class="modal-body">    
                            <form id="frmDeleteFuncionario" method="POST">
                                <input type="hidden" name="id" id="id">
                            </form>

                            <h5>Você realmente deseja deletar este Operador?</h5>

                        </div>
                        <div class="modal-footer">
                            <button type="button" id="btnCancelDeleteFuncionario" class="btn btn-default" data-dismiss="modal">Não</button>
                            <button type="button" id="btnSalvarDeleteFuncionario" class="btn btn-danger">Sim</button>                
                        </div>							
                    </div>
                    <!-- /.modal-content -->
                </div>
                <!-- /.modal-dialog -->
            </div>
            <!-- /.modal -->
        </div>
        <!-- /#wrapper -->

        <script>

            $(document).ready(function () {
                $('#dataTables-example').dataTable();
            });

            $('#frmNewFuncionario').on('submit', function (ev) {
                ev.preventDefault();

                $.ajax({
                    type: 'POST',
                    url: "add_user.php",
                    dataType: 'json',
                    data: $("#frmNewFuncionario").serialize(),
                    beforeSend: function () {
                        $('#btnSalvarNewFuncionario').attr('disabled', true);
                        $('#btnCancelarNewFuncionario').attr('disabled', true);
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        $('#btnSalvarNewFuncionario').attr('disabled', false);
                        $('#btnCancelarNewFuncionario').attr('disabled', false);
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {

                        if (data.success) {
                            var priority = 'success';
                            $('#newfuncionario').modal('toggle'); //fechar o modal
                            fLoadOptionScript('Funcionarios');
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });

            //triggered when modal is about to be shown
            $('#editfuncionariomodal').on('show.bs.modal', function (e) {

                //get data-id attribute of the clicked element
                var nome = $(e.relatedTarget).data('nome');
                var id = $(e.relatedTarget).data('id');
                var login = $(e.relatedTarget).data('login');
                var apoio = $(e.relatedTarget).data('apoio');

                //populate the textbox
                $(e.currentTarget).find('input[name="nome"]').val(nome);
                $(e.currentTarget).find('input[name="id"]').val(id);
                $(e.currentTarget).find('input[name="login"]').val(login);
                $(e.currentTarget).find('select[name="apoio"]').val(apoio);
            });


            //triggered when modal is about to be shown
            $('#deletfuncionario').on('show.bs.modal', function (e) {

                //get data-id attribute of the clicked element				
                var id = $(e.relatedTarget).data('id');

                //populate the textbox				
                $(e.currentTarget).find('input[name="id"]').val(id);
            });


            $("#btnSalvarDeleteFuncionario").click(function (e) {

                $.ajax({
                    type: 'POST',
                    url: "deleta_user.php",
                    dataType: 'json',
                    data: $("#frmDeleteFuncionario").serialize(),
                    beforeSend: function () {
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {

                        if (data.success) {
                            var priority = 'success';
                            $('#deletfuncionario').modal('toggle'); //fechar o modal
                            fLoadOptionScript('Funcionarios');
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });


            $('#frmEditFuncionario').on('submit', function (ev) {
                ev.preventDefault();

                $.ajax({
                    type: 'POST',
                    url: "edita_socio.php",
                    dataType: 'json',
                    data: $("#frmEditFuncionario").serialize(),
                    beforeSend: function () {
                        $('#btnSalvarEditFuncionario').attr('disabled', true);
                        $('#btnCancelEditFuncionario').attr('disabled', true);
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        $('#btnSalvarEditFuncionario').attr('disabled', false);
                        $('#btnCancelEditFuncionario').attr('disabled', false);
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {

                        if (data.success) {
                            var priority = 'success';
                            $('#editfuncionariomodal').modal('toggle'); //fechar o modal
                            fLoadOptionScript('Funcionarios');
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });
        </script>
        <?php
        break;

    case 'Pontos':

        $nivel_necessario = 6;

        // Verifica se não há a variável da sessão que identifica o usuário
        if (!isset($_SESSION['UsuarioID']) OR ( $_SESSION['UsuarioNivel'] > $nivel_necessario)) {
            // Destrói a sessão por segurança
            session_destroy();
            // Redireciona o visitante de volta pro login
            header("Location: index.php");
            exit;
        }

        require_once("db.php");
        ?>

        <div class="panel-heading" style="min-height: 60px">
            <strong>Pontos</strong> 
            <?php if (($_SESSION['UsuarioNivel'] == 1) OR ( $_SESSION['UsuarioNivel'] == 3) OR ( $_SESSION['UsuarioNivel'] == 4)) { ?>
                <div class="pull-right">
                    <button class="btn btn-primary"  data-toggle="modal" data-target="#newponto">
                        Novo ponto
                    </button>
                </div>
            <?php }
            ?>
        </div>
        <!-- /.panel-heading -->
        <div class="panel-body">

            <div class="table-responsive">
                <table class="table table-striped table-bordered table-hover" id="dataTables-example">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Nome</th>
                            <?php
                            if ($_SESSION['UsuarioNivel'] <= 2) {
                                echo "<th>Cliente</th>";
                            }
                            ?> 
                            <th>% Ponto</th>
                            <th>Data Registro</th>
                            <?php
                            if ($_SESSION['UsuarioNivel'] != 2) {
                                echo "<th>Ações</th>";
                            }
                            ?> 
                        </tr>
                    </thead>

                    <tbody>
                        <?php
                        if ($_SESSION['UsuarioNivel'] == 1) {
                            $resultUser = mysql_query("SELECT ponto.id id,ponto.nome nome, ponto.passwd passwd,"
                                    . " DATE_FORMAT(ponto.cadastro,'%d/%m/%Y %H:%i') cadastro, "
                                    . " porcent_ponto, a.username cliente, ponto.id_apoio, fechar_faturas_ponto "
                                    . " FROM ponto, user a "
                                    . " WHERE  ponto.id_apoio = a.id "
                                    . " AND ponto.status = 1 "
                                    . " ORDER BY id DESC");
                        } elseif ($_SESSION['UsuarioNivel'] == 2) {
                            $resultUser = mysql_query("SELECT ponto.id id,ponto.nome nome, ponto.passwd passwd,"
                                    . " DATE_FORMAT(ponto.cadastro,'%d/%m/%Y %H:%i') cadastro,"
                                    . " porcent_ponto, a.username cliente, ponto.id_apoio, "
                                    . " fechar_faturas_ponto "
                                    . " FROM ponto, user a "
                                    . " WHERE  ponto.id_apoio = a.id "
                                    . " AND a.id_apoio = " . $_SESSION['UsuarioID']
                                    . " AND ponto.status = 1 "
                                    . " ORDER BY id DESC");
                        } elseif ($_SESSION['UsuarioNivel'] == 3) {
                            $apoios = getApoios($_SESSION['UsuarioID']);
                            $resultUser = mysql_query("SELECT ponto.id,ponto.nome nome, ponto.passwd passwd,"
                                    . "DATE_FORMAT(ponto.cadastro,'%d/%m/%Y %H:%i') cadastro, "
                                    . " porcent_ponto, ponto.id_apoio "
                                    . " FROM ponto "
                                    . " WHERE id_apoio IN ( " . implode(',', $apoios) . ")"
                                    . " AND status = 1 "
                                    . " ORDER BY nome ASC");
                        } elseif ($_SESSION['UsuarioNivel'] == 6) {

                            $resultUser = mysql_query("SELECT ponto.id id,ponto.nome nome, ponto.passwd passwd, DATE_FORMAT(ponto.cadastro,'%d/%m/%Y %H:%i') cadastro, porcent_ponto, a.username cliente, ponto.id_apoio, fechar_faturas_ponto
												FROM ponto, user a 
												WHERE  ponto.id = a.id_apoio 
												AND a.id = " . $_SESSION['UsuarioID'] . " 
												AND ponto.status = 1 
												ORDER BY id DESC");
                        } else {

                            $resultUser = mysql_query("SELECT ponto.id, ponto.nome, ponto.passwd passwd,"
                                    . " DATE_FORMAT(ponto.cadastro,'%d/%m/%Y %H:%i') cadastro, "
                                    . " porcent_ponto, ponto.id_apoio "
                                    . " FROM ponto "
                                    . " WHERE id_apoio = " . $_SESSION['UsuarioID']
                                    . " AND ponto.status = 1 ORDER BY id DESC");
                        }

                        $i = 1;
                        while ($rowUser = mysql_fetch_array($resultUser)) {

                            echo "<tr class='gradeA'><td>" . $rowUser['id'] . "</td><td>" . $rowUser['nome'] . "</td>";
                            if ($_SESSION['UsuarioNivel'] <= 2)
                                echo "<td>" . $rowUser['cliente'] . "</td>";
                            echo "<td>" . $rowUser['porcent_ponto'] . "</td><td>" . $rowUser['cadastro'] . "</td>";



                            if ($_SESSION['UsuarioNivel'] != 2) {

                                echo "<td class='center' style='width: 200px'>";

                                if ($_SESSION['UsuarioNivel'] <= 4) {
                                    ?>					   
                                    <!--                                <a class="btn btn-primary btn-bg" href="javascript: void(0);"													 
                                                                       onclick="fLoadArquivosPenDrive('<?php //echo $rowUser['id']   ?>')" role='button'><i class="fa fa-sort-amount-desc" aria-hidden="true"></i>
                                                                    </a>											-->

                                <a class='btn btn-success' data-toggle="modal" data-target="#editponto" 
                                   data-id="<?php echo $rowUser['id'] ?>" 
                                   data-edit="<?php echo $rowUser['id_apoio'] ?>" 
                                   data-nome="<?php echo $rowUser['nome'] ?>" 
								   data-password="<?php echo $rowUser['passwd'] ?>" 
                                   data-porcent="<?php echo $rowUser['porcent_ponto'] ?>" 
                                   title='Editar Ponto' role='button'><i class='fa fa-edit fa-fw'></i></a>

                                <a class="btn btn-danger btn-bg" data-id="<?php echo $rowUser['id'] ?>" data-toggle="modal" data-target="#deleteponto" role='button'><i class='fa fa-times fa-fw' title="Excluir Ponto"></i></a>
                                <?php if ($_SESSION['UsuarioNivel'] == 3 || $_SESSION['UsuarioNivel'] == 4) { ?>

                                    <a class="btn btn-warning btn-bg" data-id="<?php echo $rowUser['id'] ?>" data-toggle="modal" data-target="#fecharfaturasponto" role='button'><i class='fa fa-dollar fa-fw' title="Calcular Leitura"></i></a>
                                    <?php
                                }
                            }

                            if (($_SESSION['UsuarioNivel'] == 6) AND $rowUser['fechar_faturas_ponto'] == 1) {
                                ?>
                                <a class="btn btn-warning btn-bg" data-id="<?php echo $rowUser['id'] ?>" data-toggle="modal" data-target="#fecharfaturasponto" role='button'><i class='fa fa-dollar fa-fw' title="Calcular Leitura"></i></a>
                                <?php
                            }
                            ?>

                            <?php
                            echo '</td>';
                        }

                        echo '</tr>';
                        $i++;
                    }
                    ?>
                    </tbody>

                </table>
            </div>                      
        </div>
        <!-- /#wrapper -->

        <?php include 'newponto.php'; ?>
        <?php include 'editponto.php'; ?>

        <!-- Modal -->
        <div class="modal fade" id="fecharfaturasponto" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">							
                    <div class="modal-header bg-warning">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h4 class="modal-title" id="myModalLabel">Calcular Leituras do Ponto</h4>
                    </div>								
                    <div class="modal-body">    
                        <form id="frmFecharFaturasPonto" method="POST">
                            <input type="hidden" name="id" id="id">
                        </form>

                        <h5>Você realmente deseja calcular leituras do Ponto?</h5>

                    </div>
                    <div class="modal-footer">
                        <button type="button" id="btnCancelFecharFaturasPonto" class="btn btn-default" data-dismiss="modal">Não</button>
                        <button type="button" id="btnSalvarFecharFaturasPonto" class="btn btn-primary">Sim</button>                
                    </div>							
                </div>
                <!-- /.modal-content -->
            </div>
            <!-- /.modal-dialog -->
        </div>

        <!-- Modal -->
        <div class="modal fade" id="deleteponto" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">							
                    <div class="modal-header bg-danger">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h4 class="modal-title" id="myModalLabel">Deletar Ponto</h4>
                    </div>								
                    <div class="modal-body">    
                        <form id="frmDeletePonto" method="POST">
                            <input type="hidden" name="id" id="id">
                        </form>

                        <h5>Você realmente deseja deletar este Ponto?</h5>

                    </div>
                    <div class="modal-footer">
                        <button type="button" id="btnCancelDeletePonto" class="btn btn-default" data-dismiss="modal">Não</button>
                        <button type="button" id="btnSalvarDeletePonto" class="btn btn-danger">Sim</button>                
                    </div>							
                </div>
                <!-- /.modal-content -->
            </div>
            <!-- /.modal-dialog -->
        </div>
        <!-- /.modal -->
        <script>
            // tooltip demo
            $(document).ready(function () {
                $('#dataTables-example').dataTable();
            });

            $('.tooltip-demo').tooltip({
                selector: "[data-toggle=tooltip]",
                container: "body"
            })

            // popover demo
            $("[data-toggle=popover]").popover();


            $('#frmNewPonto').on('submit', function (ev) {
                ev.preventDefault();

                $.ajax({
                    type: 'POST',
                    url: "add_ponto.php",
                    dataType: 'json',
                    data: $("#frmNewPonto").serialize(),
                    beforeSend: function () {
                        $('#btnSalvarNewPonto').attr('disabled', true);
                        $('#btnCancelarNewPonto').attr('disabled', true);
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        $('#btnSalvarNewPonto').attr('disabled', false);
                        $('#btnCancelarNewPonto').attr('disabled', false);
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {

                        if (data.success) {
                            var priority = 'success';
                            $('#newponto').modal('toggle'); //fechar o modal
                            fLoadOptionScript('Pontos');
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });

            //triggered when modal is about to be shown
            $('#deleteponto').on('show.bs.modal', function (e) {

                //get data-id attribute of the clicked element				
                var id = $(e.relatedTarget).data('id');

                //populate the textbox				
                $(e.currentTarget).find('input[name="id"]').val(id);
            });

            //triggered when modal is about to be shown
            $('#fecharfaturasponto').on('show.bs.modal', function (e) {

                //get data-id attribute of the clicked element				
                var id = $(e.relatedTarget).data('id');

                //populate the textbox				
                $(e.currentTarget).find('input[name="id"]').val(id);
            });


            $("#btnSalvarFecharFaturasPonto").click(function (e) {

                $.ajax({
                    type: 'POST',
                    url: "fechar_faturas_ponto.php",
                    dataType: 'json',
                    data: $("#frmFecharFaturasPonto").serialize(),
                    beforeSend: function () {
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {
                        if (data.success) {
                            var priority = 'success';
                            $('#fecharfaturasponto').modal('toggle'); //fechar o modal
                            if (data.id_ponto) {
                                fLoadOptionScriptPonto('ContasReceber', data.id_ponto);
                            } else if (data.username) {
                                fLoadOptionScriptPonto('ConsultarFaturas', data.username);
                                fLoadPerquisarFaturasScript(data.username, 2);
                            } else {
                                fLoadOptionScript('Pontos');
                            }
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });


            $("#btnSalvarDeletePonto").click(function (e) {

                $.ajax({
                    type: 'POST',
                    url: "deleta_ponto.php",
                    dataType: 'json',
                    data: $("#frmDeletePonto").serialize(),
                    beforeSend: function () {
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {

                        if (data.success) {
                            var priority = 'success';
                            $('#deleteponto').modal('toggle'); //fechar o modal
                            fLoadOptionScript('Pontos');
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });

            //triggered when modal is about to be shown
            $('#editponto').on('show.bs.modal', function (e) {

                //get data-id attribute of the clicked element
                var nome = $(e.relatedTarget).data('nome');
                var id = $(e.relatedTarget).data('id');
				var password = $(e.relatedTarget).data('password');
                var porcent = $(e.relatedTarget).data('porcent');
                var edit = $(e.relatedTarget).data('edit');

                //populate the textbox
                $(e.currentTarget).find('input[name="nome"]').val(nome);
                $(e.currentTarget).find('input[name="id"]').val(id);
				$(e.currentTarget).find('input[name="passwd"]').val(password);
                $(e.currentTarget).find('input[name="porcent_ponto"]').val(porcent);
                $(e.currentTarget).find('select[name="apoio"]').val(edit);
            });


            $('#frmEditPonto').on('submit', function (ev) {
                ev.preventDefault();

                $.ajax({
                    type: 'POST',
                    url: "edita_ponto.php",
                    dataType: 'json',
                    data: $("#frmEditPonto").serialize(),
                    beforeSend: function () {
                        $('#btnSalvarEditPonto').attr('disabled', true);
                        $('#btnCancelarEditPonto').attr('disabled', true);
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        $('#btnSalvarEditPonto').attr('disabled', false);
                        $('#btnCancelarEditPonto').attr('disabled', false);
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {

                        if (data.success) {
                            var priority = 'success';
                            $('#editponto').modal('toggle'); //fechar o modal
                            fLoadOptionScript('Pontos');
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });
        </script>

        <?php
        break;

    case 'Tablets':

        $nivel_necessario = 6;
        $id_user = $_SESSION['UsuarioID'];

        // Verifica se não há a variável da sessão que identifica o usuário
        if (!isset($_SESSION['UsuarioID']) OR ( $_SESSION['UsuarioNivel'] > $nivel_necessario)) {
            // Destrói a sessão por segurança
            session_destroy();
            // Redireciona o visitante de volta pro login
            header("Location: index.php");
            exit;
        }

        require_once("db.php");
        ?>

        <link rel="stylesheet" href="css/style.css"> <!-- Resource style -->

        <style>
            /*
            styles to calculator
            */
            .calculator {
                padding: 10px;
                margin-top: 20px;
                background-color: #ccc;
                border-radius: 5px;

            }
            .result {
                width: 100%;	
                height: 50px;	
                border: none;
                background-color: #eee;	
                text-align: right;
                font-size: 30px;
                padding-right: 10px;			
            }
            .calculator .row { 
                margin-top: 10px;
            }
            .calculator .digit {			

                background-color: black;
                color: white;					
                border-radius: 5px;			
                text-align: center;
            }
            .calculator .digit:hover{
                cursor: pointer;
            }
            .digit.last{
                margin-right: 0px;
            } 
            .digit.clear {
                background-color: #646060;
            }


        </style>

        <div class="panel-heading" style="min-height:60px">
            <strong>Tablets</strong> 
            <div class="pull-right">                            
                <?php
                if ($_SESSION['UsuarioNivel'] != 6 AND $_SESSION['UsuarioNivel'] != 5) {

                    $resultConfig = mysql_query("SELECT ligado FROM configuracao ORDER BY id ASC LIMIT 1");
                    $rowConfig = mysql_fetch_array($resultConfig);
                    $ligado = $rowConfig['ligado'];
                    if ($ligado == 1) {
                        ?>									
                        <a href="javascript:void(0)" onclick="fTrocaStatusServer('', '0')" class='btn btn-success btnOnlineServer' role='button'>SERVIDOR ONLINE &nbsp;</a>
                    <?php } else {
                        ?>

                        <a href="javascript:void(0)" onclick="fTrocaStatusServer('', '1')" class='btn btn-danger btnOnlineServer' role='button'>SERVIDOR OFFLINE &nbsp;</a>
                        <?php
                    }
                }
                ?>      
            </div>
        </div>
        <!-- /.panel-heading -->
        <div class="panel-body">
            <main class="cd-main-content">				

                <?php
                if ($_SESSION['UsuarioNivel'] == 1) {
                    $resultUser = mysql_query("SELECT tablet.id,tablet.idprod,cliente,ponto.nome ponto,"
                            . "tablet.cadastro cadastro, validade, ligado,expiracao,"
                            . " dificuldade, tablet.ativo, tablet.id_ponto,tablet.status "
                            . " FROM tablet,ponto "
                            . " WHERE tablet.id_ponto = ponto.id "
                            . " ORDER BY tablet.id DESC");
                }
                if ($_SESSION['UsuarioNivel'] == 2) {
                    $resultUser = mysql_query("SELECT tablet.id,tablet.idprod,tablet.cliente,ponto.nome ponto,tablet.cadastro cadastro,"
                            . " tablet.validade, tablet.ligado,tablet.expiracao, tablet.dificuldade,"
                            . " tablet.ativo, tablet.id_ponto,tablet.status "
                            . " FROM tablet,ponto,user a "
                            . " WHERE tablet.id_ponto = ponto.id "
                            . " AND tablet.cliente = a.username "
                            . " AND a.id_apoio = " . $_SESSION['UsuarioID'] . " "
                            //. " AND tablet.ativo = 1 "
                            . " ORDER BY tablet.id DESC");
                }

                if ($_SESSION['UsuarioNivel'] == 3) {
                    $apoios = getApoios($id_user);
                    $resultUser = mysql_query("SELECT tablet.id,tablet.idprod,cliente,"
                            . " ponto.nome ponto,tablet.cadastro cadastro, validade, "
                            . " ligado,tablet.status,expiracao, dificuldade, tablet.ativo, tablet.id_ponto"
                            . " FROM tablet,ponto "
                            . " WHERE tablet.id_ponto = ponto.id  "
                            . " AND tablet.id_apoio IN (" . implode(',', $apoios) . ')'
                            //. " AND tablet.ativo = 1 "
                            . " ORDER BY tablet.id DESC");
                }

                if ($_SESSION['UsuarioNivel'] == 4) {

                    $resultUser = mysql_query("SELECT tablet.id,tablet.idprod,cliente,"
                            . " ponto.nome ponto,tablet.cadastro cadastro, validade,"
                            . " ligado,tablet.status,expiracao, dificuldade, tablet.ativo, tablet.id_ponto , tablet.status "
                            . " FROM tablet,ponto "
                            . " WHERE tablet.id_ponto = ponto.id  "
                            . " AND tablet.id_apoio = " . $id_user . " "
                            //. " AND tablet.ativo = 1 "
                            . " ORDER BY tablet.id DESC");
                }

                if (($_SESSION['UsuarioNivel'] == 5) OR ( $_SESSION['UsuarioNivel'] == 6)) {
                    $resultUser = mysql_query("SELECT tablet.id,tablet.idprod,tablet.cliente,ponto.nome ponto,tablet.cadastro cadastro, "
                            . " tablet.validade, tablet.ligado, tablet.dificuldade, tablet.expiracao, "
                            . " tablet.ativo,tablet.id_ponto,tablet.status FROM tablet,ponto, user a "
                            . " WHERE tablet.id_ponto = ponto.id "
                            . " AND ponto.id = a.id_apoio AND a.id = " . $_SESSION['UsuarioID']
                            // . " AND tablet.ativo = 1 "
                            . " ORDER BY  tablet.id DESC");
                }

                $num_rows = mysql_num_rows($resultUser);

                if ($num_rows > 0) {
                    ?>				


                    <div class="cd-tab-filter-wrapper">
                        <div class="cd-tab-filter" >
                            <ul class="cd-filters">
                                <li class="placeholder"> 
                                    <a data-type="all" href="#0">TODOS</a> <!-- selected option on mobile -->
                                </li>
                                <li class="filter"><a href="javascript:void(0);" data-type=".all">TODOS</a></li>
                                <li class="filter" data-filter=".ligado"><a class="selected"  href="javascript:void(0);" data-type="ligado">ONLINE</a></li>
                                <li class="filter" data-filter=".desligado"><a href="javascript:void(0);" data-type="desligado">OFFLINE</a></li>
                                <?php if ($_SESSION['UsuarioNivel'] == 1) { ?>
                                    <li class="filter" data-filter=".desabilitado"><a href="javascript:void(0);" data-type="desabilitado">DESABILITADOS</a></li>
                                <?php } ?>
                            </ul> <!-- cd-filters -->
                        </div> <!-- cd-tab-filter -->
                    </div> <!-- cd-tab-filter-wrapper -->


                    <section class="cd-gallery" id="portfoliolist">
                        <ul style="padding-left: 0px;">

                            <?php
                            $i = 1;
                            while ($rowUser = mysql_fetch_array($resultUser)) {


                                $filtroGenerico = " $rowUser[idprod] $rowUser[cliente] $rowUser[ponto] ";

                                $clienteFiltro = " $rowUser[cliente] ";

                                $nomePontoFiltro = str_replace(" ", "_", strtolower($rowUser['ponto']));
                                $pontoFiltro = " $nomePontoFiltro ";


//                                if ($_SESSION['UsuarioNivel'] == 3 && $rowUser['ativo']==0 ){
//                                     $img = "red.png";
//                                    // $option = " option2 ";
//                                    $radio = " desabilitado ";
//                                    // $check = " check2 ";
//                                    $titulo = "Equipamento Off-line";
//                                    
//                                }


                                if ($rowUser['ligado'] == 1 && $rowUser['ativo'] == 1) {
                                    /**
                                     * ONLINE
                                     */
                                    $img = "green.png";
                                    // $option = " option1 ";
                                    $radio = " ligado ";
                                    // $check = " check1 ";
                                    $titulo = "Equipamento On-line";
                                } elseif ($rowUser['ativo'] == 0 && $rowUser['status'] == 0 && $rowUser['ligado'] == 0) {
                                    /**
                                     * DESABILITADO
                                     */
                                    $img = "green.png";
                                    // $option = " option1 ";
                                    $radio = " desabilitado ";
                                    // $check = " check1 ";
                                    $titulo = "Equipamento Desabilitado";
                                } else {
                                    /**
                                     * OFFLINE & DESABILITADO
                                     */
                                    $img = "red.png";
                                    // $option = " option2 ";
                                    $radio = " desligado ";
                                    // $check = " check2 ";
                                    $titulo = "Equipamento Off-line";
                                }

                                if ($rowUser['ativo']) {
                                    $check = " check1 ";
                                } else {
                                    $check = " check2 ";
                                }
                                ?>

                                <li data-idprod="<?= $rowUser['idprod'] ?>" class="tablet-info mix <?php
                                echo $filtroGenerico;
                                echo $check;
                                echo $radio;
                                echo $clienteFiltro;
                                echo $pontoFiltro;
                                ?>">

                                    <div style="width:100%; padding: 15px; border: 1px solid #E7E7E7; box-shadow: inset 1px 1px 0 rgba(0,0,0,.1),inset 0 -1px 0 rgba(0,0,0,.07);">
										<div style="height: 38px;">
                                        <strong><?php echo $rowUser['idprod'] . "<font size='1'> / " . $rowUser['cliente'] . " / " . $rowUser['ponto'] . "</font></strong>"; ?>

                                            <?php
                                            if ($rowUser['ativo'] == 0) {
                                                $imgTablet = "2.png";
                                                $disableButton = " disabled onclick='return false;' ";
                                                $dataToggle = "";
                                            } else {
                                                $imgTablet = "1.png";
                                                $disableButton = " ";
                                                $dataToggle = ' data-toggle="modal" ';
                                            }

                                            if ($_SESSION['UsuarioNivel'] != 6 AND $_SESSION['UsuarioNivel'] != 5) {


                                                if ($_SESSION['UsuarioNivel'] == 1 && $rowUser['ligado'] == 0 && $rowUser['ativo'] == 0 && $rowUser['status'] == 0) {
                                                    //ADMIN
                                                    ?>
                                                    <span class="pull-right">
                                                        <a style="height: 38px" href="javascript:void(0)" onclick="fTrocaStatusServer('<?php echo $rowUser['idprod'] ?>', 'habilitar')" class='btn btn-success btnOnlineServer' role='button'>&nbsp;Habilitar&nbsp;</a>
                                                    </span>

                                                    <?php
                                                } elseif ($_SESSION['UsuarioNivel'] == 3 && $rowUser['ligado'] == 0 && $rowUser['ativo'] == 0 && $rowUser['status'] == 0) {
                                                    //CLIENTE
                                                    ?>
                                                    <?php
                                                } elseif ($rowUser['ligado'] == 1) {
                                                    ?>
                                                    <span class="pull-right">
                                                        <a style="height: 38px" href="javascript:void(0)" <?php echo $disableButton ?> onclick="fTrocaStatusServer('<?php echo $rowUser['idprod'] ?>', '0')" class='btn btn-success btnOnlineServer' role='button'>&nbsp;ONLINE&nbsp;</a>
                                                    </span>
                                                <?php } else {
                                                    ?>
                                                    <span class="pull-right">
                                                        <a style="height: 38px" href="javascript:void(0)" <?php echo $disableButton ?> onclick="fTrocaStatusServer('<?php echo $rowUser['idprod'] ?>', '1')" class='btn btn-danger btnOnlineServer' role='button'>OFFLINE</a>
                                                    </span>			

                                                    <?php
                                                }
                                            }
                                            ?>
										</div>
                                            <?php if ($_SESSION['UsuarioNivel'] != 5)
											{ ?>
												<div style="position:relative; text-align: center;">
													<a href="detalhes_tablet.php?id=<?php echo $rowUser['idprod'] ?>" data-toggle="modal" data-target="#myModalDetalhesTablet<?php echo $rowUser['idprod'] ?>"><?php
											} ?>
												
														<img src="img/<?php echo $imgTablet ?>" alt="" title="<?php echo $titulo ?>" style="width:100%; padding: 15px;" >
											
                                            <?php if ($_SESSION['UsuarioNivel'] != 5)
											{ ?>
												
														<div style="color: black; line-height: 0.8em; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-weight: bold;">
															<div style="margin-top: 2.5em;">
																<p>STATUS</p>
																<p class="tablet-status" style="color: red;">OFFLINE</p>
															</div>
															
															<div style="margin-top: 3em;" hidden>
																<p>CRÉDITOS</p>
																<p class="tablet-creditos">R$ 0,00</p>
															</div>
														</div>
													</a>
												</div>
                                            <?php
                                            }
                                            ?>

                                            <a <?php echo $disableButton ?> class='btn btn-primary' <?php echo $dataToggle ?> data-target="#insertcreditomodal" data-insert="<?php echo $rowUser['idprod'] ?>"
                                                                            title='Inserir Créditos' role='button'><i class='fa fa-upload fa-fw'></i></a>

                                            <a <?php echo $disableButton ?> class='btn btn-primary' id="btnremoverCreditosTablet" onclick="fRemoverCreditos('<?php echo $rowUser['idprod'] ?>', 2);" title='Remover Créditos' role='button'><i class='fa fa-download fa-fw'></i></a>

                                            <span class="pull-right">
                                                <?php if (($_SESSION['UsuarioNivel'] != 6) && ($_SESSION['UsuarioNivel'] != 5 )) { ?>		

                                                    <a <?php echo $disableButton ?> href="editar_tablet.php?edit=<?php echo $rowUser['idprod'] ?>" <?php echo $dataToggle ?> data-target="#myModalEditarTablet<?php echo $rowUser['idprod'] ?>" class='btn btn-info' role='button' ><i class='fa fa-edit fa-fw'></i></a>

                                                    <?php
                                                }
                                                if ($_SESSION['UsuarioNivel'] == 1 || $_SESSION['UsuarioNivel'] == 3) {
                                                    ?>	
                                                    <a <?php echo $disableButton ?> href="javascript:void(0);" data-id="<?php echo $rowUser['idprod'] ?>" <?php echo $dataToggle ?> data-target="#deletetabletmodal" class='btn btn-danger' role='button'><i class='fa fa-times fa-fw'></i></a>
                                                    <?php
                                                }
                                                ?>

                                            </span>
                                    </div>								
                                </li>							
                                <?php
                            }
                            ?>						
                            <li class="gap"></li>
                            <li class="gap"></li>
                            <li class="gap"></li>

                        </ul>
                        <div class="cd-fail-message">Nenhum resultado encontrado.</div>
                    </section> <!-- cd-gallery -->

                    <?php
                    mysql_data_seek($resultUser, 0);
                    while ($rowUser = mysql_fetch_array($resultUser)) {
                        ?>

                        <!-- Modal HTML -->
                        <div id="myModalDetalhesTablet<?php echo $rowUser['idprod'] ?>" class="modal fade">
                            <div class="modal-dialog modal-lg">
                                <div class="modal-content modal-lg">
                                    <!-- Content will be loaded here from "remote.php" file -->
                                </div>
                            </div>
                        </div>

                        <!-- Modal HTML -->
                        <div id="myModalEditarTablet<?php echo $rowUser['idprod'] ?>" class="modal fade">
                            <div class="modal-dialog">
                                <form role="form" id="frmEditarTablet<?php echo $rowUser['idprod'] ?>" class="frmEditarTablet" onsubmit="return fSalvarEdicaoTablet('<?php echo $rowUser['idprod'] ?>')" method="POST">
                                    <div class="modal-content modal-lg">
                                        <!-- Content will be loaded here from "remote.php" file -->
                                    </div>
                                </form>
                            </div>
                        </div>

                        <?php
                    }
                    ?>

                    <!-- Modal -->
                    <div class="modal fade" id="deletetabletmodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                        <div class="modal-dialog">
                            <div class="modal-content">							
                                <div class="modal-header bg-danger">
                                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                                    <?php if ($_SESSION['UsuarioNivel'] == 1) { ?>
                                        <h4 class="modal-title" id="myModalLabel">Deletar Tablet</h4>
                                    <?php } else { ?>
                                        <h4 class="modal-title" id="myModalLabel">Desabiltar Tablet</h4>
                                    <?php } ?>
                                </div>								
                                <div class="modal-body">    
                                    <form id="frmDeleteTablet" method="POST">
                                        <input type="hidden" name="id" id="id">
                                    </form>
                                    <?php if ($_SESSION['UsuarioNivel'] == 1) { ?>
                                        <h5>Você realmente deseja deletar este Tablet?</h5>
                                    <?php } else { ?>
                                        <h5>Você realmente deseja desabilitar este Tablet?</h5>
                                    <?php } ?>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" id="btnCancelDeleteTablet" class="btn btn-default" data-dismiss="modal">Não</button>
                                    <button type="button" id="btnSalvarDeleteTablet" class="btn btn-danger">Sim</button>                
                                </div>							
                            </div>
                            <!-- /.modal-content -->
                        </div>
                        <!-- /.modal-dialog -->
                    </div>
                    <!-- /.modal -->

                    <div class="cd-filter">
                        <form>
                            <div class="cd-filter-block">
                                <h4>Pesquisa</h4>

                                <div class="cd-filter-content">
                                    <input type="search" placeholder="Pesquise por Tablet, Ponto ou Cliente">
                                </div> <!-- cd-filter-content -->
                            </div> <!-- cd-filter-block -->
                            <?php if ($_SESSION['UsuarioNivel'] == 1) { ?>

                                <div class="cd-filter-block">
                                    <h4>Ativos/Inativos</h4>
                                    <ul class="cd-filter-content cd-filters list">
                                        <li>
                                            <input class="filter" data-filter=".check1" type="checkbox" id="checkbox1">
                                            <label class="checkbox-label" for="checkbox1">ATIVOS</label>
                                        </li>
                                        <li>
                                            <input class="filter" data-filter=".check2" type="checkbox" id="checkbox2">
                                            <label class="checkbox-label" for="checkbox2">INATIVOS</label>
                                        </li>								
                                    </ul> <!-- cd-filter-content -->
                                </div> <!-- cd-filter-block -->								
                                <?php
                            }
                            ?>

                            <div class="cd-filter-block">
                                <h4>Cliente</h4>
                                <ul class="cd-filter-content cd-filters list">
                                    <?php
                                    if ($_SESSION['UsuarioNivel'] == 1) {

                                        $resultUser2 = mysql_query("SELECT cliente
																FROM tablet,ponto 
																WHERE tablet.id_ponto = ponto.id 
																GROUP BY cliente
																ORDER BY cliente");
                                    }

                                    if ($_SESSION['UsuarioNivel'] == 2) {

                                        $resultUser2 = mysql_query("SELECT tablet.cliente
															FROM tablet,ponto,user a
															WHERE tablet.id_ponto = ponto.id 
															AND tablet.cliente = a.username 
															AND a.id_apoio = " . $_SESSION['UsuarioID'] . " 
															AND tablet.ativo = 1 
															GROUP BY tablet.cliente
															ORDER BY tablet.cliente");
                                    }

                                    if ($_SESSION['UsuarioNivel'] == 3) {
                                        $apoios = getApoios($id_user);
                                        $resultUser2 = mysql_query("SELECT cliente
															FROM tablet,ponto 
															WHERE tablet.id_ponto = ponto.id  
															AND tablet.id_apoio IN ( " . implode(',', $apoios) . ")
															AND tablet.ativo = 1 
															GROUP BY cliente
															ORDER BY cliente");
                                    }

                                    if ($_SESSION['UsuarioNivel'] == 4) {

                                        $resultUser2 = mysql_query("SELECT cliente
															FROM tablet,ponto 
															WHERE tablet.id_ponto = ponto.id 
															AND tablet.id_apoio = '$id_user'  
															AND tablet.ativo = 1 
															GROUP BY cliente
															ORDER BY cliente");
                                    }

                                    if (($_SESSION['UsuarioNivel'] == 5) OR ( $_SESSION['UsuarioNivel'] == 6)) {

                                        $resultUser2 = mysql_query("SELECT tablet.cliente
															FROM tablet,ponto, user a
															WHERE tablet.id_ponto = ponto.id 
															AND ponto.id = a.id_apoio 
															AND a.id = " . $_SESSION['UsuarioID'] . " 
															AND tablet.ativo = 1 
															GROUP BY cliente
															ORDER BY cliente");
                                    }
                                    while ($rowUser = mysql_fetch_array($resultUser2)) {
                                        ?>
                                        <li>
                                            <input class="filter" data-filter=".<?php echo $rowUser['cliente']; ?>" type="checkbox" id="checkbox<?php echo $rowUser['cliente']; ?>">
                                            <label class="checkbox-label" for="checkbox<?php echo $rowUser['cliente']; ?>"><?php echo $rowUser['cliente']; ?></label>
                                        </li>										
                                        <?php
                                    }
                                    ?>	
                                </ul> <!-- cd-filter-content -->
                            </div> <!-- cd-filter-block -->


                            <div class="cd-filter-block">
                                <h4>Ponto</h4>
                                <ul class="cd-filter-content cd-filters list">
                                    <?php
                                    if ($_SESSION['UsuarioNivel'] == 1) {

                                        $resultUser2 = mysql_query("SELECT tablet.id_ponto, ponto.nome
																FROM tablet,ponto 
																WHERE tablet.id_ponto = ponto.id 
																GROUP BY ponto.nome
																ORDER BY ponto.nome");
                                    }

                                    if ($_SESSION['UsuarioNivel'] == 2) {

                                        $resultUser2 = mysql_query("SELECT tablet.id_ponto, ponto.nome
															FROM tablet,ponto,user a
															WHERE tablet.id_ponto = ponto.id 
															AND tablet.cliente = a.username 
															AND a.id_apoio = " . $_SESSION['UsuarioID'] . " 
															AND tablet.ativo = 1 
															GROUP BY ponto.nome
															ORDER BY ponto.nome");
                                    }

                                    if ($_SESSION['UsuarioNivel'] == 3) {
                                        $apoios = getApoios($id_user);
                                        $resultUser2 = mysql_query("SELECT tablet.id_ponto, ponto.nome
															FROM tablet,ponto 
															WHERE tablet.id_ponto = ponto.id  
															AND tablet.id_apoio IN ( " . implode(',', $apoios) . " )
															AND tablet.ativo = 1 
															GROUP BY ponto.nome
															ORDER BY ponto.nome");
                                    }

                                    if ($_SESSION['UsuarioNivel'] == 4) {

                                        $resultUser2 = mysql_query("SELECT tablet.id_ponto, ponto.nome
															FROM tablet,ponto 
															WHERE tablet.id_ponto = ponto.id 
															AND tablet.id_apoio = '$id_user'  
															AND tablet.ativo = 1 
															GROUP BY ponto.nome
															ORDER BY ponto.nome");
                                    }

                                    if (($_SESSION['UsuarioNivel'] == 5) OR ( $_SESSION['UsuarioNivel'] == 6)) {

                                        $resultUser2 = mysql_query("SELECT tablet.id_ponto, ponto.nome
															FROM tablet,ponto, user a
															WHERE tablet.id_ponto = ponto.id 
															AND ponto.id = a.id_apoio 
															AND a.id = " . $_SESSION['UsuarioID'] . " 
															AND tablet.ativo = 1 
															GROUP BY ponto.nome
															ORDER BY ponto.nome");
                                    }
                                    while ($rowUser = mysql_fetch_array($resultUser2)) {

                                        $nomePontoFiltro = str_replace(" ", "_", strtolower($rowUser['nome']));
                                        ?>
                                        <li>
                                            <input class="filter" data-filter=".<?php echo $nomePontoFiltro; ?>" type="checkbox" id="checkbox<?php echo $nomePontoFiltro; ?>">
                                            <label class="checkbox-label" for="checkbox<?php echo $nomePontoFiltro; ?>"><?php echo $rowUser['nome']; ?></label>
                                        </li>										
                                        <?php
                                    }
                                    ?>	
                                </ul> <!-- cd-filter-content -->
                            </div> <!-- cd-filter-block -->

                            <div class="cd-filter-block">
                                <h4>Tablet</h4>								
                                <div class="cd-filter-content">
                                    <div class="cd-select cd-filters">
                                        <select class="filter" name="selectThis" id="selectThis" class="form-control" >
                                            <option value="">Selecione um Tablet</option>
                                            <?php
                                            mysql_data_seek($resultUser, 0);
                                            while ($rowUser = mysql_fetch_array($resultUser)) {
                                                ?>

                                                <option value=".<?php echo $rowUser['idprod'] ?>"><?php echo $rowUser['idprod'] ?></option>
                                                <?php
                                            }
                                            ?>
                                        </select>
                                    </div> <!-- cd-select -->
                                </div> <!-- cd-filter-content -->
                            </div> <!-- cd-filter-block -->


                            <?php
                            /*
                              <div class="cd-filter-block">
                              <h4>Status</h4>

                              <ul class="cd-filter-content cd-filters list">

                              <li>
                              <input class="filter" data-filter="" type="radio" name="radioButton" id="radio3" checked>
                              <label class="radio-label" for="radio3">TODOS</label>
                              </li>

                              <li>
                              <input class="filter" data-filter=".radio2" type="radio" name="radioButton" id="radio2">
                              <label class="radio-label" for="radio2">OFFLINE</label>
                              </li>

                              <li>
                              <input class="filter" data-filter=".radio1" type="radio" name="radioButton" id="radio1">
                              <label class="radio-label" for="radio1">ONLINE</label>
                              </li>
                              </ul> <!-- cd-filter-content -->
                              </div> <!-- cd-filter-block -->
                             */
                            ?>

                        </form>

                        <a href="javascript:void(0);" class="cd-close">Fechar</a>
                    </div> <!-- cd-filter -->

                    <a href="javascript:void(0);" class="cd-filter-trigger">Filtros</a>
                    <?php
                } else {
                    echo "<div class='alert alert-warning'>Nenhum Registro encontrado.</div>";
                }
                ?>
            </main> <!-- cd-main-content -->
        </div>		

        <?php include 'newmaquina.php'; ?>
        <?php include 'inserir_credito.php'; ?>

        <script>

			var tabletInfos = $('.tablet-info');
		
			updateTabletInfos ();
			tabletInfoUpdate = setInterval (updateTabletInfos, 5000);
			
			function updateTabletInfos ()
			{
				//console.log ('Atualizando...');
				
				$.ajax ({ url: 'get_tablet_info.php', success: function (result)
				{
					//console.log (result);
					
					var tablets = jQuery.parseJSON (result);
					
					tablets.forEach ((tablet) =>
					{
						var idprod = tablet['idprod'];
						var status = tablet['status'];
						var creditos = tablet['creditos'];
						var online = status == 'ONLINE';
						
						var statusElement = $('.tablet-info[data-idprod="' + idprod + '"] .tablet-status');
								
						statusElement.text (status);
						statusElement.css ('color', online ? 'green' : 'red');
						
						var creditosElement = $('.tablet-info[data-idprod="' + idprod + '"] .tablet-creditos');
						
						if (online && creditos != null)
						{
							creditosElement.text (creditos);
							creditosElement.parent().show ();
						}
						else
							creditosElement.parent().hide ();
					});
				}});
			}
		
            jQuery(function ($) {
                /*****************************************************
                 MixItUp - Define a single object literal 
                 to contain all filter custom functionality
                 *****************************************************/
                var buttonFilter = {
                    // Declare any variables we will need as properties of the object
                    $filters: null,
                    groups: [],
                    outputArray: [],
                    outputString: '',
                    //                    load: {
                    //                        filter: '.ligado',
                    //                    },
                    // The "init" method will run on document ready and cache any jQuery objects we will need.
                    init: function () {
                        var self = this; // As a best practice, in each method we will asign "this" to the variable "self" so that it remains scope-agnostic. We will use it to refer to the parent "buttonFilter" object so that we can share methods and properties between all parts of the object.

                        self.$filters = $('.cd-main-content');
                        self.$container = $('.cd-gallery ul');
                        self.$filters.find('.cd-filters').each(function () {
                            var $this = $(this);

                            self.groups.push({
                                $inputs: $this.find('.filter'),
                                active: '',
                                tracker: false,
                            });
                        });
                        self.bindHandlers();
                    },
                    // The "bindHandlers" method will listen for whenever a button is clicked. 
                    bindHandlers: function () {
                        var self = this;

                        self.$filters.on('click', 'a', function (e) {
                            self.parseFilters();
                        });
                        self.$filters.on('change', function () {
                            self.parseFilters();
                        });
                    },
                    parseFilters: function () {
                        var self = this;

                        // loop through each filter group and grap the active filter from each one.
                        for (var i = 0, group; group = self.groups[i]; i++) {
                            group.active = [];
                            group.$inputs.each(function () {
                                var $this = $(this);
                                if ($this.is('input[type="radio"]') || $this.is('input[type="checkbox"]')) {
                                    if ($this.is(':checked')) {
                                        group.active.push($this.attr('data-filter'));
                                    }
                                } else if ($this.is('select')) {
                                    group.active.push($this.val());
                                } else if ($this.find('.selected').length > 0) {
                                    group.active.push($this.attr('data-filter'));
                                }
                            });
                        }
                        self.concatenate();
                    },
                    concatenate: function () {
                        var self = this;

                        self.outputString = ''; // Reset output string

                        for (var i = 0, group; group = self.groups[i]; i++) {
                            self.outputString += group.active;
                        }

                        // If the output string is empty, show all rather than none:    
                        !self.outputString.length && (self.outputString = 'all');

                        // Send the output string to MixItUp via the 'filter' method:    
                        if (self.$container.mixItUp('isLoaded')) {
                            self.$container.mixItUp('filter', self.outputString);
                        }
                    }
                };


                //open/close lateral filter
                $('.cd-filter-trigger').on('click', function () {
                    triggerFilter(true);
                });
                $('.cd-filter .cd-close').on('click', function () {
                    triggerFilter(false);
                });

                function triggerFilter($bool) {
                    var elementsToTrigger = $([$('.cd-filter-trigger'), $('.cd-filter'), $('.cd-tab-filter'), $('.cd-gallery')]);
                    elementsToTrigger.each(function () {
                        $(this).toggleClass('filter-is-visible', $bool);
                    });
                }

                //mobile version - detect click event on filters tab
                var filter_tab_placeholder = $('.cd-tab-filter .placeholder a'),
                        filter_tab_placeholder_default_value = 'Selecione',
                        filter_tab_placeholder_text = filter_tab_placeholder.text();

                $('.cd-tab-filter li').on('click', function (event) {
                    //detect which tab filter item was selected
                    var selected_filter = $(event.target).data('type');
					
                    //check if user has clicked the placeholder item
                    if ($(event.target).is(filter_tab_placeholder)) {
                        (filter_tab_placeholder_default_value == filter_tab_placeholder.text()) ? filter_tab_placeholder.text(filter_tab_placeholder_text) : filter_tab_placeholder.text(filter_tab_placeholder_default_value);
                        $('.cd-tab-filter').toggleClass('is-open');

                        //check if user has clicked a filter already selected 
                    } else if (filter_tab_placeholder.data('type') == selected_filter) {
                        filter_tab_placeholder.text($(event.target).text());
                        $('.cd-tab-filter').removeClass('is-open');

                    } else {
                        //close the dropdown and change placeholder text/data-type value
                        $('.cd-tab-filter').removeClass('is-open');
                        filter_tab_placeholder.text($(event.target).text()).data('type', selected_filter);
                        filter_tab_placeholder_text = $(event.target).text();

                        //add class selected to the selected filter item
                        $('.cd-tab-filter .selected').removeClass('selected');
                        $(event.target).addClass('selected');
                    }
                });

                //close filter dropdown inside lateral .cd-filter 
                $('.cd-filter-block h4').on('click', function () {
                    $(this).toggleClass('closed').siblings('.cd-filter-content').slideToggle(300);
                })

                //fix lateral filter and gallery on scrolling
                // $(window).on('scroll', function(){
                // (!window.requestAnimationFrame) ? fixGallery() : window.requestAnimationFrame(fixGallery);
                // });

                function fixGallery() {
                    var offsetTop = $('.cd-main-content').offset().top,
                            scrollTop = $(window).scrollTop();
                    (scrollTop >= offsetTop) ? $('.cd-main-content').addClass('is-fixed') : $('.cd-main-content').removeClass('is-fixed');
                }

                /************************************
                 MitItUp filter settings
                 More details: 
                 https://mixitup.kunkalabs.com/
                 or:
                 http://codepen.io/patrickkunka/
                 *************************************/
                buttonFilter.init();
                $('.cd-gallery ul').mixItUp({
                    controls: {
                        enable: false
                    },
                    callbacks: {
                        onMixStart: function () {
                            $('.cd-fail-message').fadeOut(200);
                        },
                        onMixFail: function () {
                            $('.cd-fail-message').fadeIn(200);
                        }
                    },
                    load: {//filtro iniciado
                        filter: '.ligado'
                    }
                });

                //search filtering
                //credits http://codepen.io/edprats/pen/pzAdg
                var inputText;
                var $matching = $();

                var delay = (function () {
                    var timer = 0;
                    return function (callback, ms) {
                        clearTimeout(timer);
                        timer = setTimeout(callback, ms);
                    };
                })();

                $(".cd-filter-content input[type='search']").keyup(function () {
                    // Delay function invoked to make sure user stopped typing
                    delay(function () {
                        inputText = $(".cd-filter-content input[type='search']").val().toLowerCase();
                        // Check to see if input field is empty
                        if ((inputText.length) > 0) {
                            $('.mix').each(function () {
                                var $this = $(this);

                                // add item to be filtered out if input text matches items inside the title   
                                if ($this.attr('class').toLowerCase().match(inputText)) {
                                    $matching = $matching.add(this);
                                } else {
                                    // removes any previously matched item
                                    $matching = $matching.not(this);
                                }
                            });

                            $('.cd-gallery ul').mixItUp('filter', $matching);
                        } else {
                            // resets the filter to show all item if input is empty
                            $('.cd-gallery ul').mixItUp('filter', 'all');
                        }
                    }, 200);
                });
            });



            /*
             * jQuery Growl Calc
             * Version 2.0.0
             * Last Updated 2014-02-08
             * @requires jQuery v1.11.0 or later (untested on previous version)
             *
             * Examples at: http://projects.zoulcreations.com/jquery/jquery-calc/
             * Copyright (c) 2008-2014 David Higgins
             * */
            jQuery(function ($) {

                var digits = $('#calculator .digits .digit');
                var clear = $('#calculator .clear');
                var calculator = {
                    left: false,
                    right: false,
                    result: 0,
                    operator: '+'
                };


                function isDigit(key) {
                    var digits = "15102050100";
                    var digit = false;
                    if (digits.indexOf(key) != -1)
                        digit = true;
                    return digit;
                }

                clear.click(function () {
                    $('#calculator .result').val(0);
                });
                digits.click(function () {
                    var key = $(this).text();
                    if (isDigit(key)) {
                        calculator.left = $('#calculator .result').val();
                        calculator.right = key.toString();

                        calculator.result = eval(calculator.left + calculator.operator + calculator.right);
                        $('#calculator .result').val(calculator.result);
                    }
                });
            });

            $('.modal').on('shown.bs.modal', function () {
                $(this).find('[autofocus]').focus();
            });

            //triggered when modal is about to be shown
            $('#insertcreditomodal').on('show.bs.modal', function (e) {
                //get data-id attribute of the clicked element
                var insert = $(e.relatedTarget).data('insert');

                //populate the textbox
                $(e.currentTarget).find('input[name="idprod"]').val(insert);
            });

            $('#frmInserirCredito').on('submit', function (ev) {
                ev.preventDefault();

                $.ajax({
                    type: 'POST',
                    url: "add_creditos.php",
                    dataType: 'json',
                    data: $("#frmInserirCredito").serialize(),
                    async: false,
                    success: function (data) {
                        if (data.success) {
                            $.blockUI({
                                message: '<h4 id="msgAdicionarCredito" >Conectando ao tablet... <span id="countDec"></span></h4>',
                                css: {
                                    border: '3px solid #a00'
                                }
                            });
                            $("#insertcreditomodal").modal('toggle'); //fechar o modal						
                            var idProd = data.idprod;
                            var interval = null;
                            var intervalCount = null;
                            var counter = 60;

                            intervalCount = setInterval(function () {
                                counter--;
                                span = document.getElementById("countDec");
                                if (counter >= 0) {
                                    span.innerHTML = counter;
                                }
                                // Display 'counter' wherever you want to display it.
                                if (counter === 0) {
                                    document.getElementById("msgAdicionarCredito").innerHTML = "Tempo esgotado, cancelando operação...";
                                    clearInterval(intervalCount);
                                }
                            }, 1000);

                            //realizar tentativas para efetivação do credito
                            interval = setInterval(function () {
                                $.ajax({
                                    type: 'POST',
                                    url: "creditoinfo.php",
                                    dataType: 'json',
                                    data: {'idprod': idProd},
                                    timeout: 4000, // sets timeout
                                    async: false,
                                    success: function (data) {

                                        if (data.success === 1) {

                                            var priority = 'success';
                                            setTimeout($.unblockUI, 500);
                                            toastr[priority](data.msg);
                                            fLoadOptionScript('Tablets');
                                            clearInterval(interval); // stop the interval										

                                        } else if (data.success === 0) {

                                            var priority = 'error';
                                            setTimeout($.unblockUI, 500);
                                            toastr[priority](data.msg);
                                            fLoadOptionScript('Tablets');
                                            clearInterval(interval); // stop the interval

                                        }
                                    }
                                });
                            }, 2000); //fazer nova requisição a cada dois segundos

                        } else {
                            var priority = 'error';
                            toastr[priority](data.msg);
                            fLoadOptionScript('Tablets');
                        }

                    }
                });
            });

            //triggered when modal is about to be shown
            $('#deletetabletmodal').on('show.bs.modal', function (e) {
                //get data-id attribute of the clicked element				
                var id = $(e.relatedTarget).data('id');

                //populate the textbox				
                $(e.currentTarget).find('input[name="id"]').val(id);
            });


            $("#btnSalvarDeleteTablet").click(function (e) {

                $.ajax({
                    type: 'POST',
                    url: "deleta_tablet.php",
                    dataType: 'json',
                    data: $("#frmDeleteTablet").serialize(),
                    beforeSend: function () {
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {

                        if (data.success) {
                            var priority = 'success';
                            $('#deletetabletmodal').modal('toggle'); //fechar o modal
                            fLoadOptionScript('Tablets');
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });

        </script>

        <?php
        break;

    case 'ContasReceber':
        //$nivel_necessario = 3;
        $nivel_necessario = 4;
        // Verifica se não há a variável da sessão que identifica o usuário
        if (!isset($_SESSION['UsuarioID']) OR ( $_SESSION['UsuarioNivel'] > $nivel_necessario)) {
            // Destrói a sessão por segurança
            session_destroy();
            // Redireciona o visitante de volta pro login
            echo 'saiu';
            exit;
            header("Location: index.php");

            exit;
        }

        if (isset($_REQUEST['id_ponto'])) {
            $id_ponto = $_REQUEST['id_ponto'];
        }

        require_once("db.php");
        ?>

        <div class="panel-heading">
            <strong>Contas a Receber</strong>
        </div>
        <div class="panel-body">
            <div class="row">				
                <div class="col-md-12">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <div class="row">
                                <form id="frmBuscaCobrancasReceber" onsubmit="return pesquisarCobrancasReceber()">
                                    <div class="col-lg-4">
                                        <div class="form-group input-group">    
                                            <span class="input-group-addon"> <?php
                                                if ($_SESSION['UsuarioNivel'] <= 2) {
                                                    echo 'Cliente';
                                                } else {
                                                    echo 'Ponto';
                                                }
                                                ?> 
                                            </span>                                             
                                            <select name="cliente" id="cliente" class="form-control" onchange="pesquisarCobrancasReceber()" >

                                                <?php
                                                if ($_SESSION['UsuarioNivel'] == 1) {
                                                    $resultUser = mysql_query("SELECT c.id, username, nome FROM user c WHERE nivel = 3 ORDER BY username ASC");
                                                } elseif ($_SESSION['UsuarioNivel'] == 2) {
                                                    $resultUser = mysql_query("SELECT a.id, username, nome FROM user a WHERE nivel = 3 AND a.id_apoio = " . $_SESSION['UsuarioID'] . " ORDER BY username ASC");
                                                } elseif ($_SESSION['UsuarioNivel'] == 3) {
                                                    $apoios = getApoios($_SESSION[UsuarioID]);
//                                                    $resultUser = mysql_query("SELECT a.id, a.nome username, a.nome FROM ponto a "
//                                                            . " WHERE a.id_apoio = '$_SESSION[UsuarioID]' "
//                                                            . " ORDER BY a.nome ASC");
                                                    $resultUser = mysql_query("SELECT a.id, a.nome username, a.nome FROM ponto a "
                                                            . " WHERE a.id_apoio IN (" . implode(',', $apoios) . ')'
                                                            . " ORDER BY a.nome ASC");
                                                } elseif ($_SESSION['UsuarioNivel'] == 4) {
                                                    $resultUser = mysql_query("SELECT a.id, a.nome username, a.nome FROM ponto a "
                                                            . " WHERE a.id_apoio = '$_SESSION[UsuarioID]' "
                                                            . " ORDER BY a.nome ASC");
                                                }
                                                $totalRegitros = mysql_num_rows($resultUser);
                                                if ($totalRegitros > 1) {
                                                    echo '<option value ="" >Todos</option>';
                                                }

                                                print_r($resultUser);

                                                while ($rowUser = mysql_fetch_array($resultUser)) {
                                                    if ($totalRegitros == 1) {
                                                        $selected = 'selected';
                                                    } else {
                                                        $selected = '';
                                                    }

                                                    if ($id_ponto AND $rowUser['id'] == $id_ponto) {
                                                        $selected = 'selected';
                                                    }

                                                    echo "<option value=" . $rowUser['id'] . " $selected  >" . $rowUser['nome'] . "</option>";
                                                }
                                                ?>
                                            </select>
                                        </div>
                                    </div><!-- /.col-lg-4 -->
                                    <div class="col-lg-3">                                             
                                        <div class="form-group input-group">    
                                            <span class="input-group-addon"> Pago</span>
                                            <select name="status" id="status" class="form-control" required onchange="pesquisarCobrancasReceber()">					
                                                <option value ="0" >Não</option>
                                                <option value ="1" >Sim</option>
                                            </select>                                                
                                        </div>
                                    </div>
                                    <!-- /.col-lg-4
                                    <div class="col-lg-2">
                                            <button type="submit" id="btnPesquisarCobrancas" class="btn btn-primary" data-loading-text="Carregando..." >Pesquisar</button>
                                    </div>
                                    -->
                                </form>
                            </div> 
                        </div>

                        <div class="panel-body">
                            <span id="divResultPesquisaCobrancasReceber"></span>
                            <span id="divErrosPesquisaCobrancasReceber"></span>
                        </div>
                    </div>
                </div>
                <!-- Fatura -->
                <style>
                    .height {
                        min-height: 200px;
                    }

                    .icon {
                        font-size: 30px;
                        color: #5CB85C;
                    }

                    .iconbig {
                        font-size: 50px;
                        color: #08C;
                    }

                    .table > tbody > tr > .emptyrow {
                        border-top: none;
                    }

                    .table > thead > tr > .emptyrow {
                        border-bottom: none;
                    }

                    .table > tbody > tr > .highrow {
                        border-top: 3px solid;
                    }
                </style>
                <!-- /#wrapper -->
            </div>
        </div>

        <!-- Page-Level Demo Scripts - Blank - Use for reference -->
        <script>
            $(document).ready(function () {
                $('#dataTables-example').dataTable();
                //carregar a pesquisa quando a tela for aberta
                pesquisarCobrancasReceber();
            });
        </script>
        <script type="text/javascript">

            $(function () {
                $(".btn").click(function () {
                    $(this).button('loading').delay(10000).queue(function () {
                        //$(this).button('reset');
                    });
                });
            });

            $('#cliente').change(function () {
                $(".btn").button('reset');
            });

            $('#status').change(function () {
                $(".btn").button('reset');
            });

        </script>			

        <?php
        break;

    case 'ContasPagar':

        //$nivel_necessario = 3;
        $nivel_necessario = 4;
        // Verifica se não há a variável da sessão que identifica o usuário
        if (!isset($_SESSION['UsuarioID']) OR ( $_SESSION['UsuarioNivel'] > $nivel_necessario)) {
            // Destrói a sessão por segurança
            session_destroy();
            // Redireciona o visitante de volta pro login
            header("Location: index.php");
            exit;
        }

        require_once("db.php");
        ?>

        <div class="panel-heading">
            <strong>Contas a Pagar</strong>
        </div>
        <div class="panel-body">
            <div class="row">				
                <div class="col-md-12">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <div class="row">
                                <form id="frmBuscaCobrancasPagar" onsubmit="return pesquisarCobrancasPagar()">
                                    <input type="hidden" name="cliente" id="cliente" value="<?php echo $_SESSION['UsuarioID'] ?>" >
                                    <div class="col-lg-3">                                             
                                        <div class="form-group input-group">    
                                            <span class="input-group-addon"> Pago</span>
                                            <select name="status" id="status" class="form-control" required onchange="pesquisarCobrancasPagar()">					
                                                <option value ="0" >Não</option>
                                                <option value ="1" >Sim</option>
                                            </select>                                                
                                        </div>
                                    </div>
                                </form>
                            </div> 
                        </div>						
                        <div class="panel-body">
                            <span id="divResultPesquisaCobrancasPagar"></span>
                            <span id="divErrosPesquisaCobrancasPagar"></span>
                        </div>
                    </div>
                </div>
                <!-- Fatura -->
                <style>
                    .height {
                        min-height: 200px;
                    }

                    .icon {
                        font-size: 30px;
                        color: #5CB85C;
                    }

                    .iconbig {
                        font-size: 50px;
                        color: #08C;
                    }

                    .table > tbody > tr > .emptyrow {
                        border-top: none;
                    }

                    .table > thead > tr > .emptyrow {
                        border-bottom: none;
                    }

                    .table > tbody > tr > .highrow {
                        border-top: 3px solid;
                    }
                </style>
                <!-- /#wrapper -->
            </div>
        </div>

        <!-- Page-Level Demo Scripts - Blank - Use for reference -->
        <script>
            $(document).ready(function () {
                $('#dataTables-example').dataTable();
                //carregar a pesquisa quando a tela for aberta
                pesquisarCobrancasPagar();
            });
        </script>
        <script type="text/javascript">

            $(function () {
                $(".btn").click(function () {
                    $(this).button('loading').delay(10000).queue(function () {
                        //$(this).button('reset');
                    });
                });
            });

            $('#cliente').change(function () {
                $(".btn").button('reset');
            });

            $('#status').change(function () {
                $(".btn").button('reset');
            });

        </script>			

        <?php
        break;

    case 'AcumuladosPagos':


        $nivel_necessario = 6;

        // Verifica se não há a variável da sessão que identifica o usuário
        if (!isset($_SESSION['UsuarioID']) OR ( $_SESSION['UsuarioNivel'] > $nivel_necessario)) {
            // Destrói a sessão por segurança
            session_destroy();
            // Redireciona o visitante de volta pro login
            header("Location: index.php");
            exit;
        }

        require_once("db.php");
        ?>
        <div class="panel-heading">
            <strong>Acúmulados Pagos por Período</strong>
        </div>
        <div class="panel-body">
            <div class="row">
                <div class="col-md-12">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <div class="row">
                                <form name="frmBusca" id="frmPesquisarAcumuladoPago" method="post" onsubmit="return perquisarAcumuladoPago();" > 

                                    <div class="col-lg-3">
                                        <div class="form-group input-group">    
                                            <span class="input-group-addon"> <?php
                                                if ($_SESSION['UsuarioNivel'] <= 2) {
                                                    echo 'Cliente';
                                                } else {
                                                    echo 'Tablet';
                                                }
                                                ?>  </span>                                             
                                            <select name="filtro" id="filtro" class="form-control">
                                                <option value ="" >Todos</option>
                                                <?php
                                                if ($_SESSION['UsuarioNivel'] <= 2) {

                                                    // $resultAcumulados = mysql_query("SELECT a.id, a.idprod, a.ativo 
                                                    // FROM tablet a 
                                                    // WHERE
                                                    // a.ativo = 1
                                                    // GROUP BY a.idprod
                                                    // ORDER BY a.idprod");

                                                    $resultAcumulados = mysql_query("SELECT a.id, nome as idprodNome
																	FROM user a
																	WHERE 
																	nivel = 3 
																	AND a.status = 1
																	ORDER BY username ASC");
                                                } elseif ($_SESSION['UsuarioNivel'] == 3) {
                                                    $apoios = getApoios($_SESSION[UsuarioID]);
                                                    $resultAcumulados = mysql_query("SELECT a.idprod AS id, a.idprod as idprodNome, a.ativo 
																	FROM tablet a 
																	WHERE
																	a.ativo = 1
																        AND a.id_apoio IN (" . implode(',', $apoios) . ') ' .
                                                            "GROUP BY a.idprod
																	ORDER BY a.idprod");
                                                } elseif ($_SESSION['UsuarioNivel'] == 4) {

                                                    $resultAcumulados = mysql_query("SELECT a.idprod AS id, a.idprod as idprodNome, a.ativo 
																	FROM tablet a 
																	WHERE
																	a.ativo = 1
																	AND a.id_apoio = '$_SESSION[UsuarioID]'
																	GROUP BY a.idprod
																	ORDER BY a.idprod");
                                                } elseif ($_SESSION['UsuarioNivel'] == 6) {


                                                    $resultAcumulados = mysql_query("SELECT tablet.idprod as id,tablet.idprod as idprodNome,tablet.cliente,ponto.nome ponto,tablet.cadastro cadastro, tablet.validade, tablet.ligado, tablet.dificuldade, tablet.expiracao, tablet.ativo,tablet.id_ponto
															FROM tablet,ponto, user a 
															WHERE tablet.id_ponto = ponto.id AND ponto.id = a.id_apoio AND a.id = " . $_SESSION['UsuarioID'] . " AND tablet.ativo = 1 ORDER BY idprod ASC");
                                                }

                                                while ($rowUser = mysql_fetch_array($resultAcumulados)) {
                                                    echo '<option value="' . $rowUser['id'] . '" ' . $selected . '  >' . $rowUser['idprodNome'] . '</option>';
                                                }
                                                ?>

                                            </select>
                                        </div>
                                    </div><!-- /.col-lg-4 -->

                                    <div class="col-lg-5">                                             
                                        <div class="form-group input-group" id="dataPagamento"> 
                                            <span class="input-group-addon"> Data Pagamento</span>  
                                            <div class="input-daterange input-group" id="datepicker">
                                                <input type="text" class="form-control" name="start" id="start" <?php if (!empty($_POST['start'])) echo 'value="' . $_POST['start'] . '"' ?> required />
                                                <span class="input-group-addon">a</span>
                                                <input type="text" class="form-control" name="end" id="end" <?php if (!empty($_POST['end'])) echo 'value="' . $_POST['end'] . '"' ?> required />
                                            </div>
                                        </div>
                                    </div><!-- /.col-lg-4 -->

                                    <div class="col-lg-2">
                                        <button type="submit" class="btn btn-primary" data-loading-text="Loading...">Pesquisar</button>
                                    </div><!-- /.col-lg-6 -->
                                </form>
                            </div> 
                        </div>						
                        <div class="panel-body">
                            <span id="divResultPesquisaAcumuladoPagoPeriodo"></span>
                            <span id="divErrosPesquisaAcumuladoPagoPeriodo"></span>
                        </div>
                    </div>
                </div>	
            </div>
        </div> 
        <!-- Fatura -->
        <style>
            .height {
                min-height: 200px;
            }

            .icon {
                font-size: 30px;
                color: #5CB85C;
            }

            .iconbig {
                font-size: 50px;
                color: #08C;
            }

            .table > tbody > tr > .emptyrow {
                border-top: none;
            }

            .table > thead > tr > .emptyrow {
                border-bottom: none;
            }

            .table > tbody > tr > .highrow {
                border-top: 3px solid;
            }
        </style>

        <!-- Page-Level Demo Scripts - Blank - Use for reference -->
        <script>
            $(document).ready(function () {
                $('#dataTables-example').dataTable();
            });

            $(function () {
                $(".btn").click(function () {
                    $(this).button('loading').delay(10000).queue(function () {
                        //$(this).button('reset');
                    });
                });
            });

            $('#tablet').change(function () {
                $(".btn").button('reset');
            });


            $('#datepicker').change(function () {
                $(".btn").button('reset');
            });


            $('#dataPagamento .input-daterange').datepicker({
                format: "dd/mm/yyyy",
                todayBtn: "linked",
                language: "pt-BR"
            });

        </script>

        <?php
        break;

    case 'PrePagos':

        //$nivel_necessario = 3;
        $nivel_necessario = 4;
        // Verifica se não há a variável da sessão que identifica o usuário
        if (!isset($_SESSION['UsuarioID']) OR ( $_SESSION['UsuarioNivel'] > $nivel_necessario)) {
            // Destrói a sessão por segurança
            session_destroy();
            // Redireciona o visitante de volta pro login
            header("Location: index.php");
            exit;
        }

        require_once("db.php");
        ?>

        <style>
            .checkbox label:after, 
            .radio label:after {
                content: '';
                display: table;
                clear: both;
            }

            .checkbox .cr,
            .radio .cr {
                position: relative;
                display: inline-block;
                border: 1px solid #a9a9a9;
                border-radius: .25em;
                width: 1.3em;
                height: 1.3em;
                float: left;
                margin-right: .5em;
            }

            .radio .cr {
                border-radius: 50%;
            }

            .checkbox .cr .cr-icon,
            .radio .cr .cr-icon {
                position: absolute;
                font-size: .8em;
                line-height: 0;
                top: 50%;
                left: 20%;
            }

            .radio .cr .cr-icon {
                margin-left: 0.04em;
            }

            .checkbox label input[type="checkbox"],
            .radio label input[type="radio"] {
                display: none;
            }

            .checkbox label input[type="checkbox"] + .cr > .cr-icon,
            .radio label input[type="radio"] + .cr > .cr-icon {
                transform: scale(3) rotateZ(-20deg);
                opacity: 0;
                transition: all .3s ease-in;
            }

            .checkbox label input[type="checkbox"]:checked + .cr > .cr-icon,
            .radio label input[type="radio"]:checked + .cr > .cr-icon {
                transform: scale(1) rotateZ(0deg);
                opacity: 1;
            }

            .checkbox label input[type="checkbox"]:disabled + .cr,
            .radio label input[type="radio"]:disabled + .cr {
                opacity: .5;
            }			
        </style>


        <div class="panel-heading" style="min-height:60px" >
            <strong>Pré-pagos</strong>												
            <div class="pull-right">
                <button class="btn btn-primary btn-bg" data-toggle="modal" data-target="#newprepago">
                    Novo pré-pago
                </button>
                <!--a class="btn btn-rounded btn-success navbar-btn constant imprimir"
                   style ="margin-left:5px;"
                   data-rel="tooltip"
                   data-attr="crud"
                   data-placement="bottom" title="">Imprimir Selecionados</a-->
                <span class="btn btn-rounded btn-danger navbar-btn constant excluir"
                      style ="margin-left:5px;"
                      data-rel="tooltip"
                      data-attr="crud"
                      data-placement="bottom" title="">Excluir Selecionados</span>
            </div>
        </div>
        <!-- /.panel-heading -->
        <div class="panel-body">
            <div class="table-responsive">
                <table class="table table-striped table-bordered table-hover" id="dataTables-example">
                    <thead>
                        <tr>
                            <td>
                                <?php ?>
                                <div class="checkbox">
                                    <label style="font-size: 1.5em">
                                        <input type="checkbox" value="" id="checkall" name="checkall" >
                                        <span class="cr"><i class="cr-icon fa fa-check"></i></span>													
                                    </label>
                                </div>
                                <?php ?>
                            </td>
                            <td><strong>#</strong></td>
                            <td><strong>Ponto</strong></td>
                            <td><strong>Código</strong></td>
                            <td><strong>Valor</strong></td>
                            <td><strong>Ações</strong></td>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $resultPrepagos = mysql_query("SELECT pre.id id, pre.id_apoio "
                                . " id_apoio, p.nome ponto, pre.codigo codigo, pre.valor valor "
                                . " FROM pre_pago pre, ponto p "
                                . " WHERE p.id = pre.id_apoio AND p.id_apoio = " . $_SESSION['UsuarioID']
                                . " AND pre.status = 1"
                                . " ORDER BY pre.id DESC");
                        $i = 1;
                        while ($rowPrepago = mysql_fetch_array($resultPrepagos)) {
                            echo "<tr class='gradeA'>"
                            . '<td><div class="checkbox">
                                                    <label style="font-size: 1.5em">
                                                        <input type="checkbox" value="' . $rowPrepago['id'] . '" name="selecao" >
                                                        <span class="cr"><i class="cr-icon fa fa-check"></i></span>						
                                                    </label>
                              </div></td>'
                            . '<td>' . $rowPrepago['id'] . "</td>"
                            . "<td>" . $rowPrepago['ponto'] . "</td>"
                            . "<td>" . $rowPrepago['codigo'] . "</td>"
                            . "<td>" . $rowPrepago['valor'] . "</td>";
                            echo '<td style="min-width: 165px; width: 165px">';
                            ?>

                        <a class="btn btn-success btn-bg" 
                           data-id="<?php echo $rowPrepago['id'] ?>"
                           data-apoio="<?php echo $rowPrepago['id_apoio'] ?>"
                           data-valor="<?php echo $rowPrepago['valor'] ?>"
                           data-codigo="<?php echo $rowPrepago['codigo'] ?>"

                           data-toggle="modal" data-target="#editprepagomodal" role='button'><i class='fa fa-unlock-alt fa-fw' title="Alterar dados do Pré-pago"></i>
                        </a>

                        <a class="btn btn-danger btn-bg" data-id="<?php echo $rowPrepago['id'] ?>" data-toggle="modal" data-target="#deleteprepago" role='button'><i class='fa fa-times fa-fw' title="Excluir Pré-pago"></i></a>
                        <?php
                        echo "</td>";

                        $i ++;
                    }
                    ?>
                    </tbody>
                </table>
            </div>
            <!-- /.table-responsive -->
            <!-- /#page-wrapper -->
        </div>
        <!-- /#wrapper -->

        <?php include 'newprepago.php'; ?>
        <?php include 'editprepago.php'; ?>

        <!-- Modal -->
        <div class="modal fade" id="deleteprepago" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header bg-danger">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h4 class="modal-title" id="myModalLabel">Deletar Pré-pago</h4>
                    </div>
                    <div class="modal-body">    
                        <form id="frmDeletePrePago" method="POST">
                            <input type="hidden" name="id" id="id">
                        </form>

                        <h5>Você realmente deseja deletar este Pré-pago?</h5>

                    </div>
                    <div class="modal-footer">
                        <button type="button" id="btnCancelDeletePrePago" class="btn btn-default" data-dismiss="modal">Não</button>
                        <button type="button" id="btnSalvarDeletePrePago" class="btn btn-danger">Sim</button>                
                    </div>							
                </div>
                <!-- /.modal-content -->
            </div>
            <!-- /.modal-dialog -->
        </div>
        <!-- /.modal -->

        <script>

            $(document).ready(function () {
                var table = $('#dataTables-example').dataTable({
                    "columnDefs": [{
                            "targets": 0,
                            "orderable": false,
                            "width": "30px"
                        }]
                });
            });

            $('#checkall').click(function () {
                $(':checkbox').prop('checked', this.checked);
            });

            $('#frmNewPrePago').on('submit', function (ev) {
                ev.preventDefault();
                console.log("Data: " + $("#frmNewPrePago").serialize());
                $.ajax({
                    type: 'POST',
                    url: "add_pre_pago.php",
                    dataType: 'json',
                    data: $("#frmNewPrePago").serialize(),
                    async: false,
                    beforeSend: function () {
                        $('#btnSalvarNewPrePago').attr('disabled', true);
                        $('#btnCancelarPrePago').attr('disabled', true);
                        $.blockUI({
                            message: $("#loading-indicator"),
                            // css: { 
                            // top:  ($(window).height() - 25) /2 + 'px', 
                            // left: ($(window).width() - 25) /2 + 'px', 
                            // width: '25px',
                            // border: 0
                            // } 
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        $('#btnSalvarNewPrePago').attr('disabled', false);
                        $('#btnCancelarNewPrePago').attr('disabled', false);
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {
                        if (data.success) {
                            var priority = 'success';
                            $('#newprepago').modal('toggle'); //fechar o modal
                            fLoadOptionScript('PrePagos');
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });

            //triggered when modal is about to be shown
            $('#editprepagomodal').on('show.bs.modal', function (e) {

                //get data-id attribute of the clicked element
                var id = $(e.relatedTarget).data('id');
                var apoio = $(e.relatedTarget).data('apoio');
                var valor = $(e.relatedTarget).data('valor');
                var codigo = $(e.relatedTarget).data('codigo');

                //populate the textbox
                $(e.currentTarget).find('input[name="id"]').val(id);
                $(e.currentTarget).find('select[name="apoio"]').val(apoio);
                $(e.currentTarget).find('input[name="valor"]').val(valor);
                $(e.currentTarget).find('input[name="codigo"]').val(codigo);
                $(e.currentTarget).find('p[id="textCodigoPrePago"]').html(codigo);
            });

            //triggered when modal is about to be shown
            $('#deleteprepago').on('show.bs.modal', function (e) {

                //get data-id attribute of the clicked element				
                var id = $(e.relatedTarget).data('id');

                //populate the textbox				
                $(e.currentTarget).find('input[name="id"]').val(id);
            });

            $('#newprepago').on('show.bs.modal', function (e) {

                $('#btnSalvarNewPrePago').attr('disabled', true);

                $.get("get_codigo_pre_pago.php", function (data, status) {
                    $('#codigoPrePago').val(data);
                    //$('#textCodigoPrePago').html(data);

                    $('#btnSalvarNewPrePago').attr('disabled', false);
                });
            });

            $("#btnSalvarDeletePrePago").click(function (e) {

                console.log("Data: " + $("#frmDeletePrePago").serialize());

                $.ajax({
                    type: 'POST',
                    url: "deleta_pre_pago.php",
                    dataType: 'json',
                    data: $("#frmDeletePrePago").serialize(),
                    beforeSend: function () {
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {
                        if (data.success) {
                            var priority = 'success';
                            $('#deleteprepago').modal('toggle'); //fechar o modal
                            fLoadOptionScript('PrePagos');
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });

            $('#frmEditPrePago').on('submit', function (ev) {
                ev.preventDefault();

                $.ajax({
                    type: 'POST',
                    url: "edita_pre_pago.php",
                    dataType: 'json',
                    data: $("#frmEditPrePago").serialize(),
                    beforeSend: function () {
                        $('#btnSalvarEditPrePago').attr('disabled', true);
                        $('#btnCancelEditPrePago').attr('disabled', true);
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        $('#btnSalvarEditPrePago').attr('disabled', false);
                        $('#btnCancelEditPrePago').attr('disabled', false);
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {

                        if (data.success) {
                            var priority = 'success';
                            $('#editprepagomodal').modal('toggle'); //fechar o modal
                            fLoadOptionScript('PrePagos');
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });




            $('.excluir').click(function (e) {
                e.preventDefault();
                var btn = $(this);
                var ids = $("input[name=selecao]:checkbox:checked").map(function () { //table
                    return $(this).val();
                }).get();
                if (!$.isEmptyObject(ids)) {
                    var priority = 'success';
                    if (confirm('Deseja remover o(s) item(s) selecionado(s)?')) {
                        btn.attr('data-loading-text', 'Aguarde...').button('loading');
                        var crud = btn.attr("data-attr");
                        $.post('ajax_load.php', {action: 'excluir_codigos', ids: ids}, function (data) {
                            if (data.success) {
                                fLoadOptionScript('PrePagos');
                            } else {
                                priority = 'error';
                            }
                            toastr[priority](data.msg);
                        }, 'json').always(function () {
                            btn.button('reset');
                        }).fail(function () {
                            alert('Tente mais tarde.');
                        });
                    }

                } else {
                    priority = 'warning';
                    toastr[priority]('Selecione os registros para <b>excluir</b> !');
                }
            });


            $('.imprimir').click(function () {
                // e.preventDefault();
                var btn = $(this);
                var ids = $("input[name=selecao]:checkbox:checked").map(function () {
                    return $(this).val();
                }).get();
                if (!$.isEmptyObject(ids)) {
                    var priority = 'success';
                    btn.attr('data-loading-text', 'Aguarde...').button('loading');
                    $.ajax({
                        type: 'POST',
                        url: 'ajax_load.php',
                        data: {action: 'imprimir_codigos', ids: ids},
                        dataType: 'json',
                        async: false,
                        success: function (data) {
                            if (data.success) {
                                window.open('imprimir_codigos.php?dados=' + JSON.stringify(data.dados), '_blank');
                            } else {
                                priority = 'error';
                            }
                            toastr[priority](data.msg);
                        }
                    }).always(function () {
                        btn.button('reset');
                    }).fail(function () {
                        alert('Tente mais tarde.');
                    });
                } else {
                    priority = 'warning';
                    toastr[priority]('Selecione os registros para <b>imprimir</b> !');
                }
            });
        </script>


        <?php
        break;

    case 'CrashLogs':

        $nivel_necessario = 1;

        // Verifica se não há variavel da sessão que idêntifica o usuário
        if (!isset($_SESSION['UsuarioID']) OR ( $_SESSION['UsuarioNivel'] > $nivel_necessario)) {
            // DestrÃ³i a sessÃ£o por seguranÃ§a
            session_destroy();
            // Redireciona o visitante de volta pro login
            header("Location: index.php");
            exit;
        }

        require_once("db.php");
        ?>

        <div class="panel-heading" style="min-height:60px" >
            <strong>Crash Logs</strong>
        </div>
        <!-- /.panel-heading -->
        <div class="panel-body">

            <div class="table-responsive">
                <table class="table table-striped table-bordered table-hover" id="dataTables-example">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Data e Horário</th>
                            <th>Cliente</th>
                            <th>Dispositivo</th>
                            <th>Plataforma</th>
                            <th>Versão</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $result = mysql_query("SELECT c.id, DATE_FORMAT(c.datetime,'%d/%m/%Y %H:%i:%s') "
                                . " AS datetime, c.idprod, c.platform, c.version,u.nome  "
                                . " FROM crashlog c LEFT JOIN tablet t ON c.idprod = t.idprod "
                                . " LEFT JOIN user u ON u.id = t.id_apoio"
                                . " WHERE 1"
                                . " ORDER BY c.id DESC");

                        $i = 1;
                        while ($row = mysql_fetch_array($result)) {

                            $id = $row['id'];
                            $datetime = $row['datetime'];
                            $idprod = $row['idprod'];
                            $platform = $row['platform'];
                            $version = $row['version'];
                            $cliente = $row['nome'];
                            $downloadUrl = "download_crashlog_text.php?id=" . $id;

                            echo "<tr class='gradeA'><td>" . $id . "</td>"
                            . "<td>" . $datetime . "</td>"
                            . "<td>" . $cliente . "</td>"
                            . "<td>" . $idprod . "</td>"
                            . "<td>" . $platform . "</td>"
                            . "<td>" . $version . "</td>";

                            echo '<td style="min-width: 165px; width: 165px">';
                            ?>

                        <a class="btn btn-primary" id="btnDownloadCrashLogText" onclick="location.href = '<?= $downloadUrl ?>'"><i class='fa fa-download fa-fw'></i></a>
                        <a class="btn btn-danger btn-bg" data-id="<?php echo $id ?>" data-toggle="modal" data-target="#deletecrashlog" role='button'><i class='fa fa-times fa-fw' title="Excluir Crash Log?"></i></a>
                        <?php
                        echo "</td>";

                        $i ++;
                    }
                    ?>
                    </tbody>
                </table>
            </div>
            <!-- /.table-responsive -->
            <!-- /#page-wrapper -->
        </div>
        <!-- /#wrapper -->

        <!-- Modal -->
        <div class="modal fade" id="deletecrashlog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header bg-danger">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h4 class="modal-title" id="myModalLabel">Deletar Crash Log</h4>
                    </div>
                    <div class="modal-body">    
                        <form id="frmDeleteCrashLog" method="POST">
                            <input type="hidden" name="id" id="id">
                        </form>

                        <h5>Você realmente deseja deletar este Crash Log?</h5>

                    </div>
                    <div class="modal-footer">
                        <button type="button" id="btnCancelDeleteCrashLog" class="btn btn-default" data-dismiss="modal">Não</button>
                        <button type="button" id="btnSalvarDeleteCrashLog" class="btn btn-danger">Sim</button>                
                    </div>							
                </div>
                <!-- /.modal-content -->
            </div>
            <!-- /.modal-dialog -->
        </div>
        <!-- /.modal -->

        <script>

            $(document).ready(function () {
                $('#dataTables-example').dataTable();
            });

            //triggered when modal is about to be shown
            $('#deletecrashlog').on('show.bs.modal', function (e) {

                //get data-id attribute of the clicked element				
                var id = $(e.relatedTarget).data('id');

                //populate the textbox				
                $(e.currentTarget).find('input[name="id"]').val(id);
            });

            $("#btnSalvarDeleteCrashLog").click(function (e) {

                console.log("Data: " + $("#frmDeleteCrashLog").serialize());

                $.ajax({
                    type: 'POST',
                    url: "deleta_crash_log.php",
                    dataType: 'json',
                    data: $("#frmDeleteCrashLog").serialize(),
                    beforeSend: function () {
                        $.blockUI({
                            message: $("#loading-indicator"),
                            css: {
                                border: 'none',
                                padding: '15px',
                                background: '',
                                // opacity: 0.8, 
                                color: '#fff'
                            }
                        });
                    },
                    complete: function () {
                        setTimeout($.unblockUI, 500);
                    },
                    success: function (data) {

                        if (data.success) {
                            var priority = 'success';
                            $('#deletecrashlog').modal('toggle'); //fechar o modal
                            fLoadOptionScript('CrashLogs');
                        } else {
                            var priority = 'error';
                        }
                        toastr[priority](data.msg);
                    }
                });
            });

        </script>
        <?php
        break;

    default:

        echo "<div class='alert alert-danger'>ERRO AO INCLUIR OPÇÃO!</div>";
        exit;

        break;
}    