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

//var_dump($_SESSION);



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

if (is_null($pf_pm)) {

    $pf_pm = array();
}

$opc_rev = unserialize($_SESSION["_opcoes_rev"]);

$opc_log = unserialize($_SESSION["_opcoes_log"]);

if (is_null($opc_rev)) {

    $opc_rev = array();
}
if (is_null($opc_log)) {

    $opc_log = array();
}

$qtd_logins_perfis = $_SESSION['_qtd_logins_perfis'];


if ($_SESSION['adminlevel'] != "0" && (empty($opc_rev) || array_search("7", $opc_rev) === false) && !isset($_GET['p']) && !isset($_GET['add'])) {

    exit('Erro: Voce nao tem permissao para cadastrar revendas');
}
?>
<?php
if (isset($_GET['p'])) {
    $param = json_decode(base64_decode($_GET['p']), TRUE); //array(2) { ["id"]=> int(1) ["aid"]=> int(0) }
    //$_SESSION['adminid'] 
    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
    mysql_select_db($dbname, $conn);
    $SQL = "SELECT * FROM cmum_admins WHERE id='{$param['id']}'";
    $rs = mysql_query($SQL);
    if (is_resource($rs)) {
        $edt_adm = mysql_fetch_assoc($rs);
        if ($_SESSION['adminlevel'] != "0" && ($_SESSION['adminid'] != $edt_adm['addedby']) && $edt_adm['id'] != $_SESSION['adminid']) {
            exit('Erro: A pagina nao pode ser carregada');
        }
        $edt_adm['expiredate_br'] = date("d/m/Y H:i:s", strtotime($edt_adm['expiredate']));
        $edt_adm['senha_enc'] = dpt($edt_adm['password'], $s);
        $pf_pm_edt = ($edt_adm['profiles_pm'] != "") ? unserialize($edt_adm['profiles_pm']) : null;
        $opc_rev_edt = ($edt_adm['opcoes_rev'] != "") ? unserialize($edt_adm['opcoes_rev']) : null;
        $opc_log_edt = ($edt_adm['opcoes_log'] != "") ? unserialize($edt_adm['opcoes_log']) : null;
        //pegando a quantidade por perfis
        $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
        mysql_select_db($dbname, $conn);
        $SQL = "SELECT id_profiles,quantidade FROM cmum_limite_logins_profiles WHERE id_revenda='{$param['id']}'";
        $rs = mysql_query($SQL);
        $edt_qtd_perf = array();
        while ($row = mysql_fetch_assoc($rs)) {
            $edt_qtd_perf[$row["id_profiles"]] = $row["quantidade"];
        }
    }
}
if (isset($_GET['add'])) {
    //Validando Valores Vazios
    //exit(var_dump($_POST));

    $ret['erro'] = "";

    foreach ($_POST as $c => $v) {
        if (($_SESSION['adminid'] == $_POST['_id'])) {

            if ($v == "" && $ret['erro'] == "" && ($c != "_indt")) {
                $ret['erro'] = 'Um ou mais campos nao foram preenchidos..';
                echo json_encode($ret);
                exit();
            }
        } else {
            if ($v == "" && $ret['erro'] == "" && ($c != "_indt")) {
                $ret['erro'] = 'Um ou mais campos nao foram preenchidos..';
                echo json_encode($ret);
                exit();
            }
        }
    }
    //Validando Login
    if (strlen($_POST['_login']) < 4) {

        $ret['erro'] = 'O Login e menor que o valor permitido';
        unset($ret['sucesso']);
        echo json_encode($ret);
        exit();
    } elseif (strlen($_POST['_login']) > 15) {

        $ret['erro'] = 'O Login e maior que o valor permitido';
        echo json_encode($ret);
        exit();
    } else {

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

        $SQL = "SELECT id,username FROM cmum_admins WHERE username='{$_POST['_login']}'";

        $rs_um_login = mysql_query($SQL);

        $um_login = mysql_fetch_assoc($rs_um_login);

        if (isset($um_login['id']) && $um_login['id'] != $_POST['_id']) {

            $ret['erro'] = 'Este login nao pode ser cadastrado escolha outro';
            echo json_encode($ret);
            exit();
        }
    }

    $ilegal_login = "#$%^&*()+=-[]';,./{}|:<>?~";
    //$legal_senha = "#$%^&*()+=-[]';,./{}|:<>?~";

    if (strpbrk($_POST['_login'], $ilegal_login) !== false) {
        $ret['erro'] = 'Existem caracteres nao permitidos no campo login';
        echo json_encode($ret);
        exit();
    }
    //Validando Senha
    if (strlen($_POST['_senha']) < 3) {
        $ret['erro'] = 'A Senha e menor que o valor permitido';
        echo json_encode($ret);
        exit();
    }
    if (strlen($_POST['_senha']) > 15) {
        $ret['erro'] = 'A Senha e maior que o valor permitido';
        echo json_encode($ret);
        exit();
    }
    /* if (strpbrk($_POST['_senha'], $ilegal_senha) !== false) {
      $ret['erro'] = 'Existem caracteres nao permitidos no campo senha';
      echo json_encode($ret);
      exit();
      } */
    //Validando nome
    if (strpbrk($_POST['_nome'], $ilegal) !== false) {
        $ret['erro'] = 'Existem caracteres nao permitidos no campo nome';
        echo json_encode($ret);
        exit();
    }
    //Validando Email
    if (!filter_input(INPUT_POST, '_email', FILTER_VALIDATE_EMAIL)) {
        $ret['erro'] = 'Escolha um email valido';
        echo json_encode($ret);
        exit();
    }
    //Validando Perfis
    if (!isset($_POST['_perfis'])) {

        $ret['erro'] = 'Nenhum perfil foi selecionado';

        echo json_encode($ret);

        exit();
    }

    $qtd_logins = $_POST['_qtd_logins'];

    // revenda ignora verificação de quantidade

    if ($_POST['_rev_pre'] == "0") {

        if ($_POST['_id'] > 0) {

            $saldo_logins = saldo_revenda2($_SESSION['adminid'], $_POST['_id']);
        } else {

            $saldo_logins = saldo_revenda2($_SESSION['adminid']);
        }

        if ($_SESSION['adminlevel'] == "1" && ($saldo_logins <= 0 || ($saldo_logins < $qtd_logins && $_SESSION['adminid'] != $_POST['_id']))) {

            $ret['erro'] = 'Voce excedeu o saldo de logins';

            echo json_encode($ret);

            exit();
        }
    }

    $_qtd_perfis = json_decode(stripslashes($_POST["_qtd_perfis"]), true);

    $qtd_perfis = array();

    //Inserindo no banco de dados

    $agora = date('Y-m-d');
    $vencimento = date('Y-m-d H:i:s', strtotime(str_replace("/", "-", $_POST['_expiredate'])));
    $profiles_pm = serialize($_POST['_perfis']);
    $opcoes_rev = isset($_POST['_opcoes_rev']) ? serialize($_POST['_opcoes_rev']) : "";
    $opcoes_log = isset($_POST['_opcoes_log']) ? serialize($_POST['_opcoes_log']) : "";
    $hierarquia = "0";
    $senha_enc = ept($_POST['_senha'], $s);

    if ($_SESSION['adminlevel'] != "0" || (isset($_POST['_tipo']) && $_POST['_tipo'] != "0")) {

        $hierarquia = $_SESSION['_hierarquia'] + 1;
    }
    $nivel = ($_SESSION['adminlevel'] != "0") ? "1" : $_POST['_tipo'];

    if ($_POST['_id'] == "0") {

        $SQL = "INSERT INTO cmum_admins (id,"
                . "username,"
                . "password,"
                . "realname,"
                . "indt_rev,"
                . "email,"
                . "enabled,"
                . "level,"
                . "hierarquia,"
                . "addedby,"
                . "added,"
                . "expiredate,"
                . "profiles_pm,"
                . "opcoes_rev,"
                . "opcoes_log,"
                . "id_rev_mudou_status,"
                . "qtd_logins,"
                . "rev_pre,"
                . "valor_cob_login) VALUES('null',"
                . "'{$_POST['_login']}',"
                . "'{$senha_enc}',"
                . "'{$_POST['_nome']}',"
                . "'{$_POST['_indt']}',"
                . "'{$_POST['_email']}',"
                . "'{$_POST['_status']}',"
                . "'{$nivel}',"
                . "'{$hierarquia}',"
                . "'{$_SESSION['adminid']}',"
                . "'{$agora}',"
                . "'{$vencimento}',"
                . "'{$profiles_pm}',"
                . "'{$opcoes_rev}',"
                . "'{$opcoes_log}',"
                . "'1',"
                . "'{$qtd_logins}',"
                . "'{$_POST['_rev_pre']}',"
                . "{$_POST['_valor_cob_login']})";
    } else {
        /*
          1	Pode alterar login
          2	Pode alterar senha
          3	Pode alterar nome
          4	Pode alterar email
          5	Pode alterar vencimento
          6	Pode alterar status
          7	Pode adicionar revendas
          8	Pode excluir revendas
         * 
         *          */
        $id_rev_mudou_status = false;

        if ($_POST['_status'] == 'true') {

            $id_rev_mudou_status = 0;
        }

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

            //exit(var_dump('ATT REV',$_POST));

            $SQL = "UPDATE cmum_admins SET ";

            if ((array_search("1", $opc_rev) !== false) && $_SESSION['adminid'] != $_POST['_id']) {

                $SQL .= "username='{$_POST['_login']}',";
            }
            if (array_search("2", $opc_rev) !== false) {

                $SQL .= "password='{$senha_enc}',";
            }
            if (array_search("3", $opc_rev) !== false) {

                $SQL .= "realname='{$_POST['_nome']}',";
            }
            if (array_search("4", $opc_rev) !== false && $_SESSION['adminid'] != $_POST['_id']) {

                $SQL .= "email='{$_POST['_email']}',";
            }
            if (array_search("5", $opc_rev) !== false && $_SESSION['adminid'] != $_POST['_id']) {

                $SQL .= "expiredate='{$vencimento}',";
            }

            if (($_SESSION['adminid'] != $_POST['_id'])) {// se a revenda não editando ela.
                $SQL .= "enabled='{$_POST['_status']}',"
                        . "qtd_logins='{$qtd_logins}',"
                        . "profiles_pm='{$profiles_pm}',"
                        . "opcoes_rev='{$opcoes_rev}',"
                        . "opcoes_log='{$opcoes_log}'";
            } else {

                $SQL = substr($SQL, 0, -1);
            }

            $SQL.= " WHERE id='{$_POST['_id']}'";
        } else {

            //exit(var_dump('ATT ADM',$_POST));

            $SQL = "UPDATE cmum_admins SET username='{$_POST['_login']}',"
                    . "password='{$senha_enc}',"
                    . "realname='{$_POST['_nome']}',"
                    . "indt_rev='{$_POST['_indt']}',"
                    . "email='{$_POST['_email']}',"
                    . "enabled='{$_POST['_status']}',"
                    . "level='{$nivel}',"
                    . "expiredate='{$vencimento}',"
                    . "id_rev_mudou_status='{$id_rev_mudou_status}',"
                    . "qtd_logins='{$qtd_logins}',"
                    . "rev_pre='{$_POST['_rev_pre']}',"
                    . "valor_cob_login='{$_POST['_valor_cob_login']}',";

            if (($_SESSION['adminid'] != $_POST['_id'])) {

                $SQL .= "profiles_pm='{$profiles_pm}',"
                        . "opcoes_rev='{$opcoes_rev}',"
                        . "opcoes_log='{$opcoes_log}'";
            } else {

                $SQL = substr($SQL, 0, -1);
            }

            $SQL.= " WHERE id='{$_POST['_id']}'";
        }
    }

    //var_dump($qtd_logins);exit();

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

    $rs_sav_rev = mysql_query($SQL);

    $id_rev_ins = mysql_insert_id($conn);

    if ($_POST['_id'] != "0") {

        $id_rev_ins = $_POST['_id'];
    } else {

        cria_cota_rev_pre($id_rev_ins);
    }

    if ($rs_sav_rev === TRUE) {
        //<--- removidos --->
        unset($ret['erro']);

        $ret['sucesso'] = "Dados salvos com sucesso.";

        //*** verifica se existe saldo disponivel ***//

        echo json_encode($ret);

        exit();
    }

    exit('Erro ao gravar no banco de dados' . mysql_error() . ' -- ' . $SQL);
}
?>
<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); ?> - Cadastrar Admins e Revendedores</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>        
        <script>
            $(function () {

                $("#expiredate").datepicker({
                    dateFormat: "dd/mm/yy 23:59:59"

                });

            });
        </script>
        <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>        
    </head>
    <body>
        <?php require_once 'topo.php'; ?>
        <div style="width: 450px; margin: auto">
            <div style="border: solid 0px red">
                <h4 style="line-height: 45px">Salvar Admins e Revendedores</h4> 
            </div>        
            <hr/>
            <div class="alert alert-danger div-erro" style="display: none">Erro</div>
            <form role="form" class="form-horizontal" method="post" id="form-add-adm">
                <input type="hidden" name="id_adm" id="id_adm" value="<?php echo isset($edt_adm['id']) ? $edt_adm['id'] : "0" ?>"/>
                <input type="hidden" name="is_new" id="is_new" value="<?= isset($edt_adm['id']) ? '0' : '1'; ?>"/>
                <div class="form-group">
                    <label for="login" class="col-sm-2 control-label" >Login</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="login" nome="login" value="<?php echo isset($edt_adm['username']) ? $edt_adm['username'] : "" ?>" placeholder="Login de acesso..." <?php if ($_SESSION['adminlevel'] != "0" && array_search("1", $opc_rev) === false && isset($edt_adm)): ?>disabled<?php endif; ?>/>
                    </div>
                </div>
                <div class="form-group">
                    <label for="login" class="col-sm-2 control-label">Senha</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="senha" nome="senha" value="<?php echo isset($edt_adm['senha_enc']) ? $edt_adm['senha_enc'] : "" ?>" placeholder="Senha de acesso..." <?php if ($_SESSION['adminlevel'] != "0" && array_search("2", $opc_rev) === false && isset($edt_adm)): ?>disabled<?php endif; ?>/>
                    </div>
                </div>
                <div class="form-group">
                    <label for="nome" class="col-sm-2 control-label">Nome</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="nome" name="nome" value="<?php echo isset($edt_adm['realname']) ? $edt_adm['realname'] : "" ?>" placeholder="Nome do Revendedor" <?php if ($_SESSION['adminlevel'] != "0" && array_search("3", $opc_rev) === false && isset($edt_adm)): ?>disabled<?php endif; ?>/>
                    </div>
                </div>
                <?php if ($_SESSION['adminlevel'] == "0") { ?>
                    <div class="form-group">
                        <label for="indt" class="col-sm-2 control-label">INDT:</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="indt" name="indt" value="<?php echo isset($edt_adm['indt_rev']) ? $edt_adm['indt_rev'] : "" ?>" placeholder="Prefixo para Revenda" <?php if ($_SESSION['adminlevel'] != "0" && array_search("3", $opc_rev) === false): ?>disabled<?php endif; ?>/>
                        </div>
                    </div>
                <?php } ?>
                <div class="form-group">
                    <label for="email" class="col-sm-2 control-label">Email</label>
                    <div class="col-sm-10">
                        <input type="email" class="form-control" id="email" name="email" value="<?php echo isset($edt_adm['email']) ? $edt_adm['email'] : "" ?>" placeholder="Email do Revendedor" <?php if ($_SESSION['adminlevel'] != "0" && array_search("4", $opc_rev) === false && isset($edt_adm)): ?>disabled<?php endif; ?>/>
                    </div>
                </div> 
                <?php if ($_SESSION['adminlevel'] == "0") { ?>
                    <div class="form-group">

                        <label for="tipo" class="col-sm-2 control-label">Tipo</label>

                        <div class="col-sm-5">

                            <select name="tipo" id="tipo" class="form-control">

                                <option value="0" <?php if (isset($edt_adm) && $edt_adm['level'] == "0") echo "selected"; ?>>Administrador</option>

                                <option value="1" <?php if (isset($edt_adm) && $edt_adm['level'] == "1") echo "selected"; ?>>Revendedor</option>

                            </select>

                        </div>

                    </div> 
                <?php } ?>
                <div class="form-group">
                    <label for="venc" class="col-sm-2 control-label">Venc.</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" name="expiredate" id="expiredate" value="<?php echo isset($edt_adm['expiredate_br']) ? $edt_adm['expiredate_br'] : "" ?>" placeholder="Vencimento"<?php if ($_SESSION['adminlevel'] != "0" && array_search("5", $opc_rev) === false && isset($edt_adm) || ($_SESSION['adminlevel'] == "1" && (isset($edt_adm) && $edt_adm['id'] == $_SESSION['adminid']))): ?>disabled<?php endif; ?>/>
                    </div>
                </div> 
                <div class="form-group">
                    <label for="status" class="col-sm-2 control-label">Status</label>
                    <div class="col-sm-5">
                        <select name="status" id="status" class="form-control" <?php if ($_SESSION['adminlevel'] != "0" && array_search("6", $opc_rev) === false && isset($edt_adm)): ?>disabled<?php endif; ?>>
                            <option value="true" <?php if (isset($edt_adm) && $edt_adm['enabled'] == "true") echo "selected"; ?>>Ativado</option>
                            <option value="false" <?php if (isset($edt_adm) && $edt_adm['enabled'] == "false") echo "selected"; ?>>Desativado</option>
                        </select>
                    </div>
                </div> <!-- divi status-->
                <div class="form-group" <?php if ($_SESSION['adminlevel'] == "1") { ?>style="visibility: hidden" <?php } ?>>
                    <label class="col-sm-2 control-label">Revenda PrePaga ?&nbsp;</label><div class="col-sm-5"><input type="checkbox" name="rev_pre" id="rev_pre" <?php if ((isset($edt_adm['rev_pre']) && $edt_adm['rev_pre'] == '1') || $_SESSION['rev_pre'] == '1') { ?>checked<?php } ?>/></div>
                </div>

                <div class="col-sm-offset-2" id="div-mostra-planos" style="display: none"></div>

                <?php if ($_SESSION['rev_pre'] == "0" || $_SESSION['adminlevel'] == "0"): ?>

                    <div class="form-group" id="div-qtd-logins">
                        <label for="venc" class="col-sm-2 control-label">Qtd Logins.</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="qtd_logins" id="qtd_logins" value="<?php echo isset($edt_adm['qtd_logins']) ? $edt_adm['qtd_logins'] : "" ?>" placeholder="Quantidade Logins"<?php if ($_SESSION['adminlevel'] != "0" && array_search("5", $opc_rev) === false && isset($edt_adm) || ($_SESSION['adminlevel'] == "1" && (isset($edt_adm) && $edt_adm['id'] == $_SESSION['adminid']))): ?>disabled<?php endif; ?>/>
                        </div>
                    </div> 
                    <div class="form-group" id="div-valor-cob-logins">
                        <label for="valor_cab_login" class="col-sm-2 control-label">Valor cobrado por login.</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="valor_cab_login" id="valor_cab_login" value="<?php echo isset($edt_adm['valor_cob_login']) ? $edt_adm['valor_cob_login'] : "" ?>" placeholder="Valor cobrado por login"<?php if ($_SESSION['adminlevel'] != "0" && array_search("5", $opc_rev) === false && isset($edt_adm) || ($_SESSION['adminlevel'] == "1" && (isset($edt_adm) && $edt_adm['id'] == $_SESSION['adminid']))): ?>disabled<?php endif; ?>/>
                        </div>
                    </div>

                <?php endif; ?>


                <h6>Perfis Permitidos</h6>
                <?php
//Listando todos os perfis
//$conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
//mysql_select_db($dbname, $conn);
                $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
                $SQL = "SELECT id,name FROM cmum_profiles";
                if ($_SESSION['adminlevel'] != "0") {
                    $ids_pf = implode(',', $pf_pm);
                    $SQL .= " WHERE id IN({$ids_pf})";
                }
//var_dump($SQL);
                $rs_pf = $conn->query($SQL);
//$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
                /*
                 * id	int(11)	Não 	 	 	 
                  id_revenda	int(11)	Não
                  id_profiles	int(11)	Não
                  quantidade
                 */

                $num_pfs = 0;
                $pf_pm = array();
                if (isset($rs_pf->num_rows) && $rs_pf->num_rows > 0) {
                    //$pf_pm = $rs_pf->fetch_all(MYSQLI_ASSOC);
                    while ($r = $rs_pf->fetch_assoc()) {
                        $pf_pm[] = $r;
                    }
                    $num_pfs = $rs_pf->num_rows;
                }
//var_dump($pf_pm);
//exit();
                ?>                
                <div class="form-group" style="border: solid 0px red">

                    <?php
                    if (isset($num_pfs) && $num_pfs > 0) {
                        $i = 0;
                        $str_perfis = '';
                        foreach ($pf_pm as $pf) {
                            $qtd_pf = "";
                            if (isset($edt_qtd_perf[$pf['id']])) {
                                $qtd_pf = $edt_qtd_perf[$pf['id']];
                            }
                            if ($i == 0 || $i % 2 == 0) {
                                if ($i > 0) {
                                    $str_perfis .= '</div>';
                                }
                                $str_perfis .= '<label class="col-sm-2 control-label"></label>';
                                $str_perfis .= '<div class="col-sm-10">';
                                $str_perfis .= '<label class="col-sm-4 checkbox-inline" style="border: solid 0px">';


                                if (isset($pf_pm_edt) && (array_search($pf['id'], $pf_pm_edt) !== false)) {
                                    $str_perfis .= '<input type="checkbox" name="perfis[]" id="perfis" class="perfis" value="' . $pf['id'] . '" checked/><span style="font-size: 8pt; font-weight:bolder;">' . $pf['name'] . '</span>';
                                } else {
                                    $str_perfis .= '<input type="checkbox" name="perfis[]" id="perfis" class="perfis" value="' . $pf['id'] . '"/><span style="font-size: 8pt; font-weight:bolder;">' . $pf['name'] . '</span>';
                                }


                                $str_perfis .= '</label>';
                                if (($i + 1) == $num_pfs) {
                                    $str_perfis .= '</div>';
                                }
                            } else {
                                $str_perfis .= '<label class="col-sm-4 checkbox-inline" style="border: solid 0px">';
                                if (isset($pf_pm_edt) && (array_search($pf['id'], $pf_pm_edt) !== false)) {
                                    $str_perfis .= '<input type="checkbox" name="perfis[]" id="perfis" class="perfis" value="' . $pf['id'] . '" checked/><span style="font-size: 8pt; font-weight:bolder;">' . $pf['name'] . '</span>';
                                } else {
                                    $str_perfis .= '<input type="checkbox" name="perfis[]" id="perfis" class="perfis" value="' . $pf['id'] . '"/><span style="font-size: 8pt; font-weight:bolder;">' . $pf['name'] . '</span>';
                                }
                                $str_perfis .= '</label>';
                                if (($i + 1) == $num_pfs) {
                                    $str_perfis .= '</div>';
                                }
                            }
                            $i++;
                        }

                        echo $str_perfis;

                        //exit();
                        ?>
                        <label for="opcoes" class="col-sm-2 control-label"></label>
                        <div class="col-sm-10">
                            <label class="checkbox-inline col-sm-4">
                                <input type="checkbox" name="sel-td-perfis" id="sel-td-perfis"/><span style="font-size: 8pt">MARCAR TODOS</span>
                            </label>
                        </div>
                    <?php } else { ?>
                        <p style="color: red">-- Nao existe perfis cadastrados</p>
                    <?php } ?>
                </div>
                <h6>Opçoes da Revenda</h6>
                <?php
//Listando Opcoes Revendas
                $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
                $SQL = "SELECT * FROM cmum_opc_rev";
                if ($_SESSION['adminlevel'] != "0") {
                    $ids_opc_rev = implode(',', $opc_rev);
                    $SQL .= " WHERE id IN({$ids_opc_rev})";
                }
                $rs_opc_rev = $conn->query($SQL);
                $opc_rev_lt = array();
                if (isset($rs_opc_rev->num_rows) && $rs_opc_rev->num_rows > 0) {
                    //$opc_rev_lt = $rs_opc_rev->fetch_all(MYSQLI_ASSOC);
                    while ($r = $rs_opc_rev->fetch_assoc()) {
                        $opc_rev_lt[] = $r;
                    }
                    $num_opc_rev_lt = $rs_opc_rev->num_rows;
                }
                ?>
                <div class="form-group">
                    <?php
                    if (isset($num_opc_rev_lt) && $num_opc_rev_lt > 0) {
                        $i = 0;
                        $str_opc_rev = '';
                        foreach ($opc_rev_lt as $opc_r) {
                            if ($i == 0 || $i % 2 == 0) {
                                if ($i > 0) {
                                    $str_opc_rev .= '</div>';
                                }
                                $str_opc_rev .= '<label class="col-sm-2 control-label"></label>';
                                $str_opc_rev .= '<div class="col-sm-10">';
                                $str_opc_rev .= '<label class="col-sm-4 checkbox-inline">';
                                if (isset($opc_rev_edt) && (array_search($opc_r['id'], $opc_rev_edt) !== false)) {
                                    $str_opc_rev .= '<input type="checkbox" name="opcoes_rev[]" id="opcoes_rev" class="opcoes_rev" value="' . $opc_r['id'] . '" checked/><span style="font-size: 8pt">' . $opc_r['nome_opc'] . '</span>';
                                } else {
                                    $str_opc_rev .= '<input type="checkbox" name="opcoes_rev[]" id="opcoes_rev" class="opcoes_rev" value="' . $opc_r['id'] . '"/><span style="font-size: 8pt">' . $opc_r['nome_opc'] . '</span>';
                                }


                                $str_opc_rev .= '</label>';
                                if (($i + 1) == $num_opc_rev_lt) {
                                    $str_opc_rev .= '</div>';
                                }
                            } else {
                                $str_opc_rev .= '<label class="col-sm-4 checkbox-inline">';
                                if (isset($opc_rev_edt) && (array_search($opc_r['id'], $opc_rev_edt) !== false)) {
                                    $str_opc_rev .= '<input type="checkbox" name="opcoes_rev[]" id="opcoes_rev" class="opcoes_rev" value="' . $opc_r['id'] . '" checked/><span style="font-size: 8pt">' . $opc_r['nome_opc'] . '</span>';
                                } else {
                                    $str_opc_rev .= '<input type="checkbox" name="opcoes_rev[]" id="opcoes_rev" class="opcoes_rev" value="' . $opc_r['id'] . '"/><span style="font-size: 8pt">' . $opc_r['nome_opc'] . '</span>';
                                }
                                $str_opc_rev .= '</label>';
                                if (($i + 1) == $num_opc_rev_lt) {
                                    $str_opc_rev .= '</div>';
                                }
                            }
                            $i++;
                        }

                        echo $str_opc_rev;

                        //exit();
                        ?>
                        <label for="opcoes" class="col-sm-2 control-label"></label>
                        <div class="col-sm-10">
                            <label class="checkbox-inline col-sm-4">
                                <input type="checkbox" name="sel-td-opc-rev" id="sel-td-opc-rev"/><span style="font-size: 8pt">MARCAR TODOS</span>
                            </label>
                        </div> 
                    <?php } else { ?>
                        <p style="color: red">-- Nao existe opcoes para selecionar</p>
                    <?php } ?>
                </div>
                <h6>Opçoes dos Logins</h6>
                <?php
//Listando Opcoes Revendas
                $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
                $SQL = "SELECT * FROM cmum_opc_log";
                if ($_SESSION['adminlevel'] != "0") {
                    $ids_opc_log = implode(',', $opc_log);
                    $SQL .= " WHERE id IN({$ids_opc_log})";
                }
                $rs_opc_log = $conn->query($SQL);
                $opc_log_lt = array();
                if (isset($rs_opc_log->num_rows) && $rs_opc_log->num_rows > 0) {
                    while ($r = $rs_opc_log->fetch_assoc()) {
                        $opc_log_lt[] = $r;
                    }
                    $num_opc_log_lt = $rs_opc_log->num_rows;
                    //$opc_log_lt = $rs_opc_log->fetch_all(MYSQLI_ASSOC);
                }



//var_dump($opc_log_lt);
                ?>
                <div class="form-group">
                    <?php
                    if (isset($num_opc_log_lt) && $num_opc_log_lt > 0) {
                        $i = 0;
                        $str_opc_log = '';
                        foreach ($opc_log_lt as $opc_l) {

                            if ($i == 0 || $i % 2 == 0) {
                                if ($i > 0) {
                                    $str_opc_log .= '</div>';
                                }
                                $str_opc_log .= '<label class="col-sm-2 control-label"></label>';
                                $str_opc_log .= '<div class="col-sm-10">';
                                $str_opc_log .= '<label class="col-sm-4 checkbox-inline">';
                                if (isset($opc_log_edt) && (array_search($opc_l['id'], $opc_log_edt) !== false)) {
                                    $str_opc_log .= '<input type="checkbox" name="opcoes_log[]" id="opcoes_log" class="opcoes_log" value="' . $opc_l['id'] . '" checked/><span style="font-size: 8pt">' . $opc_l['nome_opc'] . '</span>';
                                } else {
                                    $str_opc_log .= '<input type="checkbox" name="opcoes_log[]" id="opcoes_log" class="opcoes_log" value="' . $opc_l['id'] . '"/><span style="font-size: 8pt">' . $opc_l['nome_opc'] . '</span>';
                                }


                                $str_opc_log .= '</label>';
                                if (($i + 1) == $num_opc_log_lt) {
                                    $str_opc_log .= '</div>';
                                }
                            } else {
                                $str_opc_log .= '<label class="col-sm-4 checkbox-inline">';
                                if (isset($opc_log_edt) && (array_search($opc_l['id'], $opc_log_edt) !== false)) {
                                    $str_opc_log .= '<input type="checkbox" name="opcoes_log[]" id="opcoes_log" class="opcoes_log" value="' . $opc_l['id'] . '" checked/><span style="font-size: 8pt">' . $opc_l['nome_opc'] . '</span>';
                                } else {
                                    $str_opc_log .= '<input type="checkbox" name="opcoes_log[]" id="opcoes_log" class="opcoes_log" value="' . $opc_l['id'] . '"/><span style="font-size: 8pt">' . $opc_l['nome_opc'] . '</span>';
                                }
                                $str_opc_log .= '</label>';
                                if (($i + 1) == $num_opc_log_lt) {
                                    $str_opc_log .= '</div>';
                                }
                            }
                            $i++;
                        }

                        echo $str_opc_log;
                        //exit();
                        ?>
                        <label for="opcoes" class="col-sm-2 control-label"></label>
                        <div class="col-sm-10">
                            <label class="checkbox-inline col-sm-4">
                                <input type="checkbox" name="sel-td-opc-log" id="sel-td-opc-log"/><span style="font-size: 8pt">MARCAR TODOS</span>
                            </label>
                        </div>
                    <?php } else { ?>
                        <p style="color: red">-- Nao existe opcoes para selecionar</p>
                    <?php } ?>
                </div>                
                <hr/>
                <button class="btn btn-success" id="salv-sair">Salvar &<br/> Sair</button>&nbsp;<button class="btn btn-success" id="salv-novo">Salvar &<br/> Novo</button>
            </form>
        </div>
        <!-- Modal Ação Sucesso -->
        <div class="modal modal-acao-aguarde">
            <div class="modal-dialog modal-sm">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h4 class="modal-title">Processando solicitação..</h4>
                    </div>
                    <div class="modal-body" style="text-align: center">
                        <img src="<?= $config['base_url']; ?>/images/loading_transparent.gif" width="160px"/><br/>
                        Aguarda um pouquinho tá?... Eu faço um show pra voce enquanto espera.
                    </div>
                    <div class="modal-footer">
                        <!--<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>-->
                        <!--<button type="button" class="btn btn-primary btn-conf-sucesso">Ok</button>-->
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->
        <!-- Modal Erro -->
        <div class="modal modal-acao-erro">
            <div class="modal-dialog modal-sm">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h4 class="modal-title">Erro</h4>
                    </div>
                    <div class="modal-body body-erro">
                        Erro ao preencher..
                    </div>
                    <div class="modal-footer">
                        <!--<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>-->
                        <button type="button" class="btn btn-primary btn-conf-erro">Ok</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->
        <script>
            $(document).ready(function () {

                mostraQtd();

                setTimeout(function () {
                    $('.perfis').each(function () {
                        var v = $(this).val();
                        var estado = $(this).prop('checked');
                        $('#qtd_profile_' + v).prop('disabled', !estado);
                    });

                }, 500);

                $('.perfis').on('click', this, function () {
                    var v = $(this).val();
                    var estado = $(this).prop('checked');
                    $('#qtd_profile_' + v).prop('disabled', !estado);
                });

                function marcarTodos(s) {
                    $(s).trigger("click");
                }

                //Eventos Perfis
                $('#sel-td-perfis').on('click', this, function () {
                    //o = false;
                    //$(this).is(':checked') ? o = true : o = false;
                    marcarTodos('.perfis');
                });
                $('#sel-td-opc-rev').on('click', this, function () {
                    //o = false;
                    //$(this).is(':checked') ? o = true : o = false;
                    marcarTodos('.opcoes_rev');
                });
                $('#sel-td-opc-log').on('click', this, function () {
                    //o = false;
                    //$(this).is(':checked') ? o = true : o = false;
                    marcarTodos('.opcoes_log');
                });
                //Ação botão sucesso
                $('.btn-conf-sucesso').on('click', this, function () {
                    $('.modal-acao-sucesso').modal("hide");
                    //window.location.reload();
                });
                //Quando modal sucesso ocultar
                $('.modal-acao-sucesso').on('hidden.bs.modal', function (e) {
                    // do something...
                    var ele_ativo = window.sessionStorage.getItem("ele_ativo");
                    if (ele_ativo == 'salv-sair') {
                        window.location.href = "admins.php";
                    }
                    if (ele_ativo == 'salv-novo') {
                        window.location.href = "addadmin.php";
                    }
                    e.preventDefault();
                    //window.location.reload();
                });
                //Ação botão sucesso
                $('.btn-conf-erro').on('click', this, function () {
                    $('.modal-acao-erro').modal("hide");
                    //window.location.reload();
                });
                $('#form-add-adm').submit(function (e) {
                    
                    e.preventDefault();
                    //dados = new FormData(this);
                    //alert(dados.);
                    //alert($('#perfis:checked').val());

                    //alert($('#rev_pre').is(':checked'));
                    
                   $('.modal-acao-aguarde').modal("show");

                    var perfis = [];
                    var qtd_perfis = [];
                    var opcoes_rev = [];
                    var opcoes_log = [];
                    $.each($('.perfis:checked'), function () {
                        var v = $(this).val();
                        var qtd = $("#qtd_profile_" + v).val();
                        perfis.push(v);
                        //qtd_perfis.push({v:qtd});
                        qtd_perfis.push({_id: v, _qtd: qtd});
                    });
                    $.each($('.opcoes_rev:checked'), function () {
                        opcoes_rev.push($(this).val());
                    });
                    $.each($('.opcoes_log:checked'), function () {
                        opcoes_log.push($(this).val());
                    });
                    //alert(qtd_perfis[0]._id);
                    //console.debug(qtd_perfis);
                    $.ajax({
                        url: "addadmin.php?add=true",
                        type: "POST",
                        data: {
                            _id: $('#id_adm').val(),
                            _is_new: $('#is_new').val(),
                            _login: $('#login').val(),
                            _senha: $('#senha').val(),
                            _nome: $('#nome').val(),
                            _indt: $('#indt').val(),
                            _rev_pre: $('#rev_pre').is(':checked') ? '1' : '0',
                            _id_plano: $('#rev_pre').is(':checked') ? $('.id_plano').filter(':checked').val() : '0',
                            _status: $('#status').val(),
                            _email: $('#email').val(),
                            _tipo: $('#tipo').val(),
                            _expiredate: $('#expiredate').val(),
                            _qtd_logins: $('#rev_pre').is(':checked') ? "0" : $('#qtd_logins').val(),
                            _valor_cob_login: $('#rev_pre').is(':checked') ? "0" : $('#valor_cab_login').val(),
                            '_perfis[]': perfis,
                            '_qtd_perfis': JSON.stringify(qtd_perfis),
                            '_opcoes_rev[]': opcoes_rev,
                            '_opcoes_log[]': opcoes_log
                        },
                        dataType: 'json'
                    })
                            .done(function (r) {
                                //return false;
                                
                                $('.modal-acao-aguarde').modal("hide");
                                
                                if (r.erro) {
                                    $('.div-erro').css('display', 'none');
                                    //alert('Erro no preenchimento..');
                                    $('.body-erro').html('<div class="alert alert-danger">' + r.erro + '</div>');
                                    $('.modal-acao-erro').modal("show");
                                    $('.div-erro').html(r.erro);
                                    $('.div-erro').css('display', 'block');
                                }
                                if (r.sucesso) {
                                    //alert(r.sucesso);
                                    window.sessionStorage.setItem('ele_ativo', document.activeElement.id);
                                    //$('.modal-acao-sucesso').modal("show");

                                    setTimeout(function () {
                                        if (document.activeElement.id == 'salv-sair') {

                                            window.location.href = "admins.php";

                                        }
                                        if (document.activeElement.id == 'salv-novo') {

                                            window.location.href = "addadmin.php";

                                        }
                                    }, 500);


                                }
                            });
                });

                // carregando planos revendas pre

                $('#rev_pre').on('click', function () {
                    mostraQtd();
                });

                // mostra campo quantidade
                //div-valor-cob-logins
                function mostraQtd() {

                    var rev_pre_sel = $('#rev_pre').is(':checked') ? 1 : 0;


                    if (rev_pre_sel === 1) {

                        $('#div-mostra-planos').load('carrega_plano_revenda.php');

                        $('#div-mostra-planos').css('display', 'block');

                        var html_div_qtd_login = $('#div-qtd-logins').html();

                        var html_div_valor_cob_logins = $('#div-valor-cob-logins').html();

                        $('#div-qtd-logins').css('display', 'none');
                        $('#div-qtd-logins').html("");

                        $('#div-valor-cob-logins').css('display', 'none');
                        $('#div-valor-cob-logins').html("");

                        window.sessionStorage.setItem('html_div_qtd_login', encodeURI(html_div_qtd_login));
                        window.sessionStorage.setItem('html_div_valor_cob_logins', encodeURI(html_div_valor_cob_logins));
                        
                        window.sessionStorage.setItem('state_ck_rev_pre', '1');

                    } else {

                        var state_ck_rev_pre = window.sessionStorage.getItem('state_ck_rev_pre');
                        var html_div_qtd_login = window.sessionStorage.getItem('html_div_qtd_login');
                        var html_div_valor_cob_logins = window.sessionStorage.getItem('html_div_valor_cob_logins');

                        if (state_ck_rev_pre === '1' && html_div_qtd_login !== null && html_div_valor_cob_logins !== null) {

                            $('#div-mostra-planos').html("");

                            $('#div-mostra-planos').css('display', 'none');

                            $('#div-qtd-logins').html(decodeURI(html_div_qtd_login));
                            $('#div-qtd-logins').css('display', 'block');
                            
                             $('#div-valor-cob-logins').html(decodeURI(html_div_valor_cob_logins));
                             $('#div-valor-cob-logins').css('display', 'block');
                             

                            window.sessionStorage.setItem('state_ck_rev_pre', '0');

                        }
                    }
                }


            });
        </script>
        <?php require_once __DIR__ . '/includes/rodape.php'; ?>
