<?php
session_start();
require_once '../config.php'; // আপনার বট টোকেন এই ফাইলে থাকতে হবে
$conn = require_once '../db.php';

// ==========================================================
//  টেলিগ্রাম মেসেজ পাঠানোর জন্য ফাংশন
// ==========================================================
function sendTelegramMessage($botToken, $chatId, $message) {
    $url = "https://api.telegram.org/bot{$botToken}/sendMessage";
    $post_fields = [
        'chat_id' => $chatId,
        'text' => $message,
        'parse_mode' => 'HTML' // আপনি চাইলে Markdown ব্যবহার করতে পারেন
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_fields));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

// --- আপনার মূল PHP লজিক অপরিবর্তিত রাখা হয়েছে ---

// Load project_id and ad_amount from ads_settings
$conn->query("CREATE TABLE IF NOT EXISTS ads_settings (
    id INT PRIMARY KEY,
    project_id VARCHAR(50) NOT NULL,
    ad_amount DECIMAL(10,3) NOT NULL DEFAULT 0.008
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
$conn->query("INSERT IGNORE INTO ads_settings (id, project_id, ad_amount) VALUES (1, '1107', 0.008)");

$res = $conn->query("SELECT project_id, ad_amount FROM ads_settings WHERE id = 1 LIMIT 1");
$settings = $res->fetch_assoc() ?? ['project_id' => '1107', 'ad_amount' => 0.008];

// POST: Ad watched
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    $input = json_decode(file_get_contents("php://input"), true);
    $chat_id = intval($input['user_id'] ?? 0);
    $ad_id = $input['ad_id'] ?? 'default_ad';
    $amount = floatval($settings['ad_amount']);

    if (!$chat_id) exit(json_encode(['success' => false]));

    // Create user if not exists
    $stmt = $conn->prepare("SELECT id FROM users WHERE chat_id = ?");
    $stmt->bind_param("i", $chat_id);
    $stmt->execute();
    $res = $stmt->get_result();

    if ($res->num_rows === 0) {
        $stmt = $conn->prepare("INSERT INTO users (chat_id, first_name) VALUES (?, 'User')");
        $stmt->bind_param("i", $chat_id);
        $stmt->execute();
    }

    // Update user balance
    $stmt = $conn->prepare("UPDATE users SET total_balance = total_balance + ?, total_ads_watched = total_ads_watched + 1 WHERE chat_id = ?");
    $stmt->bind_param("di", $amount, $chat_id);
    
    if ($stmt->execute()) {
        // --- নোটিফিকেশন পাঠানোর নতুন কোড ---
        
        // প্রথমে নতুন ব্যালেন্স ডাটাবেস থেকে নিন
        $stmt_new_balance = $conn->prepare("SELECT total_balance FROM users WHERE chat_id = ?");
        $stmt_new_balance->bind_param("i", $chat_id);
        $stmt_new_balance->execute();
        $new_user_data = $stmt_new_balance->get_result()->fetch_assoc();
        $new_total_balance = $new_user_data['total_balance'] ?? 0;
        
        // মেসেজ তৈরি করুন
        $earned_amount_formatted = number_format($amount, 3);
        $total_balance_formatted = number_format($new_total_balance, 3);
        
        $message = "✅ <b>GIGA PUB টাস্ক সফল হয়েছে।</b>\n\n";
        $message .= "আপনি <b>৳{$earned_amount_formatted}</b> পেয়েছেন।\n";
        $message .= "আপনার মোট ব্যালেন্স এখন <b>৳{$total_balance_formatted}</b> টাকা।";

        // config.php থেকে বট টোকেন নিয়ে মেসেজ পাঠান
        if (defined('BOT_TOKEN')) {
            sendTelegramMessage(BOT_TOKEN, $chat_id, $message);
        }
        
        echo json_encode(['success' => true, 'amount' => $amount]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Database update failed.']);
    }
    exit;
}

// GET: Show user info
$chat_id = intval($_GET['user_id'] ?? 0);
if (!$chat_id) die("User ID is missing in the URL!");

$stmt = $conn->prepare("SELECT first_name, total_balance, total_ads_watched FROM users WHERE chat_id = ?");
$stmt->bind_param("i", $chat_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
if (!$user) {
    $stmt = $conn->prepare("INSERT INTO users (chat_id, first_name) VALUES (?, 'User')");
    $stmt->bind_param("i", $chat_id);
    $stmt->execute();
    $user = ['first_name' => 'User', 'total_balance' => 0, 'total_ads_watched' => 0];
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>GIGA PUB</title>
    <!-- আগের সব CSS এবং স্ক্রিপ্ট ট্যাগ এখানে থাকবে -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;600;700&display=swap" rel="stylesheet">
    <script src="https://telegram.org/js/telegram-web-app.js"></script>
    <script src="https://ad.gigapub.tech/script?id=<?= htmlspecialchars($settings['project_id']) ?>"></script>
    <style>
        :root {
            --bg-dark: #0d1b2a;
            --bg-card: #1c2a4a;
            --primary-color: #00aaff;
            --secondary-color: #ffc300;
            --text-light: #ffffff;
            --text-muted: #b0c4de;
        }
        @property --angle {
          syntax: "<angle>";
          initial-value: 0deg;
          inherits: false;
        }
        @keyframes spin {
          to { --angle: 360deg; }
        }

        body {
            margin: 0;
            font-family: 'Hind Siliguri', sans-serif;
            background-color: var(--bg-dark);
            color: var(--text-light);
            padding: 15px 15px 100px 15px; /* ফুটারের জন্য নিচে জায়গা রাখা হয়েছে */
        }

        .app-container {
            max-width: 400px;
            margin: 0 auto;
            width: 100%;
        }

        .brand-section {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 25px;
        }
        .brand-logo {
            width: 45px; height: 45px; background-color: var(--secondary-color);
            border-radius: 50%; display: flex; justify-content: center; align-items: center;
        }
        .brand-logo i { color: var(--bg-dark); font-size: 20px; }
        .brand-info h1 { margin: 0; font-size: 26px; color: var(--primary-color); font-weight: 700; line-height: 1.1; }
        .brand-info p { margin: 0; font-size: 14px; color: var(--text-muted); }

        .animated-border {
            position: relative;
            background-clip: padding-box;
            border: 2px solid transparent;
        }
        .animated-border::before {
            content: ''; position: absolute; top: 0; left: 0; right: 0; bottom: 0;
            margin: -2px;
            background: conic-gradient(from var(--angle), var(--primary-color), #ff2dff, #39ff14, var(--secondary-color), var(--primary-color));
            animation: spin 4s linear infinite;
            z-index: -1;
        }

        .balance-card {
            background-color: #1e3a8a;
            border-radius: 20px;
            padding: 25px;
            text-align: center;
            margin-bottom: 20px;
        }
        .balance-card::before { border-radius: 22px; }
        .balance-card .title { font-size: 16px; color: var(--text-muted); margin: 0 0 5px 0; }
        .balance-card .amount { font-size: 48px; font-weight: 700; margin: 0 0 15px 0; line-height: 1.2; }
        .balance-card .per-ad-income {
            background-color: rgba(0, 0, 0, 0.2); display: inline-block;
            padding: 6px 15px; border-radius: 15px; font-size: 13px;
        }

        .stats-container { display: flex; gap: 15px; margin-bottom: 30px; }
        .stat-box {
            flex: 1; background-color: var(--bg-card); border-radius: 15px;
            padding: 20px; text-align: center;
        }
        .stat-box::before { border-radius: 17px; }
        .stat-box .icon { font-size: 24px; color: var(--primary-color); margin-bottom: 10px; }
        .stat-box .label { font-size: 14px; color: var(--text-muted); margin: 0 0 5px 0; }
        .stat-box .value { font-size: 24px; font-weight: 600; margin: 0; }

        .action-button {
            width: 100%; padding: 16px; background-color: var(--primary-color);
            color: var(--text-light); border: none; border-radius: 15px;
            font-size: 18px; font-weight: 600; cursor: pointer;
            display: flex; justify-content: center; align-items: center; gap: 10px;
            transition: background-color 0.3s, transform 0.2s;
        }
        .action-button:active { transform: scale(0.98); background-color: #0088cc; }
        .action-button:disabled { background-color: #555; cursor: not-allowed; }

        .toast {
            position: fixed; top: 20px; left: 50%; transform: translateX(-50%);
            background: #4caf50; padding: 10px 20px; border-radius: 8px;
            font-weight: 600; display: none; z-index: 1000;
        }

        footer {
            position: fixed; bottom: 0; left: 0; right: 0; background: var(--bg-card);
            display: flex; justify-content: space-around; align-items: center;
            padding: 10px 0; border-top-left-radius: 25px; border-top-right-radius: 25px;
            box-shadow: 0 -5px 20px rgba(0,0,0,0.2);
        }
        footer a { color: var(--text-muted); text-decoration: none; font-size: 24px; }
        footer a.active { color: var(--primary-color); }
        .nav-item-main {
            background: var(--primary-color); color: var(--bg-dark); width: 60px; height: 60px;
            border-radius: 50%; display: flex; justify-content: center; align-items: center;
            font-size: 30px; transform: translateY(-25px); border: 5px solid var(--bg-dark);
        }
    </style>
</head>
<body>
    <div class="app-container">
        <!-- Brand Section - নাম পরিবর্তন করা হয়েছে -->
        <div class="brand-section">
            <div class="brand-logo"> <i class="fas fa-play"></i> </div>
            <div class="brand-info">
                <h1>GIGA PUB</h1>
                <p>বিজ্ঞাপন দেখুন, অর্থ উপার্জন করুন</p>
            </div>
        </div>

        <!-- বাকি HTML আগের মতোই থাকবে -->
        <div class="balance-card animated-border">
            <p class="title">total balance</p>
            <h2 class="amount">৳<?= number_format($user['total_balance'], 2) ?></h2>
            <div class="per-ad-income">প্রতি বিজ্ঞাপনে আয়: ৳<?= number_format($settings['ad_amount'], 3) ?></div>
        </div>

        <div class="stats-container">
            <div class="stat-box animated-border">
                <div class="icon"><i class="fas fa-desktop"></i></div>
                <p class="label">মোট বিজ্ঞাপন</p>
                <p class="value"><?= number_format($user['total_ads_watched']) ?></p>
            </div>
            <div class="stat-box animated-border">
                <div class="icon"><i class="fas fa-coins"></i></div>
                <p class="label">মোট আয়</p>
                <p class="value">৳<?= number_format($user['total_balance'], 2) ?></p>
            </div>
        </div>

        <div class="action-button-container">
            <button class="action-button" onclick="watchAd(<?= $chat_id ?>)">
                <i class="fas fa-play"></i>
                বিজ্ঞাপন দেখুন
            </button>
        </div>
    </div>

    <div id="toast" class="toast"></div>

    <footer>
        <a href="index.php?user_id=<?= htmlspecialchars($chat_id) ?>" class="active"><i class="fas fa-home"></i></a>
        <a href="wallet.php?user_id=<?= htmlspecialchars($chat_id) ?>"><i class="fas fa-wallet"></i></a>
        <a href="refer.php?user_id=<?= htmlspecialchars($chat_id) ?>" class="nav-item-main"><i class="fas fa-retweet"></i></a>
        <a href="profile.php?user_id=<?= htmlspecialchars($chat_id) ?>"><i class="fas fa-user"></i></a>
        <a href="settings.php?user_id=<?= htmlspecialchars($chat_id) ?>"><i class="fas fa-cog"></i></a>
    </footer>

    <script>
        // আগের জাভাস্ক্রিপ্ট কোড অপরিবর্তিত
        const tg = window.Telegram.WebApp;
        tg.ready();
        tg.expand();

        function showToast(msg) {
            const t = document.getElementById('toast');
            t.innerText = msg;
            t.style.display = 'block';
            setTimeout(() => t.style.display = 'none', 2500);
        }

        function watchAd(userId) {
            if (typeof window.showGiga !== 'function') {
                alert("বিজ্ঞাপন লোড হয়নি। অনুগ্রহ করে কিছুক্ষণ পর চেষ্টা করুন।");
                return;
            }

            const btn = document.querySelector('.action-button');
            btn.innerText = "লোড হচ্ছে...";
            btn.disabled = true;

            window.showGiga().then(res => {
                const adId = res?.adId || 'default_ad';

                fetch(location.href, {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ user_id: userId, ad_id: adId })
                }).then(res => res.json()).then(data => {
                    if (data.success) {
                        showToast("সফলভাবে আয় হয়েছে: ৳" + data.amount.toFixed(3));
                        setTimeout(() => location.reload(), 1500);
                    } else {
                        showToast("দুঃখিত, একটি সমস্যা হয়েছে।");
                        btn.disabled = false;
                        btn.innerHTML = `<i class="fas fa-play"></i> বিজ্ঞাপন দেখুন`;
                    }
                });
            }).catch(() => {
                alert("বিজ্ঞাপনটি বাতিল করা হয়েছে।");
                btn.disabled = false;
                btn.innerHTML = `<i class="fas fa-play"></i> বিজ্ঞাপন দেখুন`;
            });
        }
    </script>
</body>
</html>