<?php
error_reporting(0);
const ALLOWED_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";


function getDecodedString($str) {
    $encryptKeyPosition = getEncryptKeyPosition(substr($str, -2, 1));
    $encryptKeyPosition2 = getEncryptKeyPosition(substr($str, -1));
    $substring = substr($str, 0, -2);
    return trim(utf8_decode(base64_decode(substr($substring, 0, $encryptKeyPosition) . substr($substring, $encryptKeyPosition + $encryptKeyPosition2))));
}

function getEncryptKeyPosition($str) {
    return strpos(ALLOWED_CHARACTERS, $str);
}

function getEncodedString($str) {
    $encryptKeyPosition = getEncryptKeyPosition(substr($str, -2, 1));
    $encryptKeyPosition2 = getEncryptKeyPosition(substr($str, -1));
    $encodedString = base64_encode(utf8_encode($str));
    $substring = substr($encodedString, 0, $encryptKeyPosition) . substr($encodedString, $encryptKeyPosition + $encryptKeyPosition2);
    return $substring . substr(ALLOWED_CHARACTERS, $encryptKeyPosition, 1) . substr(ALLOWED_CHARACTERS, $encryptKeyPosition2, 1);
}

function themes(){
    $db = new SQLite3('./.eggziedb.db');
    $themes_query = $db->query('SELECT * FROM theme');
    $themes = [];
    while ($theme_row = $themes_query->fetchArray()) {
        $themes[] = ['name' => $theme_row['name'], 'url' => $theme_row['url']];
    }
    $themes_json = json_encode($themes);
    return $themes_json;
}

function loadIbo(){
    $app_info_json = file_get_contents('./ibo.json');
    $app_info = json_decode($app_info_json, true);
    $android_version_code = $app_info['app_info']['android_version_code'];
    $apk_url = $app_info['app_info']['apk_url'];
    return array(
        'android_version_code' => $android_version_code,
        'apk_url' => $apk_url
    );
}

function lang(){
    $language_json = file_get_contents('./language.json');
    return $language_json;
}

function note(){
    $note_json = file_get_contents('./note.json');
    return $note_json;
}

function getUserData($mac_address){
    $db = new SQLite3('./.eggziedb.db');
    $mac_address = strtolower($mac_address);
    $ibo_query = $db->query('SELECT * FROM ibo WHERE LOWER(mac_address)="' . $mac_address . '"');
    $urls = [];
    while ($ibo_row = $ibo_query->fetchArray()) {
        $urls[] = [
            'is_protected' => "1", 
            'id' => md5($ibo_row['password'] . $ibo_row['id']), 
            'url' => $ibo_row['url']."/get.php?username=".$ibo_row['username']."&password=".$ibo_row['password']."&type=m3u_plus&output=ts", 
            'name' => $ibo_row['title'], 
            'playlist_name' => $ibo_row['title'], 
            'created_at' => '2023-04-15 00:06:09',
            'updated_at' => '2023-04-15 00:06:09'
        ];
        $expire_date = $ibo_row['expire_date'];
    }
    //return json_encode($urls);
    return [
        'urls' => json_encode($urls),
        'expire_date' => $expire_date
    ];
}

function escapeUrl($url) {
  return addcslashes($url, '/\\');
}

function trial($mac) {
    if(!isset($mac)) return;
    
    $db2 = new SQLite3('./.eggziedb.db');

    $res = $db2->query('SELECT * FROM ibo WHERE LOWER(mac_address)="'.$mac .'"');
	$count = 0;
	while ($row = $res->fetchArray()) {
	    $count++;
	}
	
	if ($count == 0){
	    $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_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36');
		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);
		if (curl_errno($ch)) {
            $error_msg = curl_error($ch);
            file_put_contents(__DIR__ . '/_debug_response_error.json', json_encode($error_msg, JSON_PRETTY_PRINT));
        }
        
        file_put_contents(__DIR__ . '/_debug_response.json', json_encode($jsonRetorno, JSON_PRETTY_PRINT));
        
		/****************************/
		
		$username = null;
        $password = null;
        
        /**
         * Retorno do painel Qpanel
         */
        if (isset($jsonRetorno['username']) && isset($jsonRetorno['password'])) {
            $username = $jsonRetorno['username'];
            $password = $jsonRetorno['password'];
        }
        
        /**
         * Retorno de outros painéis
         */
        if (empty($username) && empty($password) && 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];
            }
        }
        
        /**
         * Verifica se temos um usuário e senha válidos
         */
        if (!empty($username) && !empty($password)) {
			/*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";
            $url = $dns;
			
			/*CADASTRA O MAC COM O TESTE*/
			$db2->exec("INSERT INTO ibo (mac_address, username, password, expire_date, title, url) VALUES ('$mac', '$username', '$password', '$expire_date2', 'NOVO*** (TESTE CADASTRADO)', '$url')");
		}else{
			
			$db2->exec("INSERT INTO ibo (mac_address, title) VALUES ('$mac', 'NOVO*** (SEM DNS, USUARIO E SENHA)')");
			/*CADASTRA O MAC SEM O TESTE*/
			
			/***************/
			
		}
		/*VERIFICA SE OBTEVE UMA RESPOSTA VALIDA*/
		/*API DE CADASTRO DE TESTE VIA JSON BY: XtremeApps 16 981019147*/
		/*******************************************************************/
	}
}

function defaultHandle($mac) {
    if(!isset($mac)) return;
    
    $db2 = new SQLite3('./.eggziedb.db');
    
    $res = $db2->query('SELECT * FROM ibo WHERE LOWER(mac_address)="'.$mac .'"');
	$count = 0;
	while ($row = $res->fetchArray()) {
	    $count++;
	}
    
    if ($count == 0) {
        $db2->exec("INSERT INTO ibo (mac_address, title, expire_date) VALUES ('$mac', 'NOVO*** (SEM DNS, USUARIO E SENHA)', '2050-01-01')");
    }
}

$filetext = 'lang.txt';
$contentstext = file_get_contents($filetext);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // get the raw post data
    $post_data = file_get_contents('php://input');
    
    $db = new SQLite3('./.eggziedb.db');
    
    
    
    // decode the JSON data
    $json_data = json_decode($post_data);
    $json_data = $json_data->data;
    $json_data = getDecodedString($json_data);
    $json_data = json_decode($json_data, true);
    $mac_address = getDecodedString($json_data['app_device_id']);
    $mac_address = chunk_split($mac_address, 2, ':');
    $mac_address = rtrim($mac_address, ':');
    $mac_address = strtolower($mac_address);
    
    $mode = file_get_contents('../trial_mode');
    if ($mode == 'trial'){
        trial($mac_address);
    } else {
        defaultHandle($mac_address);
    }

    $expire_date = "";
    
    $ibo_data = loadIbo();
    
    $result = getUserData($mac_address);
    
    $userData = $result['urls'];
    
    if($userData !== "[]"){
        $output_json = '{"android_version_code":"'.$ibo_data['android_version_code'].'","apk_url":"'.escapeUrl($ibo_data['app_url']).'","device_key":"236115","expire_date":"'.$result['expire_date'].'","is_google_paid":true,"is_trial":0,"app_pro_description":'.note().',"urls":'.$userData.',"mac_registered":true,"themes":'.themes().',"trial_days":360,"plan_id":"03370629","mac_address":"'.$mac_address.'","pin":"0000","price":"0","app_version":"'.$ibo_data['android_version_code'].'","languages":[' . $contentstext . '],"apk_link":"'.escapeUrl($ibo_data['apk_url']).'"}'; 
        
        $output_json = '{"data":"'.getEncodedString($output_json).'"}';
    }else{
        $output_json = '{"android_version_code":"'.$ibo_data['android_version_code'].'","apk_url":"'.escapeUrl($ibo_data['app_url']).'","device_key":"236115","expire_date":"2030-01-01","is_google_paid":false,"is_trial":1,"app_pro_description":'.note().',"urls":[],"mac_registered":false,"themes":'.themes().',"trial_days":7,"plan_id":"","mac_address":"'.$mac_address.'","pin":"0000","price":"0","app_version":"'.$ibo_data['android_version_code'].'","languages":[' . $contentstext . '],"apk_link":"'.escapeUrl($ibo_data['apk_url']).'"}'; 
        
        $output_json = '{"data":"'.getEncodedString($output_json).'"}';
    }

    http_response_code(200);
    header('HTTP/1.1 200 OK');
    header('Server: Apache');
    header('Cache-Control: no-cache, private');
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Max-Age: 86400');
    header('Access-Control-Allow-Headers: ');
    header('Access-Control-Allow-Method: ');
    header('Access-Control-Allow-Credentials: true');
    header('Connection: close');
    header('Content-Type: application/json');
    echo $output_json;

  }
  
  
                            /*{
                            "android_version_code":"1.0.0",
                            "apk_url":"",
                            "mac_registered":true,
                            "urls":[
                                    {
                                        "_id":"6488aa697da2e17cd90e582d",
                                        "device_id":"6487896d5e6ec0020af09855",
                                        "url":"http://tv.pro-ott.com:25443/get.php?username=ADAGO&password=4GVRGN1691&type=m3u_plus&output=ts",
                                        "playlist_name":"1",
                                        "is_protected":0,
                                        "pin":"",
                                        "__v":0,
                                        "name":"1"
                                        ,"id":"6488aa697da2e17cd90e582d"
                                        
                                    },
                                    {
                                        "_id":"6488aa777da2e17cd90e582f",
                                        "device_id":"6487896d5e6ec0020af09855",
                                        "url":"http://tv.pro-ott.com:25443/get.php?username=QR8AMFz&password=8BP1TBX6ND&type=m3u_plus&output=ts",
                                        "playlist_name":"2",
                                        "is_protected":0,
                                        "pin":"",
                                        "__v":0,
                                        "name":"2",
                                        "id":"6488aa777da2e17cd90e582f"
                                        
                                    }
                                    ],
                            "trial_days":7,
                            "device_key":"537805",
                            "is_trial":0,
                            "mac_address":"d0:5a:73:b7:42:f9",
                            "expire_date":"2023-06-19"
                        }*/


