<?php
$filename = 'c_leitura.php';

session_start();
error_reporting(0);
if (!file_exists($filename)) {
    header("Location: error.php");
    exit;
}
include $filename;
require_once("db.php");
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <link rel="shortcut icon" href="img/logo.ico" type="image/x-icon" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
        <title>Gerenciamento de Tablets</title>
        <link href="css/bootstrap2.css" rel="stylesheet">
        <link href="font-awesome/css/font-awesome.css" rel="stylesheet">
        <link href="css/toastr.min.css" rel="stylesheet" type="text/css" />
        <link href="css/sb-admin-2.css" rel="stylesheet">
        <link href="css/plugins/dataTables/dataTables.bootstrap.css" rel="stylesheet">
        <link href="datepicker/css/datepicker3.css" rel="stylesheet">
        <script src="js/modernizr.js"></script> <!-- Modernizr -->

        <!-- Page-Level Plugin CSS - Blank 
<link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<link href="http://netdna.bootstrapcdn.com/font-awesome/3.1.1/css/font-awesome.min.css" rel="stylesheet">
<link href="http://cdnjs.cloudflare.com/ajax/libs/x-editable/1.4.4/bootstrap-editable/css/bootstrap-editable.css" rel="stylesheet">
<link href="css/bootstrap-filterable.css" rel="stylesheet" type="text/css">
        -->		
        <style>
            #loading-indicator {
                position: absolute;
                left: 50%;
                top: 50%;
                width: 64px;
                height: 64px;
                margin-left: -32px;
                margin-top: -32px;
                border: 0;
                z-index: 6000;
            }	
        </style>
    </head>	
    <?php
    // para os perfis: Operador e funcionário
    if ($_SESSION['UsuarioNivel'] >= 5) {
        $loadInitialPage = 'Tablets';
    } else {
        $loadInitialPage = 'Home';
    }
    ?>

    <body onload="fLoadOptionScriptHome('<?php echo $loadInitialPage ?>')">        

        <div id="wrapper">
            <?php //include 'header.php'; ?>
            <?php include 'navbar.php'; ?>
            <div id="page-wrapper">
                <div class="row">
                    <div class="col-lg-12">
                        <h1 class="page-header"></h1> 
                    </div>
                    <!-- /.col-lg-12 -->
                </div>
                <!-- /.row -->
                <div class="row">				
                    <div class="col-lg-12">
                        <div class="panel panel-default" id="divPages"></div>
                        <div class="panel panel-default" id="divErrosPages"></div>
                    </div>
                </div><!-- /.row -->
            </div> 
            <!-- /#wrapper -->
        </div>
        <!-- inclusão de ajax -->
        <script src="js/ajax.js"></script>

        <!-- jQuery (necessary for Bootstrap's JavaScript plugins) 
        <script src="js/jquery.min.js"></script> -->
        <script src="js/jquery-2.1.1.js"></script>

        <script src="js/bootstrap.min.js"></script>
        <script src="js/plugins/metisMenu/jquery.metisMenu.js"></script>

        <!-- Page-Level Plugin Scripts - Blank -->

        <script src="js/plugins/dataTables/jquery.dataTables.js"></script>
        <script src="js/plugins/dataTables/dataTables.bootstrap.js"></script>

        <!-- SB Admin Scripts - Include with every page -->
        <script src="js/sb-admin-2.js"></script>

        <!-- Date Picker -->

        <script src="datepicker/js/bootstrap-datepicker.js"></script>

        <script src="js/jquery.blockUI.js"></script>

        <script src="js/toastr.min.js"></script>	

        <script src="js/jquery.mixitup.min.js"></script>

        <!-- CHART PLUGINS -->
        <script src="js/plugins/echarts/echarts.js" type="text/javascript"></script>

        <script src="js/jquery.filterable.js"></script> 
        <script>
        $(document).ready(function () {
            $('#dataTables-example').dataTable({sortList: [[5, 0]]});
            $('#dataTables-maquinas').dataTable({sortList: [[5, 0]]});

            toastr.options = {
                "closeButton": true,
                "debug": false,
                "newestOnTop": false,
                "progressBar": false,
                "positionClass": "toast-top-full-width",
                "preventDuplicates": false,
                "onclick": null,
                "showDuration": "300",
                "hideDuration": "1000",
                "timeOut": "5000",
                "extendedTimeOut": "1000",
                "showEasing": "swing",
                "hideEasing": "linear",
                "showMethod": "fadeIn",
                "hideMethod": "fadeOut"
            };
        });

        function pesquisarFaturas() {

            var cliente = $("#frmBuscaFaturas #cliente").val();
            var status = $("#frmBuscaFaturas #status").val();
            fLoadPerquisarFaturasScript(cliente, status);

            return false;
        }


        function pesquisarCobrancasReceber() {

            var cliente = $("#frmBuscaCobrancasReceber #cliente").val();
            var status = $("#frmBuscaCobrancasReceber #status").val();
            fLoadPerquisarCobrancasReceberScript(cliente, status);

            return false;
        }

        function pesquisarCobrancasPagar() {

            var cliente = $("#frmBuscaCobrancasPagar #cliente").val();
            var status = $("#frmBuscaCobrancasPagar #status").val();
            fLoadPerquisarCobrancasPagarScript(cliente, status);

            return false;
        }

        function pesquisarTransacoesPeriodo() {

            var tablet = $("#frmBuscaTransacoes #tablet").val();
            var start = $("#frmBuscaTransacoes #start").val();
            var end = $("#frmBuscaTransacoes #end").val();
            var tipo = $("#frmBuscaTransacoes #tipo").val();
            fLoadPerquisarTransacaoScript(tablet, start, end, tipo);

            return false;
        }

        function pesquisarFaturasPeriodo() {

            var cliente = $("#frmBuscaFaturasPeriodo #cliente").val();
            var start = $("#frmBuscaFaturasPeriodo #start").val();
            var end = $("#frmBuscaFaturasPeriodo #end").val();
            fLoadPerquisarFaturasPeriodoScript(cliente, start, end);

            return false;
        }

        function perquisarMovimentacao() {

            var user = $("#frmPesquisarMovimentacoes #user").val();
            var start = $("#frmPesquisarMovimentacoes #start").val();
            var end = $("#frmPesquisarMovimentacoes #end").val();
            fLoadPerquisarMovimentacaoScript(user, start, end);

            return false;
        }


        function perquisarAcumuladoPago() {

            var filtro = $("#frmPesquisarAcumuladoPago #filtro").val();
            var start = $("#frmPesquisarAcumuladoPago #start").val();
            var end = $("#frmPesquisarAcumuladoPago #end").val();
            fLoadPerquisarAcumuladosPagosScript(filtro, start, end);

            return false;
        }

        function alterarStatusFatura(id, opt) {

            $.ajax({
                type: 'POST',
                url: 'estado_fatura.php',
                dataType: 'json',
                data: {'id': id, 'opt': opt},
                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';
                    } else {
                        var priority = 'error';
                    }
                    toastr[priority](data.msg);
                    fLoadOptionScript('GerenciarFaturas');
                }
            });
        }


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

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

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

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

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


        function fRemoverCreditos(idprod, tipo) {
            $.ajax({
                type: 'POST',
                url: "add_creditos.php",
                dataType: 'json',
                data: {'idprod': idprod, 'tipo': tipo},
                beforeSend: function () {
                    $('.btnremoverCreditosTablet').attr('disabled', true);
                    $.blockUI({
                        message: $("#loading-indicator"),
                        css: {
                            border: 'none',
                            padding: '15px',
                            background: '',
                            // opacity: 0.8, 
                            color: '#fff'
                        }
                    });
                },
                complete: function () {
                    $('.btnremoverCreditosTablet').attr('disabled', false);
                    // setTimeout($.unblockUI, 300);									
                },
                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);
                            }

                        }, 999);

                        //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');
                    }
                }
            });
        }

        function fSalvarEdicaoTablet(idProd) {

            var $form = $("#frmEditarTablet" + idProd);

            $.ajax({
                type: 'POST',
                url: "edita_tablet.php",
                dataType: 'json',
                data: $form.serialize(),
                beforeSend: function () {
                    // $('.btnSalvarEditTablet').attr('disabled', true);	
                    $.blockUI({
                        message: $("#loading-indicator"),
                        css: {
                            border: 'none',
                            padding: '15px',
                            background: '',
                            // opacity: 0.8, 
                            color: '#fff'
                        }
                    });
                },
                complete: function () {

                    $('#myModalEditarTablet' + idProd).modal('toggle'); //fechar o modal
                    // $('.btnSalvarEditTablet').attr('disabled', false);
                    setTimeout($.unblockUI, 500);
                },
                success: function (data) {
                    if (data.success) {
                        var priority = 'success';
                    } else {
                        var priority = 'error';
                    }
                    toastr[priority](data.msg);
                    fLoadOptionScript('Tablets');
                }
            });


            return false;
        }

        function fZerarLeituraParcial(idCliente) {
            $.ajax({
                type: 'POST',
                url: "zerar_parcial.php",
                dataType: 'json',
                data: {idCliente: idCliente},
                beforeSend: function () {
                    $.blockUI({
                        message: $("#loading-indicator"),
                        css: {
                            border: 'none',
                            padding: '15px',
                            background: '',
                            color: '#fff'
                        }
                    });
                },
                complete: function () {
                    setTimeout($.unblockUI, 500);
                },
                success: function (data) {
                    if (data.success) {
                        var priority = 'success';
                    } else {
                        var priority = 'error';
                    }
                    toastr[priority](data.msg);
                    fLoadOptionScriptLeitura('LeituraParcial', '<?php echo $_SESSION['pais'] ?>');
                }
            });
        }
var intervalfInitAutoLoad;
<?php if ($_SESSION['UsuarioNivel'] > 2) { ?>
            function fInitAutoLoad() {
              intervalfInitAutoLoad =  setInterval(function () {
                    $('#leituraTopo').load('leituratopo.php?id_tela=' + $("#idTela").val() + '&idPais=' +'<?php echo $_SESSION['pais'] ?>').fadeIn("slow");
                }, 5000);
            }
<?php } else {
    ?>
            function fInitAutoLoad() {
               intervalfInitAutoLoad = setInterval(function () {
                    $('#leituraTopo').load('leituratopo.php?id_tela=' + $("#idTela").val() + '&idPais=' + $("#idPais").val()).fadeIn("slow");
                }, 5000);
            }
    <?php
}
?>

        function fShowNotifyFaturaAberto(msg, title) {

            var toastrOptions = {
                "closeButton": true,
                "debug": false,
                "newestOnTop": false,
                "progressBar": false,
                "positionClass": "toast-top-right",
                "preventDuplicates": false,
                "onclick": null,
                "showDuration": "300",
                "hideDuration": "1000",
                "timeOut": 0,
                "extendedTimeOut": 0,
                "showEasing": "swing",
                "hideEasing": "linear",
                "showMethod": "fadeIn",
                "hideMethod": "fadeOut",
                "tapToDismiss": false
            }
            toastr.warning(msg, title, toastrOptions);
        }


        function fGerarPdfCobranca(idCobranca) {

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

        </script>

        <!--
        <img src="img/loading.gif" id="loading-indicator" style="display:none;" />	
        -->
        <?php
        //verificar se possui faturas em aberto, apenas para clientes
        $resultContaPagar = mysql_query("SELECT a.id_cobranca, a.id_cliente, c.nome AS clientePonto, a.data_vencimento, a.periodo_prestacao, a.valor_total, a.pago, 
										a.data_pagamento, c.id_apoio, a.tipo_cobranca, DATEDIFF(a.data_vencimento, NOW()) AS dias_para_vencimento
										FROM cobranca_agregado a
										LEFT JOIN user c ON c.id = a.id_cliente
										WHERE
										a.pago = 0
										AND a.ativo = 1
										AND DATEDIFF(a.data_vencimento, NOW()) <= 3
										AND a.id_cliente = '$_SESSION[UsuarioID]'
										AND a.cobranca_fechada = 1") or die(mysql_error());
        $totalRegitros = mysql_num_rows($resultContaPagar);
        $rowContaPagar = mysql_fetch_array($resultContaPagar);

        if ($totalRegitros > 0) {

            $dataVencimento = fConvData($rowContaPagar['data_vencimento']);
            ?>
            <script>fShowNotifyFaturaAberto("Você possui uma fatura com vencimento em " + '<?php echo $dataVencimento ?>' + " em nosso sistema.</br></br>Evite o Bloqueio do Sistema", "Atenção")</script>
            <?php
        }
        ?>

        <div class="loader" id="loading-indicator" style="display:none" ><iframe src="loading/loading.php" width="80" height="100" scrolling="no"  frameborder="0" allowtransparency="true">   </iframe></div>

    </body>

</html>
