<?php session_start(); ?>
<?php

require("config.php");
require("includes/debug.php");
require("includes/functions.php");
require_once('includes/recaptchalib.php');

if (isset($_POST['logar']) && $_POST['logar'] == "Logar como revenda") {// Logando como revenda
    if ($_POST['token_sessao'] != $_SESSION['token_acesso']) {
        header("Location: index.php?error=5");
        exit();
    }
    $loginuser = preg_replace("/[^A-Za-z0-9]/", "", $_POST["loginuser"]);
    $loginpass = $_POST["loginpass"];
    $loginuser = addslashes($loginuser);
    $loginpass = addslashes($loginpass);
//$loginpass = sha1($loginpass);
    $loginpass = ept($loginpass, $s);
    $agora = date('Y-m-d H:i:s');

    $privatekey = "6LfZO-ISAAAAADxSo9I-gMA7yylH9XqS4iyAM44C";
    $resp = recaptcha_check_answer($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);

    if (!isset($loginuser) || !isset($loginpass)) {
        header("Location: index.php?error=2");
    } elseif (empty($loginuser) || empty($loginpass)) {
        header("Location: index.php?error=2");
        /* } elseif (!$resp->is_valid || $_POST["recaptcha_response_field"] == "") {
          header("Location: index.php?error=5"); */
    } else {
        
        $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
        mysql_select_db($dbname, $conn);
        
        $sql = mysql_query("SELECT * FROM cmum_settings WHERE id='1'");
        $line = mysql_fetch_array($sql);
        
        $logfailedlogins = $line["logfailedlogins"];
        $sql = mysql_query("SELECT *,DATE_FORMAT(expiredate,'%d/%m/%Y %H:%i:%s') as expiredate_br FROM cmum_admins WHERE username='{$loginuser}' AND password='{$loginpass}'");
        $rowcheck = mysql_num_rows($sql);
        $line = mysql_fetch_assoc($sql);
        
        
        if ($rowcheck == 1) {

            $time_agora = time();
            $time_venc = strtotime($line['expiredate']);
            if ($time_agora > $time_venc) {
                session_unset();
                session_destroy();
                header("Location: index.php?error=4&s");
                exit();
            }
            if ($line["enabled"] === "false") {
                session_unset();
                session_destroy();
                header("Location: index.php?error=3");
                exit();
            }
            $h = $line['hierarquia'];
            $_arvore[$h] = $line;

            while ($h > 1) {
                $SQL = "SELECT id,username,hierarquia,addedby,enabled,expiredate FROM cmum_admins WHERE id='{$line['addedby']}'";
                $rs = mysql_query($SQL);
                $line = mysql_fetch_assoc($rs);
                $h = $line['hierarquia'];
                $_arvore[$h] = $arvore;
                $time_venc = strtotime($line['expiredate']);
                //echo "<pre>";
                //var_dump($arvore);
                //echo "</pre>";
                if ($time_agora > $time_venc) {
                    session_unset();
                    session_destroy();
                    header("Location: index.php?error=4");
                    exit();
                }
                if ($line["enabled"] == "false") {
                    session_unset();
                    session_destroy();
                    header("Location: index.php?error=3");
                    exit();
                }
            }
            foreach ($_arvore as $primeiro_user) {
                $line = $primeiro_user;
                $sqlsrvname = mysql_query("SELECT * FROM cmum_settings WHERE id='1'");
                $lineinfo = mysql_fetch_array($sqlsrvname);
                mysql_close($conn);
                $_SESSION["loginuser"] = $loginuser;
                $_SESSION["adminid"] = $line["id"];
                $_SESSION["adminlevel"] = $line["level"];
                $_SESSION["admin_pai"] = $line['addedby'];
                $_SESSION["_expiredate"] = $line["expiredate_br"];
                $_SESSION["srvname"] = $lineinfo["servername"];
                $_SESSION["sessiontimeout"] = $lineinfo["sessiontimeout"];
                $_SESSION["srvbasename"] = $_SERVER["SERVER_NAME"];
                $_SESSION['PASTARAIZ'] = getenv('PASTARAIZ');
                $_SESSION["_profiles_pm"] = $line["profiles_pm"];
                $_SESSION["_opcoes_rev"] = $line["opcoes_rev"];
                $_SESSION["_opcoes_log"] = $line["opcoes_log"];
                $_SESSION["_hierarquia"] = $line["hierarquia"];
                $_SESSION["_indt_rev"] = $line["indt_rev"];
                $_SESSION["_modelo_padrao_rev"] = $line["id_modelo_padrao"];
                $_SESSION["_modelo_padrao_sistema"] = $lineinfo["id_modelo_padrao"];
                $_SESSION["capt_val"] = 'sim';
                $_SESSION["_qtd_logins"] = $line['qtd_logins'];
                $_SESSION['rev_pre'] = $line['rev_pre'];
                //$_SESSION["active"] = create_function('$a,$b', 'echo $a + $b');
                $_SESSION["_tempo_login_teste"] = $lineinfo["tempo_login_teste"]; 
                //"a:2:{i:0;s:1:"1";i:1;s:1:"5";}" 
                $qtd_logins_perfis = array();
                if ($line["level"] == "1") {
                    $id_perfis = unserialize($line["profiles_pm"]);

                    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
                    mysql_select_db($dbname, $conn);
                    $SQL = "SELECT * FROM cmum_limite_logins_profiles WHERE id_revenda='{$line["id"]}'";
                    $rs = mysql_query($SQL);
                    while ($row = \mysql_fetch_assoc($rs)) {
                        $qtd_logins_perfis[$row['id_profiles']] = $row['quantidade'];
                    }
                }
                $_SESSION['_qtd_logins_perfis'] = $qtd_logins_perfis;
                //var_dump($qtd_logins_perfis);
                //exit();




                if (isset($_SESSION["adminid"])) {
                    header("Location: home.php");
                    exit();
                }
                exit();
            }


        } else {
            //var_dump($sql);
            //exit($_SERVER["REMOTE_ADDR"]);
            if ($logfailedlogins == "1") {
                $logdate = date("Y-m-d");
                $logtime = date("H:i:s");
                $logip = $_SERVER["REMOTE_ADDR"];
                $loghost = gethostbyaddr($_SERVER["REMOTE_ADDR"]);
                $loguser = $loginuser;
                $logpass = $loginpass;
                mysql_query("INSERT INTO cmum_failedlogins (date,time,ip,hostname,username,password) VALUES ('" . $logdate . "','" . $logtime . "','" . $logip . "','" . $loghost . "','" . $loguser . "','" . $logpass . "')");
            }
            mysql_close($conn);
            session_start();
            session_unset();
            session_destroy();
            header("Location: index.php?error=1");
            
            //var_dump($rowcheck);
            
        }
    }
} elseif (isset($_POST['logar']) && $_POST['logar'] == "Logar como cliente") {
    if ($_POST['token_sessao'] != $_SESSION['token_acesso']) {
        exit();
    }
    $login = preg_replace("/[^A-Za-z0-9_\.]/", "", $_POST["loginuser"]);
    $senha = addslashes($_POST["loginpass"]);



    //$privatekey = "6LfZO-ISAAAAADxSo9I-gMA7yylH9XqS4iyAM44C";
    //$resp = recaptcha_check_answer($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);

    if (is_null($login) || $login == "" || is_null($senha) || $senha == "") {
        header("Location: areacliente.php?error=6");
        exit();
    }
    /* } elseif (!$resp->is_valid || $_POST["recaptcha_response_field"] == "") {
      header("Location: index.php?error=5");
      } */
    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
    mysql_select_db($dbname, $conn);
    $SQL = "SELECT id,name,displayname,profiles,maxconnections,enabled,startdate,expiredate,addedby,valor_cob FROM cmum_udb WHERE name='{$login}' AND password='{$senha}'";
    $rs = mysql_query($SQL);
    if (is_resource($rs) && mysql_num_rows($rs) > 0) {
        $linha_cliente = mysql_fetch_assoc($rs);
        //var_dump($linha_cliente);
        if ($linha_cliente['enabled'] == 'false') {
            header("Location: areacliente.php?error=8");
            exit();
        }
        /*
         * array(10) {
          ["id"]=>
          string(1) "8"
          ["name"]=>
          string(4) "az22"
          ["displayname"]=>
          string(4) "az22"
          ["profiles"]=>
          string(18) "a:1:{i:0;s:1:"1";}"
          ["maxconnections"]=>
          string(1) "3"
          ["enabled"]=>
          string(4) "true"
          ["startdate"]=>
          string(10) "2014-06-20"
          ["expiredate"]=>
          string(19) "2014-07-31 23:59:59"
          ["addedby"]=>
          string(3) "364"
          ["valor_cob"]=>
          string(5) "35.00"
          }
         */
        $_SESSION['cl_id'] = $linha_cliente['id'];
        $_SESSION['cl_login'] = $linha_cliente['name'];
        $_SESSION['cl_nome'] = $linha_cliente['displayname'];
        $_SESSION['cl_perfil'] = $linha_cliente['profiles'];
        $_SESSION['cl_num_conexoes'] = $linha_cliente['maxconnections'];
        $_SESSION['cl_data_inicio'] = $linha_cliente['startdate'];
        $_SESSION['cl_vencimento'] = $linha_cliente['expiredate'];
        $_SESSION['cl_id_revenda'] = $linha_cliente['addedby'];
        $_SESSION['cl_valor_cobrado'] = $linha_cliente['valor_cob'];

        header("Location: cliente.php");
        exit();
    } else {
        header("Location: areacliente.php?error=7");
        exit();
    }
}
?>