<?php
require_once '../config.php';
$conn = require_once '../db.php';

$user_id = intval($_GET['user_id'] ?? 0);
if (!$user_id) exit("❌ Invalid user ID");

// ইউজার ডাটা
$stmt = $conn->prepare("SELECT first_name, username, total_balance, profile_photo_url FROM users WHERE chat_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
if (!$user) exit("❌ User not found");

function getRandomAd($conn) {
    return $conn->query("SELECT * FROM website_ads WHERE status=1 ORDER BY RAND() LIMIT 1")->fetch_assoc();
}

function sendTelegramNotification($chat_id, $message) {
    $bot_token = BOT_TOKEN; // আপনার config.php থেকে টোকেন আসবে
    $url = "https://api.telegram.org/bot{$bot_token}/sendMessage";

    $data = [
        'chat_id' => $chat_id,
        'text' => $message,
        'parse_mode' => 'HTML',
        'disable_web_page_preview' => true,
    ];

    $options = [
        'http' => [
            'header'  => "Content-Type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($data),
            'timeout' => 5,
        ],
    ];

    $context  = stream_context_create($options);
    @file_get_contents($url, false, $context);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'get_ad') {
    $ad = getRandomAd($conn);
    if ($ad) {
        echo json_encode([
            'success' => true,
            'ad' => $ad
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'No Ads available'
        ]);
    }
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'reward') {
    $ad_id = intval($_POST['ad_id'] ?? 0);
    if (!$ad_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid Ad']);
        exit;
    }

    // Fetch ad details
    $stmt = $conn->prepare("SELECT amount FROM website_ads WHERE id=? AND status=1");
    $stmt->bind_param("i", $ad_id);
    $stmt->execute();
    $ad_data = $stmt->get_result()->fetch_assoc();
    if (!$ad_data) {
        echo json_encode(['success' => false, 'message' => 'Ad not found or inactive']);
        exit;
    }

    $amount = floatval($ad_data['amount']);

    // Update user balance
    $stmt = $conn->prepare("UPDATE users SET total_balance = total_balance + ? WHERE chat_id = ?");
    $stmt->bind_param("di", $amount, $user_id);
    $stmt->execute();

    // Update total views of ad
    $stmt = $conn->prepare("UPDATE website_ads SET total_views = total_views + 1 WHERE id = ?");
    $stmt->bind_param("i", $ad_id);
    $stmt->execute();

    // Get updated balance
    $stmt = $conn->prepare("SELECT total_balance FROM users WHERE chat_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $updated_balance = $stmt->get_result()->fetch_assoc()['total_balance'];

    // Send Telegram notification
    $message = "🎉 আপনি এড ভিজিট করে ৳" . number_format($amount, 4) . " পেয়েছেন।\nআপনার বর্তমান ব্যালেন্স: ৳" . number_format($updated_balance, 4);
    sendTelegramNotification($user_id, $message);

    echo json_encode(['success' => true, 'amount' => $amount]);
    exit;
}

$ad = getRandomAd($conn);
?>

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8" />
  <title>Visit Task</title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <style>
    body { font-family: sans-serif; margin: 0; background: #f2f2f2; text-align: center; padding-bottom: 80px; }
    .profile { margin-top: 20px; }
    .profile img { width: 100px; height: 100px; border-radius: 50%; border: 3px solid #007bff; box-shadow: 0 5px 15px rgba(0,123,255,0.2); }
    .balance { font-size: 20px; color: #333; font-weight: bold; margin-top: 10px; margin-bottom: 20px; }
    .iframe-container { margin: 15px 10px; }
    iframe { width: 95%; height: 250px; border: 2px solid #ccc; border-radius: 10px; }
    .timer { font-size: 32px; margin: 20px auto; background: #222; color: #0f0; padding: 10px 25px; border-radius: 10px; width: fit-content; }
    .btn-next { padding: 15px 30px; font-size: 18px; background: #28a745; color: white; border: none; border-radius: 10px; display: none; margin-top: 20px; cursor: pointer; }
    .footer { position: fixed; bottom: 0; left: 0; right: 0; background: #007bff; color: white; text-align: center; padding: 12px; font-size: 14px; }
    
    
     /* ফুটার */
        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(--secondary-color); } /* হোমপেজের জন্য active ক্লাস */
        .nav-item-main {
            background: var(--secondary-color); color: var(--bg-dark); width: 60px; height: 60px;
            border-radius: 50%; display: flex; justify-content: center; align-items: center;
            transform: translateY(-25px); border: 5px solid var(--bg-dark);
        }
  </style>
</head>
<body>

<div class="profile">
  <img id="profilePhoto" src="<?= htmlspecialchars($user['profile_photo_url']) ?>" alt="Profile" />
  <div class="balance" id="balance">💰 ৳<?= number_format($user['total_balance'], 4) ?></div>
</div>

<div class="iframe-container">
  <iframe id="adFrame" src="<?= htmlspecialchars($ad['url']) ?>" frameborder="0"></iframe>
</div>

<div class="timer" id="countdown"><?= $ad['duration_sec'] ?></div>

<button id="doneBtn" class="btn-next">✅ NEXT TASK</button>


 <!-- অপ্রয়োজনীয় পেজের div গুলো মুছে দেওয়া হয়েছে -->

    <!-- ======================= ফুটার (লিঙ্কসহ আপডেট করা) ======================= -->
    <footer>
        <a href="index.php?user_id=<?php echo $user_id; ?>" class="active">🏠</a>
        <a href="wallet.php?user_id=<?php echo $user_id; ?>">💼</a>
        <a href="refer.php?user_id=<?php echo $user_id; ?>" class="nav-item-main">⇄</a>
        <a href="profile.php?user_id=<?php echo $user_id; ?>">👤</a>
        <a href="settings.php?user_id=<?php echo $user_id; ?>">⚙️</a>
    </footer>


<script>
  let countdownEl = document.getElementById('countdown');
  let doneBtn = document.getElementById('doneBtn');
  let adFrame = document.getElementById('adFrame');
  let balanceEl = document.getElementById('balance');

  let currentAdId = <?= $ad['id'] ?>;
  let seconds = <?= $ad['duration_sec'] ?>;
  let timerInterval;

  function startTimer(sec) {
    seconds = sec;
    countdownEl.innerText = seconds;
    doneBtn.style.display = 'none';

    timerInterval = setInterval(() => {
      seconds--;
      countdownEl.innerText = seconds;
      if (seconds <= 0) {
        clearInterval(timerInterval);
        countdownEl.innerText = "✅ Done!";
        doneBtn.style.display = 'inline-block';
      }
    }, 1000);
  }

  doneBtn.onclick = function () {
    fetch(window.location.href, {
      method: "POST",
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({
        action: 'reward',
        ad_id: currentAdId
      })
    })
    .then(res => res.json())
    .then(data => {
      if (data.success) {
        alert("✅ ৳" + data.amount + " Added to your balance");
        let currentBalance = parseFloat(balanceEl.textContent.replace(/[^\d\.]/g, ''));
        balanceEl.textContent = "💰 ৳" + (currentBalance + data.amount).toFixed(4);
        loadNextAd();
      } else {
        alert("❌ " + data.message);
      }
    });
  };

  function loadNextAd() {
    fetch(window.location.href, {
      method: "POST",
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({
        action: 'get_ad'
      })
    })
    .then(res => res.json())
    .then(data => {
      if (data.success) {
        currentAdId = data.ad.id;
        adFrame.src = data.ad.url;
        startTimer(data.ad.duration_sec);
      } else {
        alert("No more ads available");
      }
    });
  }

  startTimer(seconds);
</script>

</body>
</html>