<?php

 ini_set('display_errors', 1);
 ini_set('display_startup_erros', 1);
 error_reporting(E_ALL);
if(!isset($_SESSION))
    session_start();

/* TimeZone */
date_default_timezone_set("America/Sao_Paulo");

/* Cache */
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");

/* Type */
header("Content-type: text/html; charset=UTF-8");

header("Access-Control-Allow-Origin: *");
/* Limits */
ini_set('memory_limit', '512M');
set_time_limit(300);



// IPTV UNF
define('LINK_STORE_USER', 'http://iptv01.com/includes/userlogin.php');
define('LINK_OPT_USER', 'http://iptv01.com/includes/integrationplus.php');
define('LINK_DEL_USER', 'http://iptv01.com/includes/integrationplus.php');
define('LINK_GER_M3U', 'http://painel.teambr.live/iptv/');
define('LINK_REDIR', 'http://painel.teambr.live/x/');

define('PAINEL_URL', 'http://45.162.228.250/');
define('PAINEL_USR', 'admin');
define('PAINEL_PWD', 'matrixsub123');
define('PAINEL_ID', (string) '1');
define('URL_IPTV', 'http://cdn.teambr.live/get.php?');
//SITE URL 
define('SITE_URL', 'https://cdn.teambr.live/beta/');

define('SITE_PAINEL', 'https://cdn.teambr.live/beta/');

//PAGSEGURO EMAIL & TOKEN
define('EMAIL_PAGSEGURO', 'contato@iptv01.com');
define('TOKEN_PAGSEGURO', 'F09DDF1E93334F65B61F6F256F735A9E');

// function reqCURL_local($url){
//     $ch = curl_init($url);
//     curl_setopt($ch, CURLOPT_TIMEOUT, 6);
//     curl_setopt($ch, CURLOPT_URL, $url);
//     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
//     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
//     curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:57.0) Gecko/20100101 Firefox/57.0");
//     curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//     $res = curl_exec($ch);
//     @curl_close($ch);
//     return $res;
// }
// END

// if (file_exists(__DIR__.DIRECTORY_SEPARATOR.'../env.php')) {
//     include_once(__DIR__.DIRECTORY_SEPARATOR.'../env.php');
// }

// if (!function_exists('env')) {
        
//     function env($key, $default = null)
//     {
        
//         $value = getenv($key);
//         if ($value === false) {
//             return $default;
//         }
//         return $value;
//     }
// }   

class CS
{
    // protected $ip      = '192.99.201.144:7999';
    // protected $login   = 'root';
    // protected $senha   = '@Notreve$';
    // protected $db_name = 'bd_iptv';
    
    protected $db; 
    public $con,$QueryRst,$errors,$successinfo, $total = 0;


    function __construct($die = 1)
    {            
        try {
            
            if (empty(self::$con)) {
                $this->db = parse_ini_file(__DIR__.DIRECTORY_SEPARATOR.'Lib/env.ini');

                //var_dump($this->con);
                
                //if (self::getInstance($this->db))
                if($this->con = mysqli_connect($this->db['host'], $this->db['user'], $this->db['pass'], $this->db['name'], $this->db['port'])) 
                //if($this->con = mysqli_connect($this->ip, $this->login, $this->senha, $this->db_name))
                {  
                    //var_dump($this->con);
                    $this->successinfo = mysqli_get_host_info($this->con);
                    if(!mysqli_set_charset($this->con, "utf8")) $this->errors[] = mysqli_error($this->con);
                    return true;
                }
                else
                {
                    if($die == 1)
                        die(header("HTTP/1.1 500 Internal Server Error"));

                    $this->errors[] = mysqli_connect_errno() . " : " . mysqli_connect_error();
                    throw new Exception($this->errors);
                    
                    return false;
                }
            }
        } catch (Exception $e) {
            print 'Ocorreu o erro: ' .$e->getMessage();
        }
    }

    public function getGerenciadoresVencimento($id) 
    {
        $res = 0; 
        
        $query = $this->executeQuery("SELECT id, login, email FROM gerenciadores WHERE vencimento = CURDATE() + INTERVAL 1 DAY AND gerenciador_responsavel = '{$id}'");
        if ($this->num_rows($query) > 0) {
            $res = $this->fetchQuery($query);
        } 

        return $res;
    }

    public function recaptcha() 
    {
        $json = [];
        $respon = $_POST['captcha'];
        $data   = ['secret' => $this->data['google_secret'], 'response' => $respon];

        $options = array(
            'http' => array(
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'method'  => 'POST',
                'content' => http_build_query($data)

            )
        );

        $context = stream_context_create($options);
        $result  = file_get_contents($this->data['google_url'], false, $context);
        $json    = json_decode($result);

        return $json;
    }

    public function getGerenciadorSub($id, $rows = []) {

        
        $rows_g = $this->executeQuery("SELECT * FROM gerenciadores WHERE gerenciador_responsavel = '{$id}'");
        
        if ($this->num_rows($rows_g) > 0) {
             
            $rows_g = $this->fetchQuery($rows_g);

            foreach ($rows_g as $key => $row) {

                $users = $this->executeQuery("SELECT count(*) as ativos FROM usuarios WHERE id_gerenciador = '{$row['id']}' AND status = 'normal' AND TIMESTAMP(vencimento) > CURRENT_TIMESTAMP()");
                 
                if ($this->num_rows($users) > 0) {
                    
                    if (!in_array($row['id'], $rows)) {
                        array_push($rows, $row['id']);
                    }
                }  
                
                //var_dump($rows['ativos']);  
                $this->getGerenciadorSub($row['id'], $rows);
            }
        } 

        

        return $rows;
    }

    public function getManagers($id) 
    {
            
        $query = "SELECT id, gerenciador_responsavel FROM gerenciadores WHERE gerenciador_responsavel = '{$id}' GROUP BY id";
        
        $query = $this->executeQuery($query);
        
        if ($this->num_rows($query)  > 0) { 
            return $this->fetchQuery($query);
        }
    }

    public function getPai($id) 
    {
     
        $data  = $this->getManagers($id);           
          
        if (!is_null($data) AND count($data) > 0) {
            foreach ($data as $key => $value) {
                if (isset($value['id']) AND !empty($value['id'])) {
                    if (isset($value['id']) AND !in_array($value['id'], $_SESSION['gerenciadores'])) {
                        $_SESSION['gerenciadores'][] = (int) $value['id'];
                    }

                    if (isset($value['id']) AND !in_array($value['gerenciador_responsavel'], $_SESSION['gerenciadores'])) {
                        $_SESSION['gerenciadores'][] = (int) $value['gerenciador_responsavel'];
                    }
                    
                    $this->getPai($value['id']);                                  
                }           
            }       
        }    
    }

    public function updateAtivos() 
    {
        $rows = $this->executeQuery("SELECT * FROM gerenciadores WHERE id NOT IN(1,1010101010)");
        
        $rows = $this->fetchQuery($rows);

        foreach ($rows as $key => $row) {
               
            $_SESSION['gerenciadores'] = [ (int) $row['id'] ];
            
            $this->getPai($row['id']);
        
            $gerenciadores = implode(',', $_SESSION['gerenciadores']);

            $ativos = $this->executeQuery("SELECT count(*) as ativos FROM usuarios WHERE id_gerenciador IN($gerenciadores) AND status = 'normal' AND TIMESTAMP(vencimento) > CURRENT_TIMESTAMP()");
            
            $ativos = $this->fetchQuery($ativos);

            if ($row['ativos'] != $ativos[0]['ativos']) {
            
                // Descomentar o update para atualizar o total de usuarios ativos dos gerenciadores                
                $this->executeQuery("UPDATE gerenciadores SET ativos = '{$ativos[0]['ativos']}' WHERE id = '{$row['id']}' "); 
            }        
        }
    }

    public function isLimitUsers($value) 
    {
        return (int) $value <= $this->num_rows($this->executeQuery("SELECT * from usuarios WHERE id_gerenciador = '{$_SESSION['info_unf']['id']}'"));
    }

    public function isLimitManagers($value) 
    {
        return (int) $value <= $this->num_rows($this->executeQuery("SELECT * from gerenciadores WHERE gerenciador_responsavel = '{$_SESSION['info_unf']['id']}'"));
    }

    public function setErrors($errors) 
    {
        $this->errors[] = $errors;
    }

    public function createUsuario($request) 
    {
        //var_dump($request); exit; 
        $profile_id = json_encode([(int) $request['profile_id']]);
        
        $xtream = "CALL xtream_create('1', '{$request['login']}', '{$request['senha']}', '".strtotime($request['vencimento'])."', '{$request['obs']}', '{$request['notas']}', '{$profile_id}','{$request['is_trial']}', '{$request['max_con']}')";
        
        $xtream = $this->executeQuery($xtream);

        if ($this->num_rows($xtream) == 0) {
            throw new Exception("Usuario existente");
        } 

        $xtream  = $this->fetchQuery($xtream)[0];
        
        $this->con->next_result();

        $iptv = "CALL sp_user_create('{$request['id']}', '{$request['login']}', '{$request['nome']}', '{$request['senha']}', '{$request['status']}','{$request['vencimento']}', '{$request['email']}', '{$request['obs']}', '{$request['profile']}', '{$request['max_con']}','{$request['id_gerenciador']}','{$request['iptv_url']}','{$xtream['id']}','{$request['celular']}')";
        
        $iptv = $this->executeQuery($iptv);
            
        if ($this->num_rows($iptv) == 0) {
            throw new Exception("Usuario existente");
        }
        
        return $this->fetchQuery($iptv)[0];        
    }

    public function saveApi($request) 
    {
          
        $Mpegtv = new Mpegtv();      
        
        $this->updateUsuario($request);

        $result = $Mpegtv->setEndpoint('api.php?action=user&sub=edit')->edit($request['params']); 
    }

    public function updateUsuario($request) 
    {
           
        // caso a variavel $request['id'] nao seja um array vou concatenar com " = '107'", ficando assim " id = '107'"
        $where = " id = '{$request['params']['id']}'";
        
        // Abaixo um exemplo dos parametros recebidos
        // array(9) {
        //   ["display_name"]=>
        //   string(17) "Erlan Carreira Ja"
        //   ["senha"]=>
        //   string(6) "vrfeej"
        //   ["email"]=>
        //   string(25) "erlancarreira@hotmail.com"
        //   ["celular"]=>
        //   string(11) "85966633333"
        //   ["profile"]=>
        //   string(5) "SD_HD"
        //   ["max_con"]=>
        //   string(1) "1"
        //   ["observacao"]=>
        //   string(21) "Cadastro IPTV - TESTE"
        //   ["vencimento"]=>
        //   string(19) "2019-11-20 00:00:00"
        //   ["status"]=>
        //   string(6) "normal"
        // }

        // Aqui eu percorro os parametros, repare que os parametros tem os mesmos nomes dos campos do banco de dados
        foreach ($request['params'] as $key => $value) {
            // Se a chave existe ou seja aquela referencia está definida $key
            // Ex: display_name
            // Se o valor não está vazio $value
            // Erlan Carreira Ja
            // Eu entro no IF e seto chave e valor 
            // Armazenando na variavel $params[] | Ex: display_name = 'Fulano'
            if (isset($key) AND !empty($value) AND !in_array($key,['id'])) {
                $params[] = "$key = '{$value}'";
            }
        }

        // Lembra que a variavel $params recebeu um array com chaves e valores
        // Então, a função implode precisa receber um array no segundo parametro, dessa forma você transforma os dados em uma única string       
        $params = implode(',', $params);
        // string(233) "display_name = 'Erlan Carreira Ja',senha = 'vrfeej',email = 'erlancarreira@hotmail.com',celular = '85966633333',profile = 'SD_HD',max_con = '1',observacao = 'Cadastro IPTV - TESTE',vencimento = '2019-11-20 00:00:00',status = 'normal'"
        
        $query = $this->executeQuery("UPDATE 
                    usuarios 
                SET 
                    $params 
                WHERE 
                    $where"
        );

        
        if ($this->num_rows($query) == 1) {
            
            throw new Exception('Problema ao atualizar o usuario!');            
        
        } else {   

            return $request;
        }
    }

    public static function dateDiff ($dateStart, $dateEnd) {
        
        // Return the number of days between the two dates:    
        return round(abs(strtotime($dateStart) - strtotime($dateEnd))/86400);

    } // end function dateDiff


    public static function isAdmin($ids = null) {
        $ids = (is_null($ids)) ? [1,1010101010] : $ids;
        return in_array($_SESSION['info_unf']['id'], $ids); 
    }

    public function passwordValid($password) {

        return preg_match('/[a-zA-Z0-9\W]{8,}$/', $password);
    }
        
    public function emailAllowed($email) 
    {   
        
        $permission = include("permission.php");   

        // strrpos($email, '@') 
        // Encontra a posicao da ultima ocorrencia de um caractere em uma string 
        // meuemail@hotmail.com --- Resultado = 8

        // strrpos($email, '@') + 1)
        // Pego o total de letras 
        // Ex: meuemail 8 letras + 1 = 9 (meuemail@) 
        
        //substr ($email, 0, strpos($email, '@'))
        // Pega o email 
        // Ex: email@hotmail.com no inicio 0 ate o 4 totalizando em 5 caracteres = email 

        $emailProvider = substr($email, strrpos($email, '@') + 1);
 
        $emailName = substr($email, 0, strpos($email, '@'));     

        //Comparo com a lista de emails permitidos e se o email nao ta na lista negra
        if (in_array($emailProvider, $permission['providers']) && !$this->searchString($emailName, $permission['wordsNotAllowed'])) {
            
            return false; 
        }       
         
        
        return true;
        
    }

    public function getManager($login) {
         
        $query = $this->executeQuery("SELECT g.id, g.login, a.timeout, a.attempts from gerenciadores g left join authenticator a on a.user_id = g.id WHERE g.login = '{$login}'");

        return ($this->num_rows($query) > 0) ? $this->fetchQuery($query)[0] : []; 
    }

    public function getListUrl($login, $senha, $urlLink = "http://iptv01.com/x/") {
        
       if ($this->num_rows($this->executeQuery("SELECT id FROM usuarios WHERE login = '$login'")) > 0) {
            
            return '';
        }

        $link = $this->gerarLink("http://s1.iptvcs.eu:80/get.php?username=".urlencode($login)."&password=".urlencode($senha)."&type=m3u_plus&output=mpegts");

        return $urlLink.$link;
        
    }

    public function checkConn($value) {
        
        return (isset($_SESSION['info_unf']['id']) AND $_SESSION['info_unf']['id'] != 1 || !isset($value) || empty($value)) ? false : true; 
    }

    public function isUserExists($value) {
        
        //var_dump($this->num_rows($this->executeQuery("SELECT id FROM usuarios WHERE email = '$email' OR celular = '$celular' OR login = '$login'"))); exit;
        return (int) $this->num_rows($this->executeQuery("SELECT id FROM usuarios WHERE email = '$value' OR celular = '$value' OR login = '$value'"));
       
    }

    public function getVencimentoByDayTime(int $hourOne, string $dayOne, int $hourTwo, string $dayTwo) {
        
        // if (date('H') >= $hourOne && date('l') == $dayOne || date('H') >= $hourTwo && date('l') == $dayTwo) {
        //     return new DateTime('Y-m-d H:i:s', strtotime('+6 hours'));
        // } 

        return new DateTime('Y-m-d H:i:s', strtotime('+8 hours'));
            
    }

    public function searchString($string, $words, $result = false) {
        //$String Nome do email que vai ser comparado 
        //$Words  Array com lista de palavras      
        foreach ($words as $key => $value) {
            
            $pos = strpos($string, $value);
            
            if ($pos !== false) { 
                
                $result = true; 
                break; 
            }
        } 

        return $result;
    }

    //Funcao responsavel pelo envio do SMS  
    public function QueryString($sms, $celular)  {
        //distribuindo a informação a ser enviada
        $queryString = [
            'user' => 'rafaelcosta',
            'password' => '*inter1515',
            //para sms normal = type=0
            'type' => 1,
            'number' => $celular,  
            'content'=> $sms                  
        ];

        return reqCURL_local("https://xpi.smsmarket.com.br/webservice-rest/send-single?".http_build_query($queryString));
        
    }
	
	    //Funcao responsavel pelo envio do SMS FLASH
    public function SmsFlash($sms, $celular)  {
        //distribuindo a informação a ser enviada
        $queryString = [
            'user' => 'rafaelcosta',
            'password' => '*inter1515',
            'type' => 1,
            'number' => $celular,  
            'content'=> $sms                  
        ];

        return reqCURL_local("https://xpi.smsmarket.com.br/webservice-rest/send-single?".http_build_query($queryString));
        
    }
	
	public function sendEmailUser($cod, $idUser, $lista = array()){
		$sql = "select
		a.*, b.*
		from
		emails_mensagens a
		join emails_smtp b ON b.id = a.id_email_smtp
		where
		a.email_tipo = '$cod'";
		$q = $this->executeQuery($sql);
        if($this->num_rows($q) == 1){			
			$reg = $this->fetchQuery($q)[0];
			$hostSender = $reg['host'];
			$portaSender = $reg['porta'];
			$server_emailSender = $reg['user'];
			$server_senhaSender = $reg['pass'];
			$server_emailSender_session = $reg['user'];
			$EMPRESA = 'SpaceIPTV';
			$sqlUser = $this->executeQuery("SELECT usuarios.*, profiles.profile_str
			FROM usuarios
			JOIN profiles ON profiles.profile = usuarios.profile
			WHERE usuarios.id = " . $idUser);
			$regUser = $this->fetchQuery($sqlUser)[0];
			
			$arrayMsg = array('[NOME_USUARIO]', '[NOME_PROFILE]', '[DATA_VENCIMENTO]', '[URL_LISTA]', '[USUARIO_LOGIN]', '[USUARIO_SENHA]');
			$arrayUser = array($regUser['display_name'], $regUser['profile_str'], date('d/m/Y', strtotime($regUser['vencimento'])), $regUser['iptv_url_lista'], $regUser['login'], $regUser['senha']);

            if(!empty($lista)) {
                array_push($arrayMsg, '[TOTAL_LISTAS_ATIVAS]', '[VALOR_TOTAL_POR_LISTA]');
                array_push($arrayUser, $lista['totalListasAtivas'], $lista['valorPorListaAtiva']);
            }
			
			$mensagem = str_replace($arrayMsg, $arrayUser, $reg['mensagem']);
			$assunto = str_replace($arrayMsg, $arrayUser, $reg['assunto']);
			
			$mail = new PHPMailer();
			$mail->IsSMTP();
			$mail->Host = $hostSender;
			$mail->SMTPAuth = true;
			$mail->SMTPSecure = 'tls';
			$mail->Port = '587';
			$mail->Username = $server_emailSender;
			$mail->Password = $server_senhaSender;
            //$mail->From = $server_emailSender_session;
            $mail->From = 'contato@listaiptv.vip';
            $mail->FromName = $EMPRESA;
            $mail->AddAddress('contato@listaiptv.vip', 'Space Code');
			$mail->AddAddress($regUser['email'], $regUser['display_name']);
			//$mail->WordWrap = 100;
			$mail->IsHTML(true);
			$msg = utf8_decode($mensagem);
			// $mail->AddAttachment("propostas/$DATA_CRIACAO$ID.pdf", "$DATA_CRIACAO$ID.pdf");
			# $mail->AddReplyTo($emailSession, utf8_decode($nomeSession)); 
			$mail->Subject = $assunto;
			$mail->Body = $msg;
            $result = $mail->Send();
            $mail->clearAddresses(); 
        }

        if($result) {    
            return true;
        } else {
            echo $mail->ErrorInfo;
            return false;
        }	
	}

    
    //Retorna apenas numeros 
    public function returnNumbers($value) {
        
        $tam = [10,11,14,15,16,17];
        
        if(in_array(strlen($value), $tam)) {
            return preg_replace("/[^0-9]/", "", $value);
        }

        return false;
    }

    public function profileExists($profile) {
        return $this->num_rows($this->executeQuery("SELECT * from profiles WHERE profile = '$profile'"));
    }

    public function checkLog_unf()
    {
        if(isset($_SESSION['logado_unf']) && !empty($_SESSION['info_unf'])){
            return true;
        }else{
            return false;
        }
    }

    public function checkLog_adm()
    {
        if(isset($_SESSION['logado_adm']) && !empty($_SESSION['info_adm']))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public function onlyLevel($permitir = 'buscar_usuarios')
    {
        global $_SESSION;

        $permissoes=explode(";",$_SESSION['info_adm']['permissoes']);

        if(in_array("root", $permissoes))
        {
            return true;
        }
        else
        {
            return in_array($permitir,$permissoes);
        }
        return false;
    }

    function insert_log_adm($login_adm,$acao,$detalhes)
    {
        $this->executeQuery("INSERT into admins_log(login_adm,acao,detalhes,data_hora,ip) VALUES ('$login_adm', '".$this->filterKey($acao)."', '".$this->filterKey($detalhes)."', '".date('Y-m-d H:i:s')."', '".$_SERVER['REMOTE_ADDR']."');");
    }

   function insert_log_unf($login_adm,$acao,$detalhes)
    {
        $this->executeQuery("INSERT into gerenciador_log(login_gen,acao,detalhes,data_hora,ip) VALUES ('$login_adm', '".$this->filterKey($acao)."', '".$this->filterKey($detalhes)."', '".date('Y-m-d H:i:s')."', '".$_SERVER['REMOTE_ADDR']."');");
    }

    public function filterKey($value, $SQL = 1, $HTML = 1, $NUMERIC=0, $REGEXP = 0)
    {
        if($SQL == 1)
        {
            if(!is_array($value)) {
                $value = addslashes($value);
            }
        }
        if($HTML == 1)
        {
            $value = str_replace("&", "&amp;", $value);
            $value = str_replace('"', '&quot;', $value);
            $value = str_replace("'", '&#039;', $value);
            $value = str_replace('<', '&lt;', $value);
            $value = str_replace('>', '&gt;', $value);
        }
        elseif($HTML == 2)
            $value = strip_tags($value);
        elseif($HTML == 3)
            $value = htmlentities($value);

        if($REGEXP == 1)
        {
            if($SQL == 0)
            {
                $value = addslashes($value);
            }
            $value = str_replace("?", "\\?", $value);
            $value = str_replace("#", "\\#", $value);
            $value = str_replace("[", "\\[", $value);
            $value = str_replace("]", "\\]", $value);
            $value = str_replace("*", "\\*", $value);
            $value = str_replace("+", "\\+", $value);
            $value = str_replace(".", "\\.", $value);
            $value = str_replace("^", "\\^", $value);
            $value = str_replace("(", "\\(", $value);
            $value = str_replace(")", "\\)", $value);
            $value = str_replace('$', "\\\$", $value);
            $value = str_replace("&", "\\&", $value);
            $value = str_replace("|", "\\|", $value);
            $value = str_replace("%", "\\%", $value);
        }
        if($NUMERIC)
        {
            $temp = 0;
            preg_match('/[0-9]+/i',$value,$temp);
            $value = $temp[0];
        }

        return $value;
    }

    public function executeQuery($query, $debug = 1)
    {
        
        if($this -> QueryRst = mysqli_query($this -> con, $query))
        {
            return $this->QueryRst;
        }
        else
        {
            /*if($debug)
            {
                $qry_tmp = $this->filterKey($query);
                $qry_f = __FILE__ . " . " . $_SERVER['SCRIPT_FILENAME'];
                $error = $this->filterKey(mysqli_error($this->con));
                $request = $this->filterKey(print_r($_REQUEST,1));
                $session = $this->filterKey(print_r($_SESSION,1));

                $this->executeQuery("INSERT into sql_error(error_s,error_f,error_q,request,session) VALUES (
                    '$error', '$qry_f', '$qry_tmp', '$request', '$session');", 0);
            }*/
            $this->errors[] = mysqli_error($this->con);
            return false;
        }
    }

    public function fetchQuery($query, $loop = 1, $close = 1)
    {
        
        $temp = Array();
        if(is_object($query) && $query)
        {
            if($loop)
            {
                while($row = mysqli_fetch_assoc($query))
                {
                    $temp[] = $row;
                }
            }
            else
            {
                $temp[] = mysqli_fetch_array($query);
            }
            if($close)
                mysqli_free_result($query);
        }
        return $temp;
    }

    public function getLastId() 
    {
        return mysqli_insert_id($this->con);
    }

    public function fetch($query)
    {
        return mysqli_fetch_object($query);
    }


    public function fetchObj($query, $loop = 1, $close = 1)
    {
        $temp = Array();
        if(is_object($query) && $query)
        {
            if($loop)
            {
                while($row = mysqli_fetch_object($query))
                {
                    $temp[] = $row;
                }
            }
            else
            {
                $temp[] = mysqli_fetch_object($query);
            }
            if($close)
                mysqli_free_result($query);
        }
        return $temp;
    }

    public function num_rows($query, $close = 0)
    {
        if(is_object($query)&&$query)
        {
            return mysqli_num_rows($query);
            if($close == 1) mysqli_free_result($query);
        }
        else
        {
            return false;
        }
    }

    public function setToken() {
        
        return md5(uniqid(rand(), true));
    }
	
	public function checkLoginUser($login, $senha)
    {
		
		$login = mysqli_real_escape_string($this->con, $login);
		$senha = mysqli_real_escape_string($this->con, $senha);
		
        $q = $this->executeQuery("SELECT * from usuarios WHERE login = '".$this->filterKey($login)."' AND senha = '".$this->filterKey($senha)."'");
        
        if($this->num_rows($q) == 1)
        { 
			//$this->executeQuery("UPDATE authenticator set token = '".$this->getToken()."' WHERE login = '".$this->filterKey($login)."' ");
            $_SESSION['usuario_logado'] = $this->fetchQuery($q);
            return $_SESSION['usuario_logado'];
        }
    }

    public function setTokenGerenciador($user_id) {
          
        $this->executeQuery("CALL sp_autheticator($user_id, '".$this->setToken()."', '".$_SERVER["REMOTE_ADDR"]."')");
    }

    public function checkToken() {
        
        $q = $this->executeQuery("SELECT * from authenticator WHERE user_id = ".$_SESSION['info_unf']['id']." ");
        
        if($this->num_rows($q) == 1)
        { 
            return true;
        }

        return false;
    }

    // public function checkGerenciador() {

    //     $login = mysqli_real_escape_string($this->con, $login);
    //     $senha = mysqli_real_escape_string($this->con, $senha);
        
    //     $q = $this->executeQuery("SELECT * from usuarios WHERE login = '".$this->filterKey($login)."' AND senha = '".$this->filterKey($senha)."'");
        
    //     if($this->num_rows($q) == 1)
    //     { 
    //         $this->executeQuery("CALL sp_authenticator('".$this->filterKey($login)."', '".$this->getToken()."')");
            
    //     }
    // }
	
	public function Class_cURL($method = 'GET', $url = '', $header = Array(), $post_data = null){
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:57.0) Gecko/20100101 Firefox/57.0');
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		if(!is_null($post_data)){
		  curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		}
		$res = curl_exec($ch);
		echo $url . " / " . $res."<BR>";
		echo curl_error($ch);
		return $res;
	}
	
	public function Class_editarLogin($login, $senha, $exp_date = 0, $max_con = 1, $bouquet_ids = 10){
		global $erroE;
		if($exp_date <= 0) $exp_date = date('Y-m-d');
		$exp_date = strtotime($exp_date);
		$bouquet_ids = array($bouquet_ids);
		$post_data = array(
		  'username' => $login,
		  'password' => $senha,
		  'member_id' => PAINEL_ID,
		  'admin_notes' => $admin_notes,
		  'user_data' => array(
			'username' => $login,
			'password' => $senha,
			'member_id' => PAINEL_ID,
			'exp_date' => $exp_date,
			'bouquet' => json_encode( $bouquet_ids )
		  ),
		  'max_connections' => (string) $max_con
		);
		$res = $this->Class_cURL("POST", PAINEL_URL . "api.php?action=user&sub=edit", Array(), http_build_query($post_data));
		$res = json_decode($res, true);
		if($res['result'] == true){
			return $res;
		}else{
			$erroE = $res;
			return false;
		}
	}
	
	public function updateCustomerIPTV($idUser){
		
		$q = $this->executeQuery("SELECT
		a.*, b.id_bouq, c.login as login_gerenciador
		FROM
		usuarios a
		JOIN profiles b ON b.profile = a.profile
		JOIN gerenciadores c ON c.id = a.id_gerenciador
		WHERE a.id = " . $idUser);
        if($this->num_rows($q) == 1)
        {
			$r = $this->fetchQuery($q)[0];
            $e = $this->Class_editarLogin($r['login_gerenciador'].'_'.$r['login'], $r['senha'], $r['vencimento'], $r['max_con'], $r['id_bouq']);
			return $e;
        }
		
	}

    //xtualiza os planos 
    public function updatePlanoIPTV($idUser) {
        $q = $this->executeQuery("
        SELECT
        u.*, 
        p.id_bouq, 
        g.login as login_gerenciador
        FROM
        usuarios u
        JOIN planos p ON p.nome = u.profile
        JOIN gerenciadores g ON g.id = u.id_gerenciador
        WHERE u.id = $idUser");
        if($this->num_rows($q) == 1)
        {
            $r = $this->fetchQuery($q)[0];
            $e = $this->Class_editarLogin($r['login_gerenciador'].'_'.$r['login'], $r['senha'], $r['vencimento'], $r['max_con'], $r['id_bouq']);
            return $e;
        } 
    }
	
	public function addCharge($array = array()){
		if($array && count($array) > 0){
			$set = '';
			foreach($array as $k => $v){
				$set .= ", {$k} = '{$v}'";
			}
			$this->executeQuery("INSERT INTO pagamentos SET " . substr($set,1));
			return mysqli_insert_id($this->con);
		}
	}

    public function addChargeBoleto($array = array()){
        if($array && count($array) > 0){
            $set = '';
            foreach($array as $k => $v){
                $set .= ", {$k} = '{$v}'";
            }
            $this->executeQuery("INSERT INTO pagamentos_boleto SET " . substr($set,1));
            return mysqli_insert_id($this->con);
        }
    }
	
	public function editCharge($id, $array = array()){
		if($array && count($array) > 0 && $id > 0){
			$set = '';
			foreach($array as $k => $v){
				$set .= ", {$k} = '{$v}'";
			}
			$this->executeQuery("UPDATE pagamentos SET " . substr($set,1) . " WHERE id = $id");
		}
	}

    public function getPlanos() {
        
        return $this->fetchObj($this->executeQuery("SELECT id, nome, descricao, tipo, tipo_nome, plano_tipo, valor from planos"));

    }

    // public function mountData($id) {
    //     $data = [];
        
    //     $query = $this->executeQuery("CALL sp_getGerenciadoresFilhos($id)");
        
    //     if($this->num_rows($query) > 0) {

    //         $query = $this->fetchQuery($query); 
            
    //         foreach ($query as $value) {

    //             $data[] = $value;

    //             if (count($this->getGerenciadorData($value['id'])) > 0) {

    //                 $data[]['data'] = $this->getGerenciadorData($value['id']);
    //             }
    //         }            
    //     } 

    //     return $data;             
    // }

    public function getTotalUsers($id) 
    {
        $query = "SELECT count(*) as total FROM usuarios WHERE id_gerenciador = $id AND status = 'normal' AND TIMESTAMP(vencimento) > CURRENT_TIMESTAMP()";
        
        $query = $this->executeQuery($query);
        
        if ($this->num_rows($query) > 0)
        {
            return $this->fetchQuery($query)[0]['total'];
        } 

        return 0;
    }

    public function setTotalUsers($total = 0) {
        $this->total = $total; 
    }

    public function getTotalU() {
        
        return $this->total;
    }

    public function recursiveG($data, &$list_total = 0) {
        
        
        // Total de usuarios do gerenciador    
        $totalUsersManager = $this->getTotalUsers($data[0]['pai_id']);

        //var_dump($totalUsersManager); exit;
        
        $html  = "<ul>";
        $html .= "<li data-total='{{lista}}'><b style='text-transform: uppercase;'>Gerenciador responsavel: {{pai}}";
        $html .= (isset($data[0])) ? " - <b style='text-transform: uppercase;'>Total de gerenciadores filhos:</b> {{total}}" : '';
        $html .= " - <b style='text-transform: uppercase;'>Total de usuarios: </b> {{lista}}";  
        $html = str_replace(['{{lista}}','{{total}}', '{{pai}}', '{{login}}'], [$totalUsersManager, $data[0]['total'], $data[0]['pai']], $html);
        
              
       
        //$html .= " - <b style='text-transform: uppercase;'>Lista ativas com subs:</b> {{listas_subs}}";
        $html .= "</li></b>";
        
        $html .= "<ol>";
        
        //$data['totalUsuarios'] += $total;
        //$total_lista = $total;
        
        $soma = 0;
        foreach ($data as $value) {
            
            if (isset($value['id'])) {
                
                // Total de usuarios do subgerenciador
                $total = $this->getTotalUsers($value['id']);
                
                //Soma o total de usuarios
                $soma += $total;

                //Total de usuarios do gerenciador pai com filho
                //$totalChildrsManager += $totalUsersManager;

                
                $html .= "<li data-total='{{total}}'>";    
                $html .= "ID: {{id}} - NOME: {{login}} - TOTAL_USUARIOS: {{total}}"; 
                $html .= "</li>";
                $html = str_replace(['{{total}}', '{{id}}', '{{login}}'], [$total, $value['id'], $value['login']], $html);

                
                
            }  

            if (isset($value['data']) && count($value['data']) > 0) {
                

                $html .= $this->recursiveG($value['data'], $total);
            }  


        } 

        $totalUsersManager += $soma;

        //var_dump($soma);

        $this->setTotalUsers($totalUsersManager);

        
         
        $html .= "</ol>";   
        $html .= "</ul>";
        $html = str_replace(['{{listas_ativas}}'], [$this->getTotalU()], $html);

        //var_dump($data['total_usuarios']); exit;
        if (count($data) > 0) {
            return $html;
        }
    }
	
	public function getProfiles($id = 0, $array = array())
    {
		$Where = 'valor > 0';
		if($array && count($array) > 0){
			foreach($array as $k => $v){
				$$k = mysqli_real_escape_string($this->con, $v);
				$Where .= " AND ({$k} = '$v' OR {$k} LIKE '%$v%')";
			}
		}
		
		if($id > 0){
			$Where = 'id = ' . $id;
		}
        $q = $this->executeQuery('SELECT * from profiles WHERE '. $Where);
        if($this->num_rows($q) > 0)
        {
            return $this->fetchQuery($q);
        }
    }

    public function getUserPlano($id) {
         
        $result = $this->executeQuery("SELECT pag.id_profile from pagamentos pag INNER JOIN planos p on p.id = pag.id_profile WHERE pag.id_usuario = '$id' ORDER BY pag.data_add limit 1");
        
        if(count($result) > 0) { 
            
            return mysqli_fetch_object($result);

        }
    }

    public function checkUser($login)
    {
        $q = $this->executeQuery("SELECT * from usuarios WHERE login = '".$this->filterKey($login)."'");
        if($this->num_rows($q))
        {
            return true;
        }
        $q = $this->executeQuery("SELECT * from gerenciadores WHERE login = '".$this->filterKey($login)."'");
        if($this->num_rows($q))
        {
            return true;
        }
    }

    public function gerarKey($tries_min = 3){
      //$keys = array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","p","q","r","s","u","v","w",'x',"y","z");
    	$keys = array("w",'x',"y","z","1","2","3","4","5","6","7","8","9","0");	
      for($i = 1; $i <= 9; $i++) $keys[] = (string) $i;
      $lett = "";
      for($z = 0; $z <= $tries_min; $z++)
      {
        if(rand(0,2) >= 2){
          $lett .= ($keys[rand(0, count($keys)-1)]);
        }else{
          $lett .= $keys[rand(0, count($keys)-1)];
        }
      }
      return $lett;
    }

    public function gerarLink($url) {
        
         
         
        $url = $this->filterKey($url, 1, 0);
        $exists_url = $this->executeQuery("SELECT * from redirecionamento WHERE `url_redirecionar` = '{$url}'");
        if($this->num_rows($exists_url) > 0){
            
            list($exists_url) = (array) $exists_url;
            
            return $exists_url['id_key'];
        } 

        $tkn = $this->gerarKey();
        $tries_min = 3;
        $tentativas = 0;
        while($this->num_rows($this->executeQuery("SELECT * from redirecionamento WHERE `id_key` = '{$tkn}'"))){
            $tkn = $this->gerarKey();
            $tentativas++;
            if($tentativas >= 2){$tries_min++;}
        }
        
        $this->executeQuery("INSERT into redirecionamento (id_key, url_redirecionar) VALUES ('{$tkn}', '{$url}')");
        return $tkn;
        
    }

    public function check_available($login)
    {
        return $this->checkUser($login);
    }

    public function emailsSendStore($user_id, $email)
    {   
        $now = date('Y-m-d H:i:s');

        $this->executeQuery("INSERT INTO emails_enviados(user_id,email,date_send) VALUES ('$user_id', '$email', '$now')");
    }

    public function getEmailSend() {

        return $this->fetchQuery($this->executeQuery("SELECT * from emails_enviados")); 
    
    }

    public function isEmailSend($email)
    {   
        
        return $this->fetch($this->executeQuery("SELECT * from emails_enviados WHERE `email` = '{$email}'"));             
    }

    function __destruct()
    {
	if(is_object($this->con)&&$this->con)
	        return mysqli_close($this->con);
    }
}
function checkspecial($string)
{
    return !preg_match('/^[0-9-a-z]+$/i', $string);
}


?>
