<?php


//<----------------------------------------------------------->
//<-------------------COPIA AI BRUXÃO------------------------->
//<-------------CONTATO: https://t.me/eonbry------------------>
//<-------------DEVELOPER: EMANUEL NASCIMENTO----------------->
//<----------------------------------------------------------->


error_reporting(0);
const ALLOWED_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

function getDecodedString($str) {
    $p1 = strpos(ALLOWED_CHARACTERS, substr($str, -2, 1));
    $p2 = strpos(ALLOWED_CHARACTERS, substr($str, -1, 1));
    $sub = substr($str, 0, -2);
    return trim(utf8_decode(base64_decode(substr($sub, 0, $p1) . substr($sub, $p1 + $p2))));
}
function getEncodedString($str) {
    $p1 = strpos(ALLOWED_CHARACTERS, substr($str, -2, 1));
    $p2 = strpos(ALLOWED_CHARACTERS, substr($str, -1, 1));
    $enc = base64_encode(utf8_encode($str));
    $sub = substr($enc, 0, $p1) . substr($enc, $p1 + $p2);
    return $sub . substr(ALLOWED_CHARACTERS, $p1, 1) . substr(ALLOWED_CHARACTERS, $p2, 1);
}

function loadIbo() {
    $f = @file_get_contents(__DIR__ . '/ibo.json');
    $j = $f ? json_decode($f, true) : [];
    return [
        'android_version_code' => $j['app_info']['android_version_code'] ?? '1.0',
        'apk_url' => $j['app_info']['apk_url'] ?? ''
    ];
}

function themes() {
    $db = new SQLite3(__DIR__ . '/.eggziedb.db');
    $res = @$db->query('SELECT * FROM theme');
    $t = [];
    while ($r = $res->fetchArray(SQLITE3_ASSOC)) $t[] = ['name'=>$r['name'],'url'=>$r['url']];
    return json_encode($t);
}
function note(){ return @file_get_contents(__DIR__ . '/note.json') ?: '[]'; }
function lang(){ return @file_get_contents(__DIR__ . '/language.json') ?: '[]'; }

// lê bot_status como STRING (exatamente '1' = ativo)
function getBotConfig() {
    $path = realpath(__DIR__ . '/../api/db/eonbrybot.db');
    $db = new SQLite3($path);
    $row = @$db->query("SELECT * FROM bot WHERE id=1")->fetchArray(SQLITE3_ASSOC) ?: [];
    // retorna bot_status exatamente como está no DB (string)
    return [
        'url' => trim($row['bot_url'] ?? ''),
        'dns' => trim($row['bot_dns'] ?? ''),
        'status' => isset($row['bot_status']) ? (string)$row['bot_status'] : '0',
        'name' => trim($row['bot_name'] ?? 'Bot')
    ];
}

function getDemoConfig() {
    $path = realpath(__DIR__ . '/../api/db/eonbrydemo.db');
    $db = new SQLite3($path);
    $row = @$db->query("SELECT * FROM demo WHERE id=1")->fetchArray(SQLITE3_ASSOC) ?: [];
    return [
        'url' => trim($row['demo_url'] ?? 'http://demo.4kapps.com/get.php?username=normal&password=demo&type=m3u_plus&output=mpegts'),
        'name' => trim($row['demo_name'] ?? 'Lista Demo')
    ];
}

function criarTesteAutomatico($mac, $bot) {
    $db = new SQLite3(__DIR__ . '/.eggziedb.db');
    $json = json_encode([
        "receiveMessageAppId"=>"com.whatsapp",
        "receiveMessagePattern"=>["*"],
        "senderName"=>"API DE CADASTRO",
        "groupName"=>"",
        "senderMessage"=>"api_cadastro",
        "messageDateTime"=>time(),
        "isMessageFromGroup"=>false
    ], JSON_UNESCAPED_SLASHES);
    $ch = curl_init($bot['url']);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    $resp = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);
    file_put_contents(__DIR__.'/debug_curl.txt', date('c')." ERR=$err RESP=".substr($resp,0,200)."\n", FILE_APPEND);

    $data = json_decode($resp, true) ?: [];
    $username = $data['username'] ?? null;
    $password = $data['password'] ?? null;
    if (empty($username) && isset($data['data'][0]['message'])) {
        $parts = explode('|', $data['data'][0]['message']);
        $username = $parts[0] ?? null;
        $password = $parts[1] ?? null;
    }

    if ($username && $password) {
        $expire = date('Y-m-d', strtotime('+1 day'));
        $url = "{$bot['dns']}/get.php?username=$username&password=$password&type=m3u_plus&output=ts";
        $db->exec("INSERT INTO ibo (mac_address, username, password, expire_date, title, url) VALUES ('$mac','$username','$password','$expire','{$bot['name']}','$url')");
    } else {
        $db->exec("INSERT INTO ibo (mac_address, title) VALUES ('$mac','NOVO*** (SEM DNS, USUARIO E SENHA)')");
    }
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') exit;

$raw = file_get_contents('php://input');
$j = json_decode($raw);
if (!$j || !isset($j->data)) { http_response_code(400); echo 'invalid'; exit; }
$decoded = getDecodedString($j->data);
$payload = json_decode($decoded, true);
if (!isset($payload['app_device_id'])) { http_response_code(400); echo 'no id'; exit; }

$mac = getDecodedString($payload['app_device_id']);
$mac = rtrim(chunk_split($mac,2,':'),':');
file_put_contents(__DIR__.'/last_mac.txt', $mac);

$ibo_data = loadIbo();
$db = new SQLite3(__DIR__ . '/.eggziedb.db');
$exists = (int)$db->querySingle("SELECT COUNT(*) FROM ibo WHERE mac_address='$mac'");

$bot = getBotConfig();   // status é STRING
$demo = getDemoConfig();

file_put_contents(__DIR__.'/debug_decisao.txt', date('c')." BOT_STATUS_RAW={$bot['status']} EXISTS={$exists}\n", FILE_APPEND);

// SIMPLES: se o valor no DB for exatamente '1' -> CRIA TESTE; caso contrário -> usa DEMO
if ($exists === 0) {
    if ($bot['status'] === '1') {
        criarTesteAutomatico($mac, $bot);
    } else {
        $expire = date('Y-m-d', strtotime('+7 days'));
        $db->exec("INSERT INTO ibo (mac_address, title, expire_date, url) VALUES ('$mac','{$demo['name']}','$expire','{$demo['url']}')");
    }
}

// montar resposta (busca atualizada)
$res = $db->query("SELECT * FROM ibo WHERE mac_address='$mac'");
$urls = []; $expire_date = date('Y-m-d');
while ($r = $res->fetchArray(SQLITE3_ASSOC)) {
    $urls[] = [
        'is_protected'=>"1",
        'id'=>md5(($r['password'] ?? '').$r['id']),
        'url'=>$r['url'],
        'name'=>$r['title'],
        'created_at'=>date('Y-m-d H:i:s'),
        'updated_at'=>date('Y-m-d H:i:s')
    ];
    $expire_date = $r['expire_date'] ?? $expire_date;
}

$output = [
    "android_version_code"=>$ibo_data['android_version_code'],
    "apk_url"=>$ibo_data['apk_url'],
    "device_key"=>"136115",
    "expire_date"=>$expire_date,
    "notification"=> json_decode(note(), true) ?: [],
    "urls"=>$urls,
    "mac_registered"=> (count($urls)>0),
    "themes"=> json_decode(themes(), true),
    "mac_address"=>$mac,
    "languages"=> json_decode("[".lang()."]", true) ?: []
];

header('Content-Type: application/json');
echo json_encode(['data'=> getEncodedString(json_encode($output, JSON_UNESCAPED_SLASHES))]);
