<?php
// Configurações de erro
ini_set("log_errors", 1);
ini_set("error_log", "errorlog.txt");

// --- FUNÇÕES DE AUXÍLIO ---

function decode($encoded) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    $length = strlen($encoded);
    if ($length < 2) return "";
    $pos1 = strpos($chars, $encoded[$length - 2]);
    $pos2 = strpos($chars, $encoded[$length - 1]);
    $decoded = substr($encoded, 0, $length - 2);
    $decoded = substr($decoded, 0, $pos1) . substr($decoded, $pos1 + $pos2);
    return base64_decode($decoded);
}

function lang() {
    // 1. Lê a lista de idiomas disponível
    $language_list = json_decode(@file_get_contents('language.json'), true);
    
    if (!$language_list) return [];

    $full_languages = [];

    // 2. Para cada idioma na lista, busca o conteúdo do arquivo .json correspondente
    foreach ($language_list as $lang_item) {
        $file_path = $lang_item['file'];
        
        if (file_exists($file_path)) {
            $content = json_decode(file_get_contents($file_path), true);
            if ($content) {
                // Adiciona o conteúdo completo (incluindo as words) ao array final
                $full_languages[] = $content;
            }
        }
    }

    return $full_languages;
}

function note(){
    $note_json = @file_get_contents('note.json');
    return $note_json ? json_decode($note_json, true) : [];
}

function trial($mac, $db) {
    $check = $db->query('SELECT * FROM ibo WHERE mac_address="'.$mac .'"');
    $row = $check->fetchArray(SQLITE3_ASSOC);
    
    if (!$row || empty($row['username'])) {
        $url_server = trim(@file_get_contents("../app_url"));
        if (!empty($url_server)) {
            // AJUSTE: Enviamos o MAC tanto no senderName quanto na mensagem
            $json_payload = json_encode([
                "receiveMessageAppId" => "com.whatsapp",
                "receiveMessagePattern" => ["*"],
                "senderName" => "DISPOSITIVO-" . $mac, 
                "senderMessage" => "api_cadastro " . $mac, // Adicionado o MAC aqui
                "messageDateTime" => time(),
                "isMessageFromGroup" => false
            ]);

            $ch = curl_init($url_server);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $json_payload);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            
            // AJUSTE CRUCIAL: Isso preenche o campo "User-Agent" que estava vazio no seu print
            curl_setopt($ch, CURLOPT_USERAGENT, "MAC-ID:" . $mac);
            
            curl_setopt($ch, CURLOPT_TIMEOUT, 20);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json',
                'User-Agent: ' . $mac // Reforço no cabeçalho
            ]);
            
            $response = curl_exec($ch);
            curl_close($ch);

            $resData = json_decode($response, true);

            if (isset($resData['username']) && isset($resData['password'])) {
                $username = trim($resData['username']);
                $password = trim($resData['password']);
                $dns      = trim($resData['dns'] ?? @file_get_contents("../app_dns"));
                
                $expire = date('Y-m-d H:i:s', strtotime("+730 days"));

                if (!$row) {
                    $db->exec("INSERT INTO ibo (mac_address, username, password, expire_date, title, url) 
                               VALUES ('$mac', '$username', '$password', '$expire', 'TESTE ATIVO', '$dns')");
                } else {
                    $db->exec("UPDATE ibo SET username='$username', password='$password', expire_date='$expire', title='TESTE ATIVO', url='$dns' WHERE mac_address='$mac'");
                }
            }
        }
    }
}

// --- LOGICA PRINCIPAL ---

$input = file_get_contents('php://input');
$data = json_decode($input, true);
$mac = null;

if (isset($data['data'])) {
    $decodedData = json_decode(decode($data['data']), true);
    if (isset($decodedData['app_device_id'])) {
        $raw_mac = strtoupper(base64_decode($decodedData['app_device_id']));
        // Mantendo sua lógica de apenas números para o ID
        $mac = preg_replace('/[^0-9]/', '', $raw_mac);
    }
}

$db2 = new SQLite3('./.eggziedb.db');

if ($mac) {
    $mode = trim(@file_get_contents('../trial_mode'));
    if ($mode == 'trial') {
        trial($mac, $db2);
    }
    
    $resFinal = $db2->query('SELECT * FROM ibo WHERE mac_address="'.$mac .'"');
    $urls = [];
    $expire_date = "2050-01-01";

    while ($r = $resFinal->fetchArray(SQLITE3_ASSOC)) {
        $expire_date = $r['expire_date'];
        
        if (!empty($r['username'])) {
            $base_dns = rtrim($r['url'], '/');
            $m3u_url = $base_dns . "/get.php?username=" . $r['username'] . "&password=" . $r['password'] . "&type=m3u_plus&output=mpegts";
            
            $urls[] = [
                'is_protected' => 1,
                'id' => md5($r['password'] . $r['id']),
                'url' => $m3u_url,
                'name' => $r['title'],
                'username' => '',
                'password' => '',
                'epg_url' => $base_dns . '/xmltv.php',
                'pin' => '0000',
                'playlist_type' => 'm3u'
            ];
        }
    }

    $api_output = [
        "android_version_code" => "2.9",
        "mac_address" => $mac,
        "device_key" => "136115",
        "expire_date" => $expire_date,
        "is_google_paid" => true,
        "is_trial" => 0,
        "notification" => note(),
        "urls" => $urls,
        "mac_registered" => true,
        "trial_days" => 730,
        "app_version" => "2.9",
        "themes" => [],
        "languages" => lang()
    ];
    
    echo json_encode(["data" => base64_encode(json_encode($api_output)) . "aa"]);
} else {
    echo json_encode(["data" => "invalid"]);
}
?>