<?php
// Impede o cache definindo cabeçalhos apropriados
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Expires: 0");

// Caminho para o banco de dados de vencimento
$dbv = new SQLite3("./db/studiolivecode_vencimento.db");

// Inicialmente, definimos $id_user como null
$id_user = null;

// Funções existentes
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('./db/studiolivecode_clientes.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('./db/studiolivecode_clientes.db');
    
    $ibo_query = $db->prepare('SELECT * FROM ibo WHERE mac_address=:mac_address');
    $ibo_query->bindValue(':mac_address', $mac_address, SQLITE3_TEXT);
    $ibo_result = $ibo_query->execute();
    $urls = [];
    $has_url = false;
    $device_key = '';
    $id_user = null;

    while ($ibo_row = $ibo_result->fetchArray(SQLITE3_ASSOC)) {
        if ($ibo_row['url']) {
            $has_url = true;
            $urls[] = [
                'is_protected' => "1", 
                'id' => md5($ibo_row['password'] . $ibo_row['id']), 
                'url' => $ibo_row['url'], 
                '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'];
        $device_key = $ibo_row['key'];
        $id_user = $ibo_row['id_user']; // Obtendo o id_user
    }

    if ($has_url) {
        return [
            'urls' => json_encode($urls),
            'expire_date' => $expire_date,
            'device_key' => $device_key,
            'id_user' => $id_user
        ];
    } else {
        return [
            'urls' => json_encode($urls),
            'expire_date' => date('Y-m-d', strtotime("+15 DAYS")),
            'device_key' => $device_key,
            'id_user' => $id_user
        ];
    }
}

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

function generateUniqueDeviceKey($db) {
    do {
        $device_key = rand(100000, 999999); // Gera um número aleatório de 6 dígitos
        $stmt = $db->prepare('SELECT COUNT(*) as count FROM ibo WHERE key = :device_key');
        $stmt->bindValue(':device_key', $device_key, SQLITE3_TEXT);
        $result = $stmt->execute();
        $row = $result->fetchArray(SQLITE3_ASSOC);
    } while ($row['count'] > 0);
    return $device_key;
}

function getDnsUrl() {
    $db = new SQLite3("./db/studiolivecode_dns.db");
    $dns_query = $db->query("SELECT url FROM dns LIMIT 1");
    $row = $dns_query->fetchArray();
    return $row ? $row['url'] : null;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $post_data = file_get_contents('php://input');
    $json_data = json_decode($post_data);
    
    if (!isset($json_data->data)) {
        die('Dados inválidos.');
    }
    
    $json_data = $json_data->data;
    $json_data = getDecodedString($json_data);
    $json_data = json_decode($json_data, true);
    
    if (!isset($json_data['app_device_id'])) {
        die('ID do dispositivo não fornecido.');
    }
    
    $mac_address = getDecodedString($json_data['app_device_id']);
    $mac_address = chunk_split($mac_address, 2, ':');
    $mac_address = rtrim($mac_address, ':');
    $mac_address = strtoupper($mac_address);
    $mac_address = substr($mac_address, 0, 17);

    $ibo_data = loadIbo();
    $result = getUserData($mac_address);
    $userData = $result['urls'];
    $device_key = $result['device_key'];
    $id_user = $result['id_user']; // Obtendo o id_user

    // Variável para determinar se deve bloquear ou não
    $shouldBlock = false;

    // Conexão com o banco de dados vencimento usando id_user, se existir
    if ($id_user !== null) {
        $stmt_vencimento = $dbv->prepare("SELECT vencimento FROM vencimento WHERE id = :id_user");
        $stmt_vencimento->bindValue(':id_user', $id_user, SQLITE3_INTEGER);
        $resv = $stmt_vencimento->execute();
        $rowv = $resv->fetchArray();

        if ($rowv) {
            $vencimento = $rowv["vencimento"];
            $dbt = $vencimento;
            $T1 = strtotime($dbt) < time();

            if ($T1) {
                $shouldBlock = true;
            }
        } else {
            // Se não encontrar o vencimento para o id_user, bloqueia o acesso
            $shouldBlock = true;
        }
    }
    // Se id_user for null, não bloqueia o acesso (deixa livre)

    if ($shouldBlock) {
        die('Acesso bloqueado devido ao vencimento.');
    }

    // Continuação do processamento se não estiver bloqueado
    $dbb = new SQLite3("./db/studiolivecode_bot.db");
    $resb = $dbb->query("SELECT * FROM bot WHERE id='1'");
    $rowb = $resb->fetchArray();
    $bot_url = $rowb["bot_url"];
    $bot_dns = $rowb["bot_dns"];
    $bot_status = $rowb["bot_status"];
    $bot_name = $rowb["bot_name"];

    $db = new SQLite3('./db/studiolivecode_clientes.db');
    $res = $db->prepare("SELECT * FROM ibo WHERE mac_address = :mac_address");
    $res->bindValue(':mac_address', $mac_address, SQLITE3_TEXT);
    $result_ib = $res->execute();

    if ($result_ib->fetchArray() === false) {
        $device_key = generateUniqueDeviceKey($db); // Gera um device_key único
        if ($bot_status == 1) {
            $json ='{"receiveMessageAppId":"com.whatsapp","receiveMessagePattern":["*"],"senderName":"API DE CADASTRO","groupName":"","senderMesage":"api_cadastro","senderMessage":"api_cadastro","messageDateTime":'.time().',"isMessageFromGroup":false}';
            $url_server = $bot_url;
            $dns = $bot_dns;
            $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))
            );

            $jsonRetorno = json_decode(curl_exec($ch), true);

            $username = null;
            $password = null;

            if (isset($jsonRetorno['username']) && isset($jsonRetorno['password'])) {
                $username = $jsonRetorno['username'];
                $password = $jsonRetorno['password'];
            } elseif (empty($username) && empty($password) && isset($jsonRetorno['data'][0]['message'])) {
                $user_pass = explode("|", $jsonRetorno['data'][0]['message']);

                if (isset($user_pass[0]) && isset($user_pass[1])) {
                    $username = $user_pass[0];
                    $password = $user_pass[1];
                }
            }

            if (!empty($username) && !empty($password)) {
                $now = date('Y-m-d');
                $expire_date2 = date('Y-m-d', strtotime("+15 DAYS"));
                $url = $dns."/get.php?username=".$username."&password=".$password."&type=m3u_plus&output=ts";
                $cadastra_mac = $db->exec("INSERT INTO ibo (mac_address, username, password, expire_date, dns, title, url, type, id_user, active, key) VALUES ('$mac_address', '$username', '$password', '$expire_date2', '$dns', '$bot_name', '$url', 1, 1, 0, '$device_key')");
                sleep(30);
            }
        } else {
            $dns = getDnsUrl();
            if ($dns) {
                $username = 'usuario';
                $password = 'senha';
                $expire_date2 = date('Y-m-d', strtotime("+15 DAYS"));
                $url = $dns."/get.php?username=".$username."&password=".$password."&type=m3u_plus&output=ts";
                $cadastra_mac = $db->exec("INSERT INTO ibo (mac_address, title, expire_date, url, active, key, dns, username, password) VALUES ('$mac_address', 'Lista Demo', '$expire_date2', '$url', 1, '$device_key', '$dns', '$username', '$password')");
            } else {
                die('DNS URL not found');
            }
        }
    }

    if ($userData !== "[]") {
        $output_json = '{"android_version_code":"'.$ibo_data['android_version_code'].'","apk_url":"'.escapeUrl($ibo_data['apk_url']).'","device_key":"'.$device_key.'","expire_date":"'.$result['expire_date'].'","is_google_paid":true,"is_trial":0,"notification":'.note().',"urls":'.$userData.',"mac_registered":true,"themes":'.themes().',"trial_days":360,"plan_id":"03370629","mac_address":"'.$mac_address.'","pin":"0000","price":"","app_version":"'.$ibo_data['android_version_code'].'","languages":[' . lang() . '],"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['apk_url']).'","device_key":"'.$device_key.'","expire_date":"'.date('Y-m-d', strtotime("+15 DAYS")).'","is_google_paid":false,"is_trial":1,"notification":'.note().',"urls":[],"mac_registered":true,"themes":'.themes().',"trial_days":7,"plan_id":"","mac_address":"'.$mac_address.'","pin":"0000","price":"","app_version":"'.$ibo_data['android_version_code'].'","languages":[' . lang() . '],"apk_link":"'.escapeUrl($ibo_data['apk_url']).'"}'; 
        $output_json = '{"data":"'.getEncodedString($output_json).'"}';
    }

    // Cabeçalhos adicionais já definidos no início

    http_response_code(200);
    header('HTTP/1.1 200 OK');
    header('Server: Apache');
    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;
}
?>
