<?php

if(strpos($_SERVER['REQUEST_URI'],"login.php") || !isset($_POST['tokserver_hk'])){
    require_once 'Utils.php';
    PlainDie();
}
include 'init.php';
date_default_timezone_set('America/Sao_Paulo');
//initialization
$crypter = Crypter::init();
$privatekey = readFileData("Keys/44PrivateKey.prk");

//echo $crypter->getPrivateKey();
function tokenResponse($data){
    global $crypter, $privatekey;
    $data = toJson($data);
    $datahash = sha256($data);
    $acktoken = array(
        "Dados_hk" => profileEncrypt($data, $datahash),
        "Sign_hk" => toBase64($crypter->signByPrivate($privatekey, $data)),
        "Hash_hk" => $datahash
    );
    return toBase64(toJson($acktoken));
}

function meuip() {
    $ipaddress = '';
    
    if (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    } 
    else if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        // Caso contenha múltiplos IPs, pegar o primeiro
        $ipaddress = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
    } 
    else if (isset($_SERVER['HTTP_X_FORWARDED'])) {
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    } 
    else if (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    } 
    else if (isset($_SERVER['HTTP_FORWARDED'])) {
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    } 
    else if (isset($_SERVER['REMOTE_ADDR'])) {
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    } 
    else {
        $ipaddress = 'UNKNOWN';
    }

    return trim($ipaddress);  // Retorna o IP, removendo qualquer espaço extra
}

function getCountryByIP($ip) {
    $url = "http://ip-api.com/json/{$ip}";
    $response = file_get_contents($url);
    $data = json_decode($response);
    
    if ($data && $data->status === "success") {
        return $data->country;
    }
    return "Unknown";
}
//token data
$token = fromBase64($_POST['tokserver_hk']);
$tokarr = fromJson($token, true);

//Data section decrypter
$encdata = $tokarr['Dados_hk'];
$appToken = $tokarr['Tok_hk'];
$decdata = trim($crypter->decryptByPrivate($privatekey, fromBase64($encdata)));
$data = fromJson($decdata);

//Hash Validator
$tokhash = $tokarr['Hash_hk'];
$newhash = sha256($encdata);

if (strcmp($tokhash, $newhash) == 0) {
    PlainDie();
}

$check_status = mysqli_query($conn,"SELECT * FROM products WHERE mode = 'injetorMobile'");
$row = mysqli_fetch_assoc($check_status);

$version = $row['version'];
$status = $row['status'];
$download = $row['download'];
$sIDx = $row['apk_size'];
$cargo = $row['cargo'];

if($status == "ATT")
{
    $statusMsg = "Servidor em manutenção!";
}
elseif($status == "OFF")
{
    $statusMsg = "Servidor Offline!";
}

if($status == "OFF" || $status == "ATT")
{
    $ackdata = array(
        "ConnectSt_hk" => "Failed",
        "MessageFromSv" => $statusMsg,
        "ExpireDays" => "0",
        "ApkVersion_hk" => $version
    );
    PlainDie(tokenResponse($ackdata));
}

//Username Validator
$uname = $data["User_hk"];
if($uname == null || preg_match("([a-zA-Z0-9]+)", $uname) === 0){
    $ackdata = array(
        "ConnectSt_hk" => "Failed",
        "MessageFromSv" => "Key está inválida.",
        "ExpireDays" => "0",
        "ApkVersion_hk" => $version
    );
    PlainDie(tokenResponse($ackdata));
}

$query = $conn->query("SELECT * FROM `tokens` WHERE `Username` = '".$uname."'");
if($query->num_rows < 1){
    $ackdata = array(
        "ConnectSt_hk" => "Failed",
        "MessageFromSv" => "Key está inválida.",
        "ExpireDays" => "0",
        "ApkVersion_hk" => $version
    );
    PlainDie(tokenResponse($ackdata));
}


$check_produto = mysqli_query($conn,"SELECT * FROM `tokens` WHERE `Username` = '".$uname."' AND `mode` = 'injetorMobile'");
if($check_produto->num_rows < 1){
    $ackdata = array(
        "ConnectSt_hk" => "Failed",
        "MessageFromSv" => "Produto Incorreto!",
        "ExpireDays" => "0",
        "ApkVersion_hk" => $version
    );
    PlainDie(tokenResponse($ackdata));
}

$check_produtocargo = mysqli_query($conn,"SELECT * FROM `tokens` WHERE `Username` = '".$uname."' AND `cargo` ='".$cargo."'");
if($check_produtocargo->num_rows < 1){
    $ackdata = array(
        "ConnectSt_hk" => "Failed",
        "MessageFromSv" => "ESTAMOS EM TESTES!",
        "ExpireDays" => "0",
        "ApkVersion_hk" => $version
    );
    PlainDie(tokenResponse($ackdata));
}

$res = $query->fetch_assoc();

if($res["UID2"] == "one device"){
        if($res["UID"] == NULL){
            $query = $conn->query("UPDATE `tokens` SET `UID` = '".$data["Uid_hk"]."' WHERE `Username` = '".$uname."' AND `Password` = '".$pass."' AND `mode` = 'injetorMobile'");
        }elseif($res["UID"] != $data["Uid_hk"]) {
            $ackdata = array(
            "ConnectSt_hk" => "Failed",
            "MessageFromSv" => "Dispositivo não permitido.",
            "ExpireDays" => "0"
            );
            PlainDie(tokenResponse($ackdata));
        }
} elseif($res["UID2"] == NULL){
    $query = $conn->query("UPDATE `tokens` SET `UID2` = '".$data["Uid_hk"]."' WHERE `Username` = '".$uname."' AND `mode` = 'injetorMobile'");
} elseif($res["UID2"] != $data["Uid_hk"]) {
        
    if($res["UID"] == NULL){
            $query = $conn->query("UPDATE `tokens` SET `UID` = '".$data["Uid_hk"]."' WHERE `Username` = '".$uname."' AND `mode` = 'injetorMobile'");
    }elseif($res["UID"] != $data["Uid_hk"]) {
        $ackdata = array(
        "ConnectSt_hk" => "Failed",
        "MessageFromSv" => "Dispositivo não permitido.",
        "ExpireDays" => "0"
        );
        PlainDie(tokenResponse($ackdata));
    }
}

if ($res["ipclient"] === NULL) {
    // Atualiza o IP do cliente se estiver vazio
    $conn->query("UPDATE `tokens` SET `ipclient` = '".$data["Ip_hk"]."' WHERE `Username` = '".$uname."'");
} elseif ($res["ipclient"] !== $data["Ip_hk"]) {
    
    $ackdata = array(
        "ConnectSt_hk" => "Failed",
        "MessageFromSv" => "Acesso de um novo IP ou dispositivo detectado. Faça um reset para continuar.",
        "ExpireDays" => "0"
    );
    PlainDie(tokenResponse($ackdata));
}
 if($res["StartDate"] == '0000-00-00 00:00:00'){
    $date2 = date("Y-m-d H:i:s");
    $query = $conn->query("UPDATE `tokens` SET `StartDate` = '$date2' WHERE `Username` = '$uname'");
}

if($res["EndDate"] == '0000-00-00 00:00:00'){
    
    $date2 = date("Y-m-d H:i:s");
    $dias = $res["Expiry"];
    $mod_date = strtotime($date2."+ $dias days");
    $adicionardias = date("Y-m-d H:i:s",$mod_date);

    $query = $conn->query("UPDATE `tokens` SET `EndDate` = '$adicionardias' WHERE `Username` = '$uname'");
      $ackdata = array(
        "ConnectSt_hk" => "Failed",
        "MessageFromSv" => "Sua licença Foi Ativada,Relogue!",
        "ExpireDays" => "0",
        "ApkVersion_hk" => $version
    );
    PlainDie(tokenResponse($ackdata));
}
if($res["EndDate"] != '0000-00-00 00:00:00'){
$EndDate = strtotime($res["EndDate"]);
$DataHoje = strtotime(date("Y-m-d H:i:s"));
$DataFinal = 0; 
if($EndDate < $DataHoje){
    $query = $conn->query("UPDATE `tokens` SET `Expiry` = '".$DataFinal."' WHERE `Username` = '".$uname."' AND `mode` = 'injetorMobile'");
    $ackdata = array(
        "ConnectSt_hk" => "Failed",
        "MessageFromSv" => "Sua licença expirou, renove para continuar usando.",
        "ExpireDays" => "0",
        "ApkVersion_hk" => $version
    );
    PlainDie(tokenResponse($ackdata));
}
}
   if($EndDate > $DataHoje){
    $DataDias = ($EndDate - $DataHoje) /86400;
    $DataFinal = round($DataDias, 0);
    if($DataFinal > 0){
        $query = $conn->query("UPDATE `tokens` SET `Expiry` = '".$DataFinal."' WHERE `Username` = '".$uname."' AND `mode` = 'injetorMobile'");
    }
    else{
        $DataFinal = 0;
        $query = $conn->query("UPDATE `tokens` SET `Expiry` = '".$DataFinal."' WHERE `Username` = '".$uname."' AND `mode` = 'injetorMobile'");
    }
} 


  
///Conta Pausada.
if($res['pause'] == 1){
    $ackdata = array(
        "ConnectSt_hk" => "Failed",
        "MessageFromSv" => "LOGIN PAUSADO OU VERSAO EM TESTE PARA  APENAS ADMINS !",
        "ExpireDays" => "0",
        "ApkVersion_hk" => $version
    );
    PlainDie(tokenResponse($ackdata));
}

if($res['ban'] == 1){
    $ackdata = array(
        "ConnectSt_hk" => "Failed",
        "MessageFromSv" => "Conta Banida",
        "ExpireDays" => "0",
        "ApkVersion_hk" => $version
    );
    PlainDie(tokenResponse($ackdata));
}


if ($data["Load_hk"] == 699) {
   
    $loaderdata = readFileData("Loaders/DAEMON/PUBG.kmods");
    $ackdata = array(
        "ConnectSt_hk" => "HasBeenSucceeded",
        "MessageFromSv" => "",
        "Bolsonaro" => toBase64($loaderdata),
        "ExpireDays" => $DataFinal,
        "Logged_UserHK" => $res["Username"],
        "CurrToken" => $data["Uid_hk"],
         "Ip_hk" => $data["ipclient"],
        "ApkVersion_hk" => "1.3",
        "DownLink_hk" => $download,
        "Logged_TokHK" => $appToken
    );
}

if ($data["Load_hk"] == 701) {
   
    $loaderdata = readFileData("Loaders/DAEMON_MAX/PUBG.kmods");
    $ackdata = array(
        "ConnectSt_hk" => "HasBeenSucceeded",
        "MessageFromSv" => "",
        "Bolsonaro" => toBase64($loaderdata),
        "ExpireDays" => $DataFinal,
        "Logged_UserHK" => $res["Username"],
        "CurrToken" => $data["Uid_hk"],
         "Ip_hk" => $data["ipclient"],
        "ApkVersion_hk" => "1.3",
        "DownLink_hk" => $download,
        "Logged_TokHK" => $appToken
    );
}

if($data["Load_hk"] == 867) 
{
  
    $ackdata = array(
        "ConnectSt_hk" => "HasBeenSucceeded",
        "MessageFromSv" => "",
        "ExpireDays" => $DataFinal,
        "Logged_UserHK" => $res["Username"],
        "CurrToken" => $data["Uid_hk"],
        "ApkVersion_hk" => "1.3",
        "Ip_hk" => $data["ipclient"],
        "DownLink_hk" => $download,
        "Logged_TokHK" => $appToken
    );
}

if($data["jofjofjoe"] == 9) 
{
  
    $ackdata = array(
        "ConnectSt_hk" => "HasBeenSucceeded",
        "MessageFromSv" => "",
        "ExpireDays" => $DataFinal,
        "Logged_UserHK" => $res["Username"],
        "CurrToken" => $data["Uid_hk"],
        "Ip_hk" => $data["ipclient"],
        "DownLink_hk" => $download,
        "Logged_TokHK" => $appToken,
        "Vendedor1" => $res["Vendedor"],
        "piddaemon" => $sIDx,
        "cargo" => $res["cargo"]
    );
}


 $pais = getCountryByIP(meuip());
// Atualizando o campo PaisLogin no banco de dados
$conn->query("UPDATE tokens SET PaisLogin = '$pais' WHERE Username = '$uname'");
echo tokenResponse($ackdata);