<?php
require("includes/logincheck.php");
require("config.php");
require("includes/debug.php");
require("includes/functions.php");
require("includes/settings.php");

$admId = $_SESSION["adminid"];
$level = $_SESSION["adminlevel"];
$id = "";
if (isset($_GET["p"])) {
    $param = json_decode(base64_decode($_GET["p"]), true);
    if (key_exists("id", $param)) {
        $admId = $param["id"];
    }
}

$opc_rev = unserialize($_SESSION["_opcoes_rev"]);
if (is_null($opc_rev)) {
    $opc_rev = array();
}

$admLevel = $_SESSION["adminlevel"];

$adminexists = "false";
$status = "";
$uadmin = "";
$padmin = "";
$level = "";
$lastadmin = "";
$nouserpass = "false";
$rowcolor = "#FFFFFF";

if (isset($_POST["baction"]) and $_POST["baction"] == "Yes") {
    $adminid = $_POST["adminid"];
    $username = $_POST["username"];
    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
    mysql_select_db($dbname, $conn);
    $sql = mysql_query("SELECT * FROM cmum_admins");
    $rowcheck = mysql_num_rows($sql);
    if ($rowcheck == 1) {
        $lastadmin = "true";
        mysql_close($conn);
    } else {
        $lastadmin = "false";

        $_arvore = arvoreRevendas2();
        $arvore = $_arvore[$adminid];
        $ids_rev_arvore = array();

        if (!is_null($arvore)) {
            listaIdsRenvendasSub($arvore, $ids_rev_arvore);
        }
        //deletando as subrevendas
        if (!empty($ids_rev_arvore)) {
            $ids_sub_rev = implode(',', $ids_rev_arvore);
            mysql_query("DELETE FROM cmum_limite_logins_profiles WHERE id_revenda IN ({$ids_sub_rev})") or sqlerror();
            mysql_query("DELETE FROM cmum_udb WHERE addedby IN ({$ids_sub_rev})") or sqlerror();
            mysql_query("DELETE FROM cmum_admins WHERE id IN ({$ids_sub_rev})") or sqlerror();
        }
        //deletando a revenda
        mysql_query("DELETE FROM cmum_limite_logins_profiles WHERE id_revenda = '{$adminid}'") or sqlerror();
        mysql_query("DELETE FROM cmum_udb WHERE addedby = '{$adminid}'") or sqlerror();
        mysql_query("DELETE FROM cmum_admins WHERE id='{$adminid}'") or sqlerror();
        mysql_close($conn);


        $status = "<div class='alert alert-success'>Revenda " . $username . " Deletado com sucesso.</div>";
    }
    //$_GET['buscadmin'] = $username;
}

if (isset($_POST["chngusername"]) and $_POST["chngusername"] == true) {
    //header("Location: editadminname.php?id=" . $_POST["adminid"]);
    $status = '<div class="alert alert-success">Login admin/revenda atualizado com sucesso</div>';
}


if (isset($_GET["action"]) and $_GET["action"] == "quickenable" and $_GET["aid"] <> "") {


    $adminid = $_GET["aid"];

    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
    mysql_select_db($dbname, $conn);


    //Desativando subrevendas e logins
    $_arvore = arvoreRevendas2();

    $arvore = isset($_arvore[$adminid]) ? $_arvore[$adminid] : null;

    $ids_rev_arvore = array();

    if (!is_null($arvore)) {

        listaIdsRenvendasSub($arvore, $ids_rev_arvore);
    }

    if (!empty($ids_rev_arvore)) {

        $ids_sub_rev = implode(',', $ids_rev_arvore);

        mysql_query("UPDATE cmum_admins SET enabled='true',id_rev_mudou_status='0' WHERE id IN ({$ids_sub_rev}) AND id_rev_mudou_status='{$_SESSION['adminid']}'") or sqlerror();
        mysql_query("UPDATE cmum_udb SET enabled='true',id_rev_mudou_status='0' WHERE addedby IN ({$ids_sub_rev}) AND id_rev_mudou_status='{$_SESSION['adminid']}'") or sqlerror();
    
                
    }


    mysql_query("UPDATE cmum_admins SET enabled='true',id_rev_mudou_status='0' WHERE id='{$adminid}' AND id_rev_mudou_status='{$_SESSION['adminid']}'") or sqlerror(); // Desativa o revenda atual
    mysql_query("UPDATE cmum_udb SET enabled='true',id_rev_mudou_status='0' WHERE addedby = '{$adminid}' AND expiredate > NOW() AND id_rev_mudou_status='{$_SESSION['adminid']}'") or sqlerror(); // Logins


    mysql_close($conn);
}

if (isset($_GET["action"]) and $_GET["action"] == "quickdisable" and $_GET["aid"] <> "") {


    $adminid = $_GET["aid"];

    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
    mysql_select_db($dbname, $conn);

    //Desativando subrevendas e logins
    $_arvore = arvoreRevendas2();

    $arvore = isset($_arvore[$adminid]) ? $_arvore[$adminid] : null;

    $ids_rev_arvore = array();

    if (!is_null($arvore)) {
        listaIdsRenvendasSub($arvore, $ids_rev_arvore);
    }

    if (!empty($ids_rev_arvore)) {

        $ids_sub_rev = implode(',', $ids_rev_arvore);

        mysql_query("UPDATE cmum_admins SET enabled='false',id_rev_mudou_status='{$_SESSION['adminid']}' WHERE id IN ({$ids_sub_rev})") or sqlerror();
        mysql_query("UPDATE cmum_udb SET enabled='false',id_rev_mudou_status='{$_SESSION['adminid']}' WHERE addedby IN ({$ids_sub_rev})") or sqlerror();
    }

    mysql_query("UPDATE cmum_admins SET enabled='false',id_rev_mudou_status='{$_SESSION['adminid']}' WHERE id='{$adminid}'") or sqlerror();
    mysql_query("UPDATE cmum_udb SET enabled='false',id_rev_mudou_status='{$_SESSION['adminid']}' WHERE addedby = '{$adminid}'") or sqlerror();
   
    mysql_close($conn);
}
?>
<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"/>
            <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
            <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
            <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

            <link rel="stylesheet" href="/resources/demos/style.css" />
            <script>
                $(function () {
                    $("#expiredate").datepicker({
                        dateFormat: "yy-mm-dd <?php echo date("H:i:s"); ?>"
                                /* showOn: "button",
                                 buttonImage: "images/calendar/calendar.gif",
                                 buttonImageOnly: true*/
                    });
                });
            </script>
            <!--<link href="css/calendar.css" type="text/css" media="screen" rel="stylesheet">
            <script type="text/javascript" src="js/mootools-core.js"></script>
            <script type="text/javascript" src="js/mootools-more.js"></script>
            <script type="text/javascript" src="js/mootools-locale.js"></script>
            <script type="text/javascript" src="js/calendar.js"></script>
            <script type="text/javascript">
            window.addEvent('domready', function() {
            //new CalendarEightysix('startdate', { prefill: false, startMonday: true, toggler: 'togglestart', format: '%Y-%m-%d', hiddenInputName: 'stdate' });
            new CalendarEightysix('expiredate', { 
                prefill: false, 
                startMonday: true, 
                toggler: 'toggleexpire', 
                format: '%Y-%m-%d <?php echo date('H:i:s'); ?>', 
                hiddenInputName: 'exdate' });
            });
            </script>-->
    </head>

    <body <?php
    if ($adminexists == "true") {
        print(" \"onLoad=\"focus();addadmin.uadmin.focus()\"");
    }
    ?>>
    <!--<table width="980" border="0" align="center" valign="top" cellpadding="0" cellspacing="0" style="border-left: 1px solid #DDDDDD; border-right: 1px solid #DDDDDD; text-align: left;">
      <tr bgcolor="#006699">
        <td height="22" colspan="6">&nbsp;</td>
      </tr>
      <tr bgcolor="#006699">
        <td width="15" bgcolor="#006699">&nbsp;</td>
        <td width="851" height="120" bgcolor="#006699"><?php //require("includes/header.php");                                     ?></td>
        <td width="15" bgcolor="#006699">&nbsp;</td>
      </tr>
      <tr bgcolor="006699">
        <td height="18">&nbsp;</td>
        <td height="18"><center><?php //require("includes/menu.php");                                     ?></center></td>
        <td height="18">&nbsp;</td>
      </tr>
        <tr bgcolor="006699">
        <td height="18">&nbsp;</td>
        <td height="18">&nbsp;</td>
        <td height="18">&nbsp;</td>
      </tr>
    </table>-->
        <?php require_once 'topo.php'; ?>
        <table width="980" height="18" border="0" align="center" valign="top" cellpadding="0" cellspacing="0" style="font-size:8pt">
            <?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 = $admId";
            $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) {
                $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><div style="font-size: 12pt">Você está em:</div><ul class="breadcrumb" style="height: 50px; line-height: 30px; padding-left:5px; font-size: 12pt "><?php echo breadcrumbs($admId) ?></ul></td>
            </tr>
            <?php if (($_SESSION["adminlevel"] == "0") || (!empty($opc_rev) && array_search("7", $opc_rev) !== false)) { ?>
                <tr>
                    <td><a href="addadmin.php" class="btn btn-info" style="text-decoration: none">+ Novo</a></td>
                </tr>
            <?php } ?>
            <tr>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>
                    <table width="980" border="0">
                        <tr>
                            <td>
                                <form name="formFiltro" id="formFiltro" method="" action="?filtro=revenda">
                                    <table>
                                        <tr>
                                            <td>Listar revendas de:</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>
                            </td>
                            <td align="right">
                                <form style="">
                                    <?php if (isset($_GET['p'])): ?>
                                        <input type="hidden" name="p" value="<?php echo $_GET['p'] ?>"/>
                                    <?php endif; ?>
                                    <table border="0" >
                                        <tr>
                                            <td>Buscar</td>
                                            <td><input type="text" name="buscadmin" class="form-control" value="<?php echo isset($_GET['buscadmin']) ? $_GET['buscadmin'] : ""; ?>"/></td>
                                            <td><input type="submit" value="IR" class="btn btn-default"/></td>
                                        </tr>                                    
                                    </table>
                                </form> 
                            </td>
                        </tr>
                    </table>
                    <table width="980px" height="18" border="0" align="center" valign="top" cellpadding="0" cellspacing="2" style="font-size: 8pt" class="table table-striped table-bordered table-condensed table-hover">
                        <thead>

                            <th>ID:</th>
                            <th>&nbsp;</th>
                            <?php if ($_SESSION["adminlevel"] == "0"): ?>
                                <th>Nivel:</th>                            
                                <th>Cadastrado Por:</th>
                            <?php endif; ?>
                            <th>Login:</th>
                            <th>Senha:</th>
                            <th>Nome:</th>
                            <th>Email:</th>
                            <th>Tipo:</th>

                            <th>Vencimento:</th>
                            <th>Valor Por Login:</th>
                            <th colspan="3">&nbsp;</th>


                        </thead>
                        <?php
                        $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
                        mysql_select_db($dbname, $conn);
//$sql = mysql_query("SELECT * FROM cmum_admins ORDER BY id ASC") or sqlerror();
                        $SQL = "SELECT *,DATE_FORMAT(expiredate,'%d/%m/%Y %H:%i:%s') as expiredate_br,"
                                . "(SELECT username FROM cmum_admins as B WHERE B.id = A.addedby) as admin "
                                . "FROM cmum_admins as A WHERE 1=1";
//ORDER BY id ASC
                        if ($_SESSION['adminlevel'] != "0" && !isset($param["id"]) && !isset($_GET['filtro_rev'])) {
                            $SQL .= " AND (addedby = '{$admId}' OR id = '{$admId}')";
                        }
                        if (isset($param["id"]) or isset($_GET['filtro_rev'])) {
                            $SQL .= " AND addedby = '{$admId}'";
                        }
                        if (isset($_GET['buscadmin']) && $_GET['buscadmin'] != "") {
                            $_GET['buscadmin'] = trim($_GET['buscadmin']);
                            $SQL .= " AND (username LIKE '%{$_GET['buscadmin']}%' OR email LIKE '%{$_GET['buscadmin']}%' OR realname LIKE '%{$_GET['buscadmin']}%')";
                        }
                        $SQL .= " ORDER BY id DESC";
                        $rs = mysql_query($SQL) or die(mysql_error());

                        /* if ($admLevel == 1) {
                          $sql = mysql_query("SELECT *,DATE_FORMAT(expiredate,'%d/%m/%Y %H:%i:%s') as expiredate_br,(SELECT username FROM cmum_admins as B WHERE B.id = A.addedby) as admin FROM cmum_admins as A WHERE addedby='{$_SESSION["adminid"]}' OR id = '{$_SESSION["adminid"]}' ORDER BY id ASC") or sqlerror();
                          if (isset($_GET['buscadmin']) && $_GET['buscadmin'] != "") {
                          $sql = mysql_query("SELECT *,DATE_FORMAT(expiredate,'%d/%m/%Y %H:%i:%s') as expiredate_br,(SELECT username FROM cmum_admins as B WHERE B.id = A.addedby) as admin FROM cmum_admins as A WHERE username LIKE '%{$_GET['buscadmin']}%' AND (addedby='{$_SESSION["adminid"]}' OR id = '{$_SESSION["adminid"]}') ORDER BY id ASC") or sqlerror();
                          }
                          } */
                        if (mysql_num_rows($rs) > 0) {
                            while ($line = mysql_fetch_array($rs)) {

                                $admlevel = "";

                                if ($_SESSION['adminlevel'] != "0") {

                                    if (array_search("6", $opc_rev) !== false && $_SESSION['adminid'] != $line["id"]) {

                                        if ($line["enabled"] == "true") {

                                            $enableline = "<div id=\"piclink\"><a href=\"admins.php?action=quickdisable&aid=" . $line["id"] . "\" title=\"Habilitado (Click para Desabilitar)\" style='text-decoration: none'><span class='label label-success'>Ativado</span></a></div>";
                                        } else {

                                            $enableline = "<div id=\"piclink\"><a href=\"admins.php?action=quickenable&aid=" . $line["id"] . "\" title=\"Desabilitado (Click para Habilitar)\" style='text-decoration: none'><span class='label label-danger'>Desativado</span></a></div>";
                                        }
                                    } else {

                                        if ($line["enabled"] == "true") {

                                            $enableline = "<div id=\"piclink\"><span class='label label-success'>Ativado</span></div>";
                                        } else {

                                            $enableline = "<div id=\"piclink\"><span class='label label-danger'>Desativado</span></div>";
                                        }
                                    }
                                } else {
                                    if ($line["enabled"] == "true") {
                                        $enableline = "<div id=\"piclink\"><a href=\"admins.php?action=quickdisable&aid=" . $line["id"] . "\" title=\"" . $line["username"] . " Habilitado (Click para Desabilitar)\" style='text-decoration: none'><span class='label label-success'>Ativado</span></a></div>";
                                    } else {
                                        $enableline = "<div id=\"piclink\"><a href=\"admins.php?action=quickenable&aid=" . $line["id"] . "\" title=\"" . $line["username"] . " Desabilitado (Click para Habilitar)\" style='text-decoration: none'><span class='label label-danger'>Desativado</span></a></div>";
                                    }
                                }

                                if ($line["level"] == "0") {
                                    $admlevel = "Admin";
                                }
                                if ($line["level"] == "1") {
                                    $admlevel = "Revendedor";
                                }
                                $senha = dpt($line["password"], $s);
                                print('<tr>');
                                $exclamation = "";
                                $aux1 = explode("-", $line["expiredate"]);
                                $aux2 = explode(" ", $aux1[2]);
                                $hoje = time();
                                //var_dump($aux2);
                                $expira = mktime(23, 59, 59, $aux1[1], $aux2[0], $aux1[0]);
                                if ($hoje > $expira) {
                                    $exclamation = "<img src='images/exclamation.png' alt='Vencido' title='Vencido' style='vertical-align: middle;'/>";
                                }

                                //exibindo info pre pago

                                $rev_pre = "";

                                if ($line['rev_pre'] == '1') {
                                    $rev_pre = '<span class="label label-warning">PrePago</span>';
                                }

                                print('<td>' . $line["id"] . '</td>');
                                print("<td >" . $enableline . "</td>");

                                if ($_SESSION["adminlevel"] == "0") {

                                    print("<td >" . $line["hierarquia"] . "</td>");
                                    print("<td >" . $line["admin"] . "</td>");
                                }

                                print("<td >" . $line["username"] . " " . $rev_pre . "</td>");
                                print("<td >" . $senha . "</td>");
                                print("<td >" . $line["realname"] . "</td>");
                                print("<td >" . $line["email"] . "</td>");
                                print("<td >" . $admlevel . "</td>");

                                print("<td >" . $line["expiredate_br"] . " {$exclamation}</td>");
                                
                                print("<td >R$ " . $line["valor_cob_login"] . "</td>");
                                
                                $pedit = base64_encode("{\"id\":{$line["id"]},\"aid\":{$line["addedby"]}}");
                                $pdel = $pedit;
                                //print("<td colspan=\"3\ ><span id=\"piclink\"><a href=\"editadmin.php?p=" . $pedit . "\"><img src=\"images/edit.png\" title=\"Edit admin\"></a></span>");
                                print("<td colspan=\"3\ ><span id=\"piclink\"><a href=\"addadmin.php?p=" . $pedit . "\"><img src=\"images/edit.png\" title=\"Edit admin\"></a></span>");
                                if ($_SESSION["adminlevel"] != "0") {
                                    if ($_SESSION["adminid"] != $line['id']) {
                                        print("<span id=\"piclink\"><a href=\"deladmin.php?p=" . $pdel . "\"><img src=\"images/delete.png\" title=\"Delete admin\"></a></span>");
                                    }
                                    print("&nbsp;<span ><a href='tools.php?impuser=true&id={$line['id']}' >Importar Logins</a></span>");
                                } else {
                                    if ($_SESSION["adminid"] != $line['id']) {
                                        print("<span id=\"piclink\"><a href=\"deladmin.php?p=" . $pdel . "\"><img src=\"images/delete.png\" title=\"Delete admin\"></a></span>");
                                    }
                                    print("&nbsp;<span ><a href='tools.php?impuser=true&id={$line['id']}' >Importar Logins</a></span>");
                                    if ($_SESSION['adminlevel'] == "0") {
                                        print("&nbsp;|&nbsp;<span ><a href='tools.php?expuser=true&id={$line['id']}' >Exportar Logins</a></span>");
                                    }
                                }
                                print("</td>");
                                print("</tr>");
                            }
                        } else {
                            echo "<tr>";
                            echo "<td colspan='11' align='center'>Não existem resultados</td>";
                            echo "<tr/>";
                        }

                        mysql_close($conn);
                        ?>
                    </table>
                    </table>
                    <?php
                    require("includes/footer.php");
                    ?>
                    </body>
                    </html>
