<?php
ini_set("display_errors", 1);
include __DIR__ . "/../includes/functions.php";

$jsonIn = file_get_contents("php://input");
$response = json_decode($jsonIn, true);
$decoded = base64_decode($response["data"]);
$authData = json_decode($decoded, true);
$portal = [];

// Verificar se o MAC está no authData
if (isset($authData["app_device_id"])) {
    $macAddress = base64_decode($authData["app_device_id"]);
    $macAddress = substr($macAddress, 0, 12);
    $formattedMac = strtoupper(preg_replace("/..(?!$)/", "\$0:", $macAddress));
} else {
    $formattedMac = strtoupper($authData["mac_address"]);
}

// Gerar ou recuperar a device_key do banco de dados
$existingKey = $db->select("device_keys", "device_key", "mac_address = :mac_address", "", [":mac_address" => $formattedMac]);

if (!empty($existingKey)) {
    $device_key = $existingKey[0]["device_key"];
} else {
    $device_key = substr(md5($formattedMac), 0, 8);
    $db->insert('device_keys', [
        'mac_address' => $formattedMac,
        'device_key' => $device_key
    ]);
}

// Verificar o status do chatbot no banco de dados
$res_bot = $db->select("chatbot", "bot_status, bot_url, bot_dns", "id = :id", "", [':id' => 1]);
$bot_status = $res_bot[0]["bot_status"] ?? 0;
$bot_url = $res_bot[0]["bot_url"] ?? '';
$bot_dns_id = $res_bot[0]["bot_dns"] ?? '';

// Verificar se o cliente já está cadastrado na tabela `playlist`
$existingClient = $db->select("playlist", "*", "mac_address = :mac_address", "", [":mac_address" => $formattedMac]);

if (empty($existingClient)) { // Se o cliente NÃO está cadastrado na playlist, tenta gerar via chatbot
    // Se o chatbot está ativo, gerar os dados automaticamente
    if ($bot_status == 1) {
        $json = '{"receiveMessageAppId":"com.whatsapp","receiveMessagePattern":["*"],"senderName":"API DE CADASTRO","groupName":"","senderMesage":"api_cadastro","senderMessage":"api_cadastro","messageDateTime":' . time() . ',"isMessageFromGroup":false}';
        
        $ch = curl_init($bot_url);
        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 = curl_exec($ch);
        $jsonRetornoDecoded = json_decode($jsonRetorno, true);

        if ($jsonRetorno === false || is_null($jsonRetornoDecoded)) {
            echo json_encode(["error" => "Falha na comunicação com o chatbot"]);
            exit;
        }

        $username = null;
        $password = null;
        $payUrl = null;

        if (isset($jsonRetornoDecoded['username']) && isset($jsonRetornoDecoded['password'])) {
            $username = $jsonRetornoDecoded['username'];
            $password = $jsonRetornoDecoded['password'];
            // Verifica se existe payUrl na resposta
            $payUrl = $jsonRetornoDecoded['payUrl'] ?? null;
        } elseif (isset($jsonRetornoDecoded['data'][0]['message'])) {
            $user_pass = explode("|", $jsonRetornoDecoded['data'][0]['message']);
            $username = $user_pass[0];
            $password = $user_pass[1];
            // Verifica se existe payUrl na resposta
            $payUrl = $jsonRetornoDecoded['data'][0]['payUrl'] ?? null;
        }

        if (!empty($username) && !empty($password)) {
            $dns = $db->select("dns", "*", "id = :id", "", [":id" => $bot_dns_id]);
            $dns_url = $dns[0]['url'] ?? '';

            $url = $dns_url . "/get.php?username=" . $username . "&password=" . $password . "&type=m3u_plus&output=ts";
            
            // Dados para inserção na tabela playlist
            $playlistData = [
                'mac_address' => $formattedMac,
                'username' => $username,
                'password' => $password,
                'pin' => '0000',
                'url' => $url,
                'dns_id' => $bot_dns_id
            ];
            
            // Se payUrl foi recebido, adiciona ao array de dados
            if (!empty($payUrl)) {
                $playlistData['link'] = $payUrl;
            }
            
            $db->insert('playlist', $playlistData);
        }
    }
}

// Consultas de banco de dados para pegar TODAS as listas vinculadas ao mac_address
$results = $db->select("playlist", "*", "mac_address = :mac_address", "", [":mac_address" => $formattedMac]);

foreach ($results as $result) {
    $dns = $db->select("dns", "*", "id = :id", "", [":id" => $result["dns_id"]]);
    if (!empty($dns)) {
        $row = $dns[0];
        $portal[] = [
            "is_protected" => 0,
            "id" => $row["id"],
            "url" => $row["url"] . "/get.php?username=" . $result["username"] . "&password=" . $result["password"] . "&type=m3u_plus&output=ts",
            "name" => $row["title"],
            "playlist_name" => $row["title"],
            "type" => "xc",
            "created_at" => $result["created_at"] ?? "2023-03-26 16:42:48",
            "updated_at" => $result["updated_at"] ?? "2023-03-26 16:42:48"
        ];
    }
}

// Outros dados para envio
$backdropUrl = getBaseUrl() . "/backdrop.php";
$settings = $db->select("settings", "*", "id = :id", "", [":id" => 1]);
$theme = $db->select("themes", "*", "id = :id", "", [":id" => 1]);
$theme_id = !empty($theme) ? $theme[0]["theme_id"] : "1";
$result_pin = $db->select("playlist", "*", "mac_address = :mac_address", "", [":mac_address" => $formattedMac]);

$response = [
    "android_version_code" => "1.0.0",
    "apk_url" => "",
    "device_key" => $device_key,
    "expire_date" => "2034-03-26",
    "is_google_paid" => true,
    "is_trial" => 0,
    "languages" => json_decode(file_get_contents("language.json"), true),
    "mac_registered" => true,
    "themes" => [],
    "trial_days" => 7,
    "plan_id" => "36269518",
    "mac_address" => $formattedMac,
    "pin" => $result_pin[0]["pin"] ?? "0000",
    "price" => "7.99",
    "apk_link" => "",
    "urls" => $portal,
    "note_title" => $settings[0]["note_title"] ?? '',
    "note_content" => $settings[0]["note_content"] ?? '',
    "qr_url" => "",
    "qr_url_short" => "",
    "home_mode" => null,
    "home_url1" => $backdropUrl,
    "home_url2" => $backdropUrl,
    "theme" => $theme_id
];

echo Encryption::run(json_encode($response), "IBO_38");

// Função utilitária
function getBaseUrl() {
    $protocol = (!empty($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] !== "off" || $_SERVER["SERVER_PORT"] == 443) ? "https://" : "http://";
    $domainName = $_SERVER["HTTP_HOST"];
    $folderPath = dirname($_SERVER["PHP_SELF"]);
    return $protocol . $domainName . $folderPath;
}
?>