<?php
ini_set("display_errors", 'Off');
error_reporting(0);

// =======================================================
// 🛡️ 1. 爬虫检测与拦截
// =======================================================
$userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? strtolower($_SERVER['HTTP_USER_AGENT']) : '';
$bots = [
    'facebook', 'facebot', 'meta-externalagent',
    'google', 'googlebot', 'adsbot',
    //'twitter', 'telegram', 'whatsapp',
    'bytespider', 'python', 'curl', 'wget'
];

$is_bot = false;
foreach ($bots as $bot) {
    if (strpos($userAgent, $bot) !== false) {
        $is_bot = true;
        break;
    }
}

// 🤖 如果是爬虫 -> 显示 Wiki 安全页 -> 停止运行
if ($is_bot) {
    show_safe_page();
    exit;
}

// =======================================================
// 🟠 2. 核心归因拦截与入库
// =======================================================
require_once('DB.php'); 

function getRealIpAddr() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) return $_SERVER['HTTP_CLIENT_IP'];
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ipList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        return trim($ipList[0]);
    }
    return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}

$client_ip = getRealIpAddr();
$client_ua = $_SERVER['HTTP_USER_AGENT'] ?? '';

// 捕获并种下 FBCLID
$fbclid = $_GET['fbclid'] ?? null;
if ($fbclid) {
    $msec_time = round(microtime(true) * 1000); 
    $fbc_value = 'fb.1.' . $msec_time . '.' . $fbclid;
    setcookie('_fbc', $fbc_value, time() + (86400 * 90), "/", "", true, true);
} else {
    $fbc_value = $_COOKIE['_fbc'] ?? null;
}

// 生成我们的究极暗号 DDID (追踪号)
$new_ddid = 'AD3_' . uniqid() . '_' . mt_rand(1000, 9999);
$code = !empty($_GET['code']) ? intval($_GET['code']) : 0;

try {
    $db = new DB('13.234.145.200', 'indiarummy_game', 'remoteuser1', 'Strong@Password123!');
    $exists = $db->query("SELECT id FROM agent_tree_temp WHERE ddid = ? LIMIT 1", [$new_ddid])->getOne();
    
    if (!$exists) {
        $fb_clid      = $_GET['fbclid'] ?? '';
        $customize_id = $_GET['pp0'] ?? '';
        $campaign_name= $_GET['pp1'] ?? '';
        $campaign_id  = $_GET['pp2'] ?? '';
        $adset_name   = $_GET['pp3'] ?? '';
        $adset_id     = $_GET['pp4'] ?? '';
        $ad_name      = $_GET['pp5'] ?? '';
        $ad_id        = $_GET['pp6'] ?? '';
        $pixel        = $_GET['pp7'] ?? '';

        $sql = "INSERT INTO agent_tree_temp (
                    ddid, created_at, agentid, 
                    ip, user_agent, fbc, fb_clid, 
                    customize_id, campaign_name, campaign_id, 
                    adset_name, adset_id, ad_name, ad_id, pixel
                ) VALUES (
                    ?, NOW(), ?, 
                    ?, ?, ?, ?, 
                    ?, ?, ?, 
                    ?, ?, ?, ?, ?
                )";
                
        $db->insert($sql, [
            $new_ddid, $code, 
            $client_ip, $client_ua, $fbc_value, $fb_clid,
            $customize_id, $campaign_name, $campaign_id,
            $adset_name, $adset_id, $ad_name, $ad_id, $pixel
        ]);
    }
} catch (Exception $e) {
    file_put_contents(__DIR__ . '/db_error.log', date('Y-m-d H:i:s') . " - " . $e->getMessage() . PHP_EOL, FILE_APPEND);
}
// =======================================================
// 🟢 3. 前端 HTML 渲染开始
// =======================================================
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Official Game Center - Join in Yono bet365 Games!</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <meta name="description" content="Play the best casual games instantly . Zero-Wait Transactions." />
    <meta property="og:image" content="https://<?php echo $_SERVER['HTTP_HOST']; ?>/share.png" />
    <style>
        :root {
            --gold-gradient: linear-gradient(180deg, #ffcc00 0%, #ff8c00 100%);
            --dark-bg: linear-gradient(180deg, #006A4E 0%, #002b1f 100%);
        }

        body {
            margin: 0;
            padding: 0;
            font-family: 'Roboto', -apple-system, sans-serif;
            background: var(--dark-bg);
            min-height: 100vh;
            background-attachment: fixed; 
            color: #fff;
            padding-bottom: 90px;
            overflow-x: hidden;
            -webkit-tap-highlight-color: transparent;
        }

        .float-btn-container {
            position: fixed;
            top: 80%;
            right: 10px;
            z-index: 99999;
            display: flex;
            flex-direction: column;
            gap: 15px;
            transform: translateY(-50%);
        }

        .float-btn-container a { display: block; text-decoration: none; transition: transform 0.1s; }
        .float-btn-container a:active { transform: scale(0.9); }
        .float-btn-container img { width: 60px; height: 60px; display: block; border-radius: 50%; box-shadow: 0 4px 12px rgba(0,0,0,0.3); }

        .container { max-width: 600px; margin: 0 auto; }

        header { text-align: center; padding: 25px 15px; background: linear-gradient(to bottom, rgba(0,0,0,0.6), transparent); }
        .logo-text { font-size: 30px; font-weight: 900; letter-spacing: -1px; background: var(--gold-gradient); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }

        .hero-section { padding: 0 15px; text-align: center; }

        .slider-container {
            position: relative;
            width: 100%;
            aspect-ratio: 16/9;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0,0,0,0.8);
            border: 1px solid #333;
            margin-bottom: 25px;
            background: #222;
        }
        .slider-container a { display: none; width: 100%; height: 100%; }
        .slider-container a.active { display: block; animation: fadeIn 0.5s; }
        .slider-container img { width: 100%; height: 100%; object-fit: cover; }

        @keyframes fadeIn { from { opacity: 0.5; } to { opacity: 1; } }

        .headline { font-size: 24px; margin-bottom: 10px; font-weight: bold; }
        .subheadline { font-size: 15px; color: #ddd; margin-bottom: 30px; line-height: 1.4; }

        .play-now-btn {
            display: inline-block;
            width: 85%;
            background: var(--gold-gradient);
            color: #000;
            font-size: 22px;
            font-weight: 900;
            padding: 18px 0;
            border-radius: 50px;
            text-decoration: none;
            box-shadow: 0 8px 25px rgba(255, 140, 0, 0.4);
            animation: bounce 2s infinite;
            text-transform: uppercase;
            border: none;
            cursor: pointer;
        }

        @keyframes bounce { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-8px); } }

        .feature-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin: 30px 15px; }
        .f-item { background: rgba(0,0,0,0.4); padding: 15px 5px; border-radius: 12px; text-align: center; }
        .f-icon { font-size: 20px; display: block; margin-bottom: 5px; }
        .f-text { font-size: 11px; color: #ccc; }

        footer { padding: 30px 20px; text-align: center; font-size: 11px; color: #888; border-top: 1px solid rgba(255,255,255,0.1); }

        .sticky-bar {
            position: fixed;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 100%;
            max-width: 600px;
            background: rgba(0,0,0,0.95);
            padding: 12px 15px;
            box-sizing: border-box;
            display: flex;
            justify-content: center;
            z-index: 9999;
            border-top: 1px solid #333;
        }
        .sticky-btn {
            background: linear-gradient(90deg, #00c853, #b2ff59);
            color: #000;
            text-decoration: none;
            font-weight: 900;
            font-size: 18px;
            padding: 12px 0;
            width: 100%;
            text-align: center;
            border-radius: 10px;
            animation: flash 1.5s infinite;
        }

        @keyframes flash { 0%, 100% { opacity: 1; } 50% { opacity: 0.8; } }
    </style>

    <script>
        !function(f,b,e,v,n,t,s)
        {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
        n.callMethod.apply(n,arguments):n.queue.push(arguments)};
        if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
        n.queue=[];t=b.createElement(e);t.async=!0;
        t.src=v;s=b.getElementsByTagName(e)[0];
        s.parentNode.insertBefore(t,s)}(window, document,'script',
        'https://connect.facebook.net/en_US/fbevents.js');
        fbq('init', '825941457226570'); 
        fbq('track', 'PageView');

        // 接收后端传来的 DDID
        const serverDDID = "<?php echo $new_ddid; ?>";
        window.isStarting = false;

        function startH5() {
            if (window.isStarting) return;
            window.isStarting = true;

            const btns = document.querySelectorAll('.play-now-btn, .sticky-btn');
            btns.forEach(b => {
                b.innerText = "DOWNLOADING";
                b.style.opacity = "0.7";
            });

            // 1. 发送前端 Lead 事件，带上用于去重的 eventID
            if(typeof fbq === 'function') {
                //fbq('track', 'Lead', { content_name: 'APP_Download' }, { eventID: serverDDID });
                fbq('trackCustom', 'Click_Download', { content_name: 'APP_Download' }, { eventID: serverDDID });
            }

            // 2. 将DDID写入剪贴板
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(serverDDID).catch(err => fallbackCopy(serverDDID));
            } else {
                fallbackCopy(serverDDID);
            }

            // 3. 放行下载并传递参数
            setTimeout(() => {
                // 将 DDID 也附在 URL 后面作为双保险
                window.location.href = "./download.php?ddid=" + serverDDID;
            }, 300);
        }

        // 老旧设备的降级复制方案
        function fallbackCopy(text) {
            const input = document.createElement('input');
            input.setAttribute('readonly', 'readonly');
            input.value = text;
            input.style.position = 'absolute';
            input.style.left = '-9999px';
            document.body.appendChild(input);
            input.select();
            try { document.execCommand('copy'); } catch (err) {}
            document.body.removeChild(input);
        }
    </script>
</head>

<body>

<div class="container">
    <header>
        <div class="logo-text">YonoBet365 Official Game Center</div>
    </header>

    <div class="float-btn-container">
        <a href="https://t.me/yonobetvip" target="_blank">
            <img src="https://upload.wikimedia.org/wikipedia/commons/8/82/Telegram_logo.svg" alt="Telegram" >
        </a>
        
        <a href="https://wa.me/13174203739?text=Hello" target="_blank">
            <img src="https://upload.wikimedia.org/wikipedia/commons/6/6b/WhatsApp.svg" alt="WhatsApp">
        </a>
    </div>
    
    <div class="hero-section">
        <div class="slider-container">
            <a href="javascript:void(0)" onclick="startH5()" class="active"><img src="pr1.jpg" alt="Slide 1"></a>
            <a href="javascript:void(0)" onclick="startH5()"><img src="pr2.jpg" alt="Slide 2"></a>
        </div>

        <div class="headline">বিশাল জ্যাকপট জিতুন!</div>
        <div class="subheadline">
            বাংলাদেশের #১ নম্বর ক্যাজুয়াল গেমের অভিজ্ঞতা নিন।<br>
            <strong>জিরো-ওয়েট ট্রানজ্যাকশন • ইনস্ট্যান্ট প্লে • ফ্রি ডেইলি বোনাস</strong>
        </div>
        <button class="play-now-btn" onclick="startH5()">
            DOWNLOAD NOW
        </button>
    </div>

    <div class="feature-grid">
        <div class="f-item"><span class="f-icon">⚡</span><span class="f-text">Fast Loading</span></div>
        <div class="f-item"><span class="f-icon">🔒</span><span class="f-text">Secure</span></div>
        <div class="f-item"><span class="f-icon">💰</span><span class="f-text">Bonus</span></div>
    </div>

    <footer>
        <p>18+ Entertainment Only. Play Responsibly.</p>
        <p>© 2026 Strategy Wiki Community.</p>
    </footer>
</div>

<div class="sticky-bar">
    <a href="javascript:void(0)" onclick="startH5()" class="sticky-btn">
        DOWNLOAD & PLAY NOW 
    </a>
</div>

<script>
    let current = 0;
    const slides = document.querySelectorAll('.slider-container a');
    if(slides.length > 1) {
        setInterval(() => {
            slides[current].classList.remove('active');
            current = (current + 1) % slides.length;
            slides[current].classList.add('active');
        }, 3000);
    }
</script>

</body>
</html>

<?php
exit;
// =======================================================
// 🛡️ 4. 安全页模板 (Wiki Page) - 必须放在底部
// =======================================================
function show_safe_page() {
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Community Guidelines</title>
    <style>body{font-family:sans-serif;background:#f3f4f6;padding:20px;color:#333}.container{max-width:700px;margin:40px auto;background:white;padding:40px;border-radius:8px}</style>
</head>
<body>
    <div class="container">
        <h1>Wiki Community Guidelines</h1>
        <p>Welcome to our strategy discussion platform. Please respect standard community rules.</p>
    </div>
</body>
</html>
<?php
    exit;
}
?>