<?php //echo ini_get('max_execution_time')                ?>
<?php
require("config.php");
//$debug = "1";
require("includes/debug.php");
require("includes/functions.php");
require("includes/logincheck.php");
require("includes/settings.php");


$aid = $_SESSION["adminid"];

if (isset($_GET["p"])) {
    
    $param = json_decode(base64_decode($_GET["p"]), true);
    
    if (key_exists("id", $param)) {
        
        $aid = $param["id"];
        
    }
}

$pf_pm = unserialize($_SESSION["_profiles_pm"]);

if (is_null($pf_pm)) {
    
    $pf_pm = array();
    
}

$dados_revenda = dados_revenda($aid, 'rev_pre');

$rev_pre = $_SESSION['rev_pre'];

// restrigindo somente as revendas pós
if($rev_pre == '1' || $dados_revenda['rev_pre'] == '1'){
    
    $js = <<<EOF
            <script>
                  alert('indisponivel para revendas pre pagas.');
                  window.history.go(-1);
            </script>
            
EOF;
    exit($js);
    
}

//set_time_limit(1200);
?>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
        <meta http-equiv="Content-Type" content="text/html; charset=<?php print($charset); ?>" />
        <title><?php print($longtitle); ?></title>
        <link rel="shortcut icon" href="favicon.ico"/>
        <link rel="apple-touch-icon" href="favicon.png"/> 

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
            <link href="css/main.css" rel="stylesheet" type="text/css" />
            <script type="text/javascript" src="js/jquery.js"></script> 
    </head>
    <style>
        #relatorio td{
            padding: 7px;
        }
        #relatorio ul{
            list-style: none;
            padding: 0px;
        }
        #relatorio li{
            padding-top: 2px;
        }

    </style>
    <body>                      
        <?php require_once 'topo.php'; ?>
        <table width="980" border="0" align="center" valign="top" cellpadding="2" cellspacing="1" style="border: solid 0px #DDDDDD" id="relatorio">
            <?php
            $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
            mysql_select_db($dbname, $conn);
            $sSQL = "SELECT id,addedby,username,level,realname FROM cmum_admins WHERE id=$aid";
            $result = mysql_query($sSQL);

            $revs = array();
            while ($linha = mysql_fetch_array($result)) {
                $revs[$linha['id']] = array('id' => $linha['id'], 'parent' => $linha['addedby'], 'title' => $linha['username']);
                $revID = $linha['addedby'];
                $level = $linha['level'];
                while ($level > 0) {
                    $sSQL = "SELECT id,addedby,username,level,realname FROM cmum_admins WHERE id=$revID";
                    $result = mysql_query($sSQL);
                    $linha = mysql_fetch_array($result);
                    $revs[$linha['id']] = array('id' => $linha['id'], 'parent' => $linha['addedby'], 'title' => $linha['username']);
                    $revID = $linha['addedby'];
                    $level = $linha['level'];
                }
            }

            function breadcrumbs($id) {

                // $p = base64_encode("{\"id\":{$GLOBALS['revs'][$id]['id']}}");
                $json["id"] = "{$GLOBALS['revs'][$id]['id']}";
                $p = base64_encode(json_encode($json));

                if ($id >= $_SESSION['adminid']) {
                    if ($GLOBALS['revs'][$id]['parent'] > 0) {
                        return breadcrumbs($GLOBALS['revs'][$id]['parent']) . "<li><a href='?p=$p'>" . $GLOBALS['revs'][$id]['title'] . "</a></li>";
                    } else {
                        return "<li><a href='?p=$p'>" . $GLOBALS['revs'][$id]['title'] . '</a></li>';
                    }
                }
            }
            ?>
            <tr >
                <td colspan="3" style="border: solid 0px red; height: 25px; font-size: 12pt"><span>Você está em:</span><ul class="breadcrumb" style="height: 50px; line-height: 50px; padding-left:5px;"><?php echo breadcrumbs($aid) ?></ul></td>
            </tr>
            <tr>
                <td width="33%">
                    <fieldset>
                        <h5>Filtro Por Revendas</h5>
                        <form name="formFiltro" id="formFiltro" method="" action="?filtro=revenda">
                            <table>
                                <tr>
                                    <td></td><td>
                                        <select name='p' class='form-control' id="p" onchange="this.form.submit()">
                                            <?php
                                            $json["id"] = "{$_SESSION['adminid']}";
                                            $p = base64_encode(json_encode($json));
                                            ?>
                                            <option value="<?php echo $p ?>"><?php echo $_SESSION['loginuser'] ?></option>
                                            <?php
                                            $arvore = arvoreRevendas2();
                                            $arvore_lista = arvoreRevendasLista();
                                            listaOptionsRenvendas($arvore[$_SESSION['adminid']], $arvore_lista, isset($_GET['p']) ? $_GET['p'] : "", $_SESSION['_hierarquia']);
                                            ?>
                                        </select>
                                    </td><td><input type="submit" value="Filtrar" name="" <?php if ($numReg == 0) { ?>disabled="true"<?php } ?> class="btn btn-default"/></td>
                                </tr>
                            </table>
                        </form>
                    </fieldset>
                </td>
                <td width="33%">
                    <fieldset>
                        <h5>Opções Logins</h5>
                        <form>
                            <?php if (isset($_GET['p'])): ?>
                                <input type="hidden" name="p" value="<?php echo $_GET['p']; ?>"/>
                            <?php endif; ?>
                            <table>
                                <tr>
                                    <td></td>
                                    <td>
                                        <select class="form-control" name="opc_logins" onchange="this.form.submit();">
                                            <option value="1" <?php if (isset($_GET['opc_logins']) && $_GET['opc_logins'] == 1): ?> selected<?php endif; ?>>Ativos</option>
                                            <option value="2" <?php if (isset($_GET['opc_logins']) && $_GET['opc_logins'] == 2): ?> selected<?php endif; ?>>Desativados</option>
                                            <option value="3" <?php if (isset($_GET['opc_logins']) && $_GET['opc_logins'] == 3): ?> selected<?php endif; ?>>Testes</option>
                                            <option value="4" <?php if (isset($_GET['opc_logins']) && $_GET['opc_logins'] == 4): ?> selected<?php endif; ?>>Vencidos</option>
                                        </select>
                                    </td>
                                </tr>
                            </table> 
                        </form>
                    </fieldset>
                </td>
                <td width="33%">
                    <fieldset>                        
                        <h5>Filtro Por Perfil</h5>
                        <form>
                            <?php if (isset($_GET['p'])): ?>
                                <input type="hidden" name="p" value="<?php echo $_GET['p']; ?>"/>
                            <?php endif; ?>
                            <?php if (isset($_GET['opc_logins'])): ?>
                                <input type="hidden" name="opc_logins" value="<?php echo $_GET['opc_logins']; ?>"/>
                            <?php endif; ?>
                            <table>
                                <tr>
                                    <td>Perfil:</td>
                                    <td>
                                        <?php
                                        $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
                                        $SQL = "SELECT * FROM cmum_profiles ORDER BY value ASC";
                                        $rs = $conn->query($SQL);
                                        $ls_pfs = array();
                                        while ($reg_pf = $rs->fetch_assoc()) {
                                            $ls_pfs[$reg_pf['value']] = $reg_pf;
                                        }
                                        ?>
                                        <select class="form-control" name="perfil" onchange="this.form.submit();">
                                            <?php if ($rs !== false): ?>
                                                <option value="0" <?php
                                                if ((isset($_GET['perfil']) && 0 == $_GET['perfil']) || !isset($_GET['perfil'])) {
                                                    echo "selected";
                                                }
                                                ?>>-- Todos --</option>
                                                        <?php foreach ($ls_pfs as $ls_pf): ?>
                                                            <?php if ($_SESSION['adminlevel'] == "0" || ($_SESSION['adminlevel'] != "0" && array_search($ls_pf['id'], $pf_pm) !== false)): ?>
                                                        <option value="<?php echo $ls_pf['id'] ?>" <?php
                                                        if (isset($_GET['perfil']) && $ls_pf['id'] == $_GET['perfil']) {
                                                            echo "selected";
                                                        }
                                                        ?>><?php echo $ls_pf['name'] ?></option>
                                                            <?php endif; ?>
                                                        <?php endforeach; ?>
                                                    <?php else: ?>
                                                <option>Não Ha Perfis</option>
                                            <?php endif; ?>
                                        </select>
                                    </td>
                                    <td><!--<input type="submit" class="btn btn-default" value="Filtrar"/>--></td>
                                </tr>
                            </table>
                        </form>
                    </fieldset>
                </td>
                <td align="right">
                    <!--<fieldset>
                        <h5>Buscar por login ou nome:</h5>
                        <form method="post">
                            <table>
                                <tr>
                                    <td></td><td><input type="text" name="bcLogin" class="form-control" id="bcLogin" value="<?php echo isset($_POST["bcLogin"]) ? $_POST["bcLogin"] : ""; ?>"/></td>
                                    <td><input type="submit" name="" id="btBcLogin" value="Buscar" class="btn btn-default"/></td>
                                </tr>
                            </table>
                        </form>
                    </fieldset>-->
                </td>

            </tr><!-- tr filtro rev e perfl -->


            <?php
            $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
            mysql_select_db($dbname, $conn);
            if ((isset($_GET['opc_logins']) && $_GET['opc_logins'] == 1) || !isset($_GET['opc_logins'])) {//Logins ativos
                $SQL = "select `a`.`id` AS `id`,`a`.`username` AS `username`,(select count(`vw1`.`name`) from `cmum_logins_ativos_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id`)) AS `total_ativos`,ifnull((select sum(`vw1`.`maxconnections`) from `cmum_logins_ativos_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id`)),0) AS `total_por_con` from `cmum_admins` `a` where a.id = '{$aid}'";
                if (isset($_GET['perfil']) && (is_numeric($_GET['perfil']) && $_GET['perfil'] != 0)) {
                    $SQL = "select `a`.`id` AS `id`,`a`.`username` AS `username`,(select count(`vw1`.`name`) from `cmum_logins_ativos_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id` AND vw1.id_profile = '{$_GET['perfil']}')) AS `total_ativos`,ifnull((select sum(`vw1`.`maxconnections`) from `cmum_logins_ativos_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id` AND vw1.id_profile = '{$_GET['perfil']}')),0) AS `total_por_con` from `cmum_admins` `a` where a.id = '{$aid}'";
                }
            }
            if ((isset($_GET['opc_logins']) && $_GET['opc_logins'] == 2)) {//Logins ativos
                $SQL = "select `a`.`id` AS `id`,`a`.`username` AS `username`,(select count(`vw1`.`name`) from `cmum_logins_desativados_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id`)) AS `total_ativos`,ifnull((select sum(`vw1`.`maxconnections`) from `cmum_logins_desativados_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id`)),0) AS `total_por_con` from `cmum_admins` `a` where a.id = '{$aid}'";
                if (isset($_GET['perfil']) && (is_numeric($_GET['perfil']) && $_GET['perfil'] != 0)) {
                    $SQL = "select `a`.`id` AS `id`,`a`.`username` AS `username`,(select count(`vw1`.`name`) from `cmum_logins_desativados_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id` AND vw1.id_profile = '{$_GET['perfil']}')) AS `total_ativos`,ifnull((select sum(`vw1`.`maxconnections`) from `cmum_logins_desativados_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id` AND vw1.id_profile = '{$_GET['perfil']}')),0) AS `total_por_con` from `cmum_admins` `a` where a.id = '{$aid}'";
                }
            }
            if ((isset($_GET['opc_logins']) && $_GET['opc_logins'] == 3)) {// Logins testes
                $SQL = "select `a`.`id` AS `id`,`a`.`username` AS `username`,(select count(`vw1`.`name`) from `cmum_logins_testes_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id`)) AS `total_ativos`,ifnull((select sum(`vw1`.`maxconnections`) from `cmum_logins_testes_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id`)),0) AS `total_por_con` from `cmum_admins` `a` where a.id = '{$aid}'";
                if (isset($_GET['perfil']) && (is_numeric($_GET['perfil']) && $_GET['perfil'] != 0)) {
                    $SQL = "select `a`.`id` AS `id`,`a`.`username` AS `username`,(select count(`vw1`.`name`) from `cmum_logins_testes_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id` AND vw1.id_profile = '{$_GET['perfil']}')) AS `total_ativos`,ifnull((select sum(`vw1`.`maxconnections`) from `cmum_logins_testes_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id` AND vw1.id_profile = '{$_GET['perfil']}')),0) AS `total_por_con` from `cmum_admins` `a` where a.id = '{$aid}'";
                }
            }
            if ((isset($_GET['opc_logins']) && $_GET['opc_logins'] == 4)) {// Logins testes
                $SQL = "select `a`.`id` AS `id`,`a`.`username` AS `username`,(select count(`vw1`.`name`) from `cmum_logins_vencidos_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id`)) AS `total_ativos`,ifnull((select sum(`vw1`.`maxconnections`) from `cmum_logins_vencidos_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id`)),0) AS `total_por_con` from `cmum_admins` `a` where a.id = '{$aid}'";
                if (isset($_GET['perfil']) && (is_numeric($_GET['perfil']) && $_GET['perfil'] != 0)) {
                    $SQL = "select `a`.`id` AS `id`,`a`.`username` AS `username`,(select count(`vw1`.`name`) from `cmum_logins_vencidos_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id` AND vw1.id_profile = '{$_GET['perfil']}')) AS `total_ativos`,ifnull((select sum(`vw1`.`maxconnections`) from `cmum_logins_vencidos_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id` AND vw1.id_profile = '{$_GET['perfil']}')),0) AS `total_por_con` from `cmum_admins` `a` where a.id = '{$aid}'";
                }
            }


            $result = mysql_query($SQL);
            $line = mysql_fetch_assoc($result);
            
            //Numero de revendas
            $SQL = "SELECT * FROM cmum_admins_pais_filhos WHERE id_pai = '{$aid}'";
            $rs = mysql_query($SQL);
            $total_revs = mysql_num_rows($rs);
            //Somando de subrevendas
            $filhos = arvoreRevendasSemTotais();
            if ((isset($_GET['opc_logins']) && $_GET['opc_logins'] == 1) || !isset($_GET['opc_logins'])) {
                $logins_atv_revs = totalPorRevendasSub($aid, $filhos, 0, (isset($_GET['perfil']) && is_numeric($_GET['perfil']) && $_GET['perfil'] != 0) ? $_GET['perfil'] : NULL);
                $logins_atv_revs_con = totalPorRevendasSub($aid, $filhos, 1, (isset($_GET['perfil']) && is_numeric($_GET['perfil']) && $_GET['perfil'] != 0) ? $_GET['perfil'] : NULL);
            }
            if ((isset($_GET['opc_logins']) && $_GET['opc_logins'] == 2)) {
                $logins_atv_revs = totalPorRevendasSubDesat($aid, $filhos, 0, (isset($_GET['perfil']) && is_numeric($_GET['perfil']) && $_GET['perfil'] != 0) ? $_GET['perfil'] : NULL);
                $logins_atv_revs_con = totalPorRevendasSubDesat($aid, $filhos, 1, (isset($_GET['perfil']) && is_numeric($_GET['perfil']) && $_GET['perfil'] != 0) ? $_GET['perfil'] : NULL);
            }
            if ((isset($_GET['opc_logins']) && $_GET['opc_logins'] == 3)) {
                $logins_atv_revs = totalPorRevendasSubTestes($aid, $filhos, 0, (isset($_GET['perfil']) && is_numeric($_GET['perfil']) && $_GET['perfil'] != 0) ? $_GET['perfil'] : NULL);
                $logins_atv_revs_con = totalPorRevendasSubTestes($aid, $filhos, 1, (isset($_GET['perfil']) && is_numeric($_GET['perfil']) && $_GET['perfil'] != 0) ? $_GET['perfil'] : NULL);
            }
            if ((isset($_GET['opc_logins']) && $_GET['opc_logins'] == 4)) {
                $logins_atv_revs = totalPorRevendasSubVenc($aid, $filhos, 0, (isset($_GET['perfil']) && is_numeric($_GET['perfil']) && $_GET['perfil'] != 0) ? $_GET['perfil'] : NULL);
                $logins_atv_revs_con = totalPorRevendasSubVenc($aid, $filhos, 1, (isset($_GET['perfil']) && is_numeric($_GET['perfil']) && $_GET['perfil'] != 0) ? $_GET['perfil'] : NULL);
            }
            
            $total_geral_ativos = $line["total_ativos"] + $logins_atv_revs;
            
            $total_geral_ativos_con = $line["total_por_con"] + $logins_atv_revs_con;
            
            $dados_revenda = dados_revenda($aid, "valor_cob_login");
            
            $valor_cob_login = $dados_revenda['valor_cob_login'];
            
            //var_dump($valor_cob_login);
            
            ?>
            <tr >
                <td colspan="2"><h4>Relatorio de <u><?php echo $line["username"]; ?></u></h4></td>
            </tr>
            <tr  >
                <td width="20%">Logins:</td><td><?php echo $line["total_ativos"]; ?></td>
            </tr>
            <tr>
                <td width="20%">Logins por conexao</td><td><?php echo $line["total_por_con"]; ?></td>
            </tr>                            
            <!--<tr  >
                <td width="20%">Logins testes</td><td><?php //echo $line["cTes"];           ?></td>
            </tr>
            <tr >
                <td width="20%">Logins desativado ou vencidos</td><td><?php //echo $line["cIna"];           ?></td>
            </tr>-->
            <tr>
                <td width="20%" valign="top"><strong>Numero de Revendas:</strong></td><td><strong><?php echo $total_revs; ?></strong></td>
            </tr>
            <tr>
                <td width="20%" valign="top">Logins revendas</td><td><?php echo $logins_atv_revs; ?></td>
            </tr>
            <tr>
                <td width="20%" valign="top">Logins revendas por conexão</td><td><?php echo $logins_atv_revs_con; ?></td>
            </tr>

            <tr>
                <td colspan="2"><hr/></td>
            </tr>
            <tr>
                <td width="20%" valign="top"><strong>Total: Logins + Logins revendas</strong></td><td><?php echo  $total_geral_ativos ?> * <?php echo "R$ ".$valor_cob_login; ?><span style="font-size: 8pt;">&nbsp;(Valor por login)</span> R$ <?=  number_format($total_geral_ativos * $valor_cob_login,2)?><span style="font-size: 8pt;">&nbsp;(Valor a ser pago)</span></td>
            </tr>
            <tr>
                <td width="20%" valign="top"><strong>Total: Logins por conexão + Logins revendas por conexão</strong></td><td><?php echo $total_geral_ativos_con; ?> * <?php echo "R$ ".$valor_cob_login; ?><span style="font-size: 8pt;">&nbsp;(Valor por login)</span>  R$ <?=number_format($total_geral_ativos_con * $valor_cob_login,2)?><span style="font-size: 8pt;">&nbsp;(Valor a ser pago)</span></td>
            </tr>
            <!-- Removido tabela revendedores -->
            </td> 
            </tr>
        </table>
        </table>
        <?php
        require("includes/footer.php");
        ?>
    </body>
</html>