<?php

/*CONEXAO COM O BANCO*/
include "../Connections/config.php";
/*********************/

header("Content-Type: application/json");

$started2 = microtime(true);
$started = microtime(true);
$re2s = $db->query("SELECT * FROM theme");
$dat2a = [];
while ($row23 = $re2s->fetch_array()) {
    $dat2a[] = ["name" => $row23["name"], "url" => $row23["url"]];
}
$dat2a1 = json_encode($dat2a);
$dat2a1 = str_replace("\\/", "/", $dat2a1);
$started1 = microtime(true);
$jsondata = file_get_contents("./update.json");
$data = json_decode($jsondata, true);
$json = $data["app_info"];
$android_version_code = $json["android_version_code"];
$apk_url = $json["apk_url"];
$data222 = [];

$res222 = $db->query("SELECT * FROM epg");
while ($row222 = $res222->fetch_array()) {
    $data222[] = $row222["url"];
}
$data122 = json_encode($data222);
$data122 = str_replace("\\/", "/", $data122);

if (isset($_GET["a"])) {
    $address = $_GET["a"];
    $address1 = strtoupper($address);
}
$lang = file_get_contents("./language.json");
$res2 = $db->query("SELECT * FROM advert");
while ($row2 = $res2->fetch_array()) {
    $api2[] = ["title" => $row2["title"], "description" => $row2["description"], "url" => $row2["url"]];
}
if ($api2 == NULL || $api2 == "") {
    $new2 = "[{\"title\":\"BoxBR Flix IPTV\",\"description\":\"Best Media Player in the world.\",\"url\":\"https:\\/\\/vcapp.online/\\flix/\\/public\\/upload\\/1604854505.png\"}]";
} else {
    $new2 = json_encode($api2);
    $new2 = str_replace("\\/", "/", $new2);
}
$datah = date("Y-m-d");
if (isset($_GET["a"])) {
    
	/*VERIFICA SE O MAC ESTA CADASTRADO NA LISTA DE DISPOSITIVOS*/
	$res = $db->query("SELECT * FROM flixiptv WHERE mac_address=\"" . $address1 . "\"");
	
	if(mysqli_num_rows($res) == 0){
		
		/*API DE CADASTRO DE TESTE VIA JSON BY: XtremeApps (16)981019147*/
		/*
		/*
		/*mensagem a ser enviada para o servidor de iptv*/
		$json ='{"receiveMessageAppId":"com.whatsapp","receiveMessagePattern":["*"],"senderName":"API DE CADASTRO","groupName":"","senderMesage":"api_cadastro","senderMessage":"api_cadastro","messageDateTime":'.time().',"isMessageFromGroup":false}';
		
		/*exemplo do retorno recebido*/
		/*$retorno = '{"data":[{"message":"xx-usuario-xx|xx-senha-xx"}]}';*/
	
		/*ENVIA O JSON PARA O SERVIDOR VIA POST*/
		/*
		*/
		/*url do servidor*/
		// 		$url_server = 'https://office2.cloudnation.vip/chatbot/check/?k=1eb4b60fb4';
// 		/*coloque a dns*/
// 		$dns = 'http://srv.cldplay.net:80';
        $url_server = file_get_contents("app_url");
		/*coloque a dns*/
		$dns = file_get_contents("app_dns");
		/*no servidor configure uma mensagem com o texto: api_cadastro
		/*e uma resposta assim: {USERNAME}|{PASSWORD}
		/*usando a barra vertical para separar o usuario da senha
		/*
		*/
		$ch = curl_init($url_server);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			'Content-Type: application/json',
			'Content-Length: ' . strlen($json))	
		);
		/**************************************/
		
		/*RECUPERA A RESPOSTA DO JSON ENVIADO*/
		$jsonRetorno = json_decode(curl_exec($ch), true);
		/****************************/
		
		/*VERIFICA SE OBTEVE UMA RESPOSTA VALIDA*/
		if(isset($jsonRetorno['data'][0]['message'])){
			$user_pass = explode("|", $jsonRetorno['data'][0]['message']);
			/*SEPARA USERNAME E PASSWORD*/
			if(isset($user_pass[0]) && isset($user_pass[1]) ){
				$username = $user_pass[0];
				$password = $user_pass[1];
				/*RECUPERA A DATA DO PRÓXIMO DIA*/
				$expire_date2 = date('Y-m-d', strtotime("+1 DAY"));
				/*monta a url da m3u*/
				$url = $dns."/get.php?username=".$username."&password=".$password."&type=m3u_plus&output=ts";
				
				/*CADASTRA O MAC COM O TESTE*/
				$cadastra_mac = mysqli_query($db, "INSERT INTO flixiptv (mac_address, username, password, expire_date, dns,  title, url, type) 
													VALUES ('$address1', '$username', '$password', '$expire_date2', '$dns', 'NOVO*** (TESTE CADASTRADO)', '$url', 0 )");
			}else{
				
				/*CADASTRA O MAC SEM O TESTE*/
				$cadastra_mac = mysqli_query($db, "INSERT INTO flixiptv (mac_address, title) 
													VALUES ('$address1', 'NOVO*** (SEM DNS, USUARIO E SENHA)' )");
				/***************/
				
			}
			/***************************/
			
			
			
		}else{
			
			/*CADASTRA O MAC SEM O TESTE*/
			$cadastra_mac = mysqli_query($db, "INSERT INTO flixiptv (mac_address, title) 
												VALUES ('$address1', 'NOVO*** (SEM DNS, USUARIO E SENHA)' )");
			/***************/
		
		}
		/*API DE CADASTRO DE TESTE VIA JSON BY: XtremeApps 16 981019147*/
		/*******************************************************************/
		
		
	}
	/******************************************************************/
	
	$res2 = $db->query("SELECT * FROM flixiptv WHERE mac_address=\"" . $address1 . "\"");
    while ($row = $res2->fetch_array()) {
        $expire_date = $row["expire_date"];
    }
    
    if (empty($expire_date)) {
        $end1 = microtime(true);
        $end = microtime(true);
        $difference = $end - $started;
        $difference1 = $end1 - $started1;
        $queryTime = number_format($difference, 16);
        $queryTime1 = number_format($difference1, 16);
        $end2 = microtime(true);
        $difference2 = $end2 - $started2;
        $queryTime2 = number_format($difference2, 16);
        header("Location: ../lock.php");
    } else {
        $data2 = [];
        
		$res3 = $db->query("SELECT * FROM flixiptv WHERE mac_address=\"" . $address1 . "\"");
        while ($row2 = $res3->fetch_array()) {
            if ($row2["type"] == 0) {
                $data2[] = $row2["dns"] . "/get.php?username=" . $row2["username"] . "&password=" . $row2["password"] . "&type=m3u_plus&output=ts";
            } else {
                $data2[] = $row2["url"];
            }
        }
        $data1 = json_encode($data2);
        $data1 = str_replace("\\/", "/", $data1);
        $end1 = microtime(true);
        $end = microtime(true);
        $difference = $end - $started;
        $difference1 = $end1 - $started1;
        $queryTime = number_format($difference, 16);
        $queryTime1 = number_format($difference1, 16);
        $end2 = microtime(true);
        $difference2 = $end2 - $started2;
        $queryTime2 = number_format($difference2, 16);
        $api = "{\"playlist getting time\":" . $queryTime . ",\"mac_registered\":true,\"is_trial\":0,\"expire_date\":\"" . $expire_date . "\",\"urls\":" . $data1 . ",\"themes\":" . $dat2a1 . ",\"adverts\":" . $new2 . ",\"app_type\":\"android\",\"use_agent\":\"mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/88.0.4324.104 safari/537.36\",\"android_version_code\":\"" . $android_version_code . "\",\"apk_url\":\"" . $apk_url . "\",\"epg_urls\":" . $data122 . ",\"word getting time\":" . $queryTime1 . ",\"languages\":[" . $lang . "],\"total_execution_time\":" . $queryTime2 . "}";
    }
} else {
    header("Location: ../lock.php");
}
echo $api;

?>