<?php
require_once 'db.php';
require_once 'auth_check.php';
require_once 'currency.php';
require_once 'commission_helper.php'; // ← ADD THIS LINE

$_sup = $conn->query("SELECT key_value FROM settings WHERE key_name='support_url'")->fetch_assoc();
$support_url = $_sup['key_value'] ?? '#';

$plan_slug = trim($_GET['plan'] ?? '');
$video_id  = (int)($_GET['video'] ?? 0);
$autoplay  = !empty($_GET['autoplay']);

$plan = null;
if ($plan_slug) {
    $plan = $conn->query("SELECT * FROM plans WHERE slug='" . $conn->real_escape_string($plan_slug) . "' AND active=1")->fetch_assoc();
}
if (!$plan && $active_plan) $plan = $active_plan;

$has_access   = false;
$plan_expired = false;
if ($plan) {
    $pid = (int)$plan['id'];
    $row = $conn->query("SELECT id FROM user_plans WHERE user_id=$user_id AND plan_id=$pid AND active=1 AND (expires_at IS NULL OR expires_at>NOW())")->fetch_assoc();
    if ($row) {
        $has_access = true;
    } else {
        $exp = $conn->query("SELECT id FROM user_plans WHERE user_id=$user_id AND plan_id=$pid AND active=1 AND expires_at IS NOT NULL AND expires_at<=NOW()")->fetch_assoc();
        if ($exp) $plan_expired = true;
    }
}

$today_done = 0;
if ($plan && $has_access) {
    $pid = (int)$plan['id'];
    $r = $conn->query("SELECT COUNT(*) as c FROM task_completions WHERE user_id=$user_id AND plan_id=$pid AND DATE(completed_at)=CURDATE()")->fetch_assoc();
    $today_done = (int)$r['c'];
}

// ── AJAX: complete video ─────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['complete_video'])) {
    header('Content-Type: application/json');
    $vid = (int)$_POST['complete_video'];
    $pid = (int)$_POST['plan_id'];

    $access_row = $conn->query("SELECT id FROM user_plans WHERE user_id=$user_id AND plan_id=$pid AND active=1 AND (expires_at IS NULL OR expires_at>NOW())")->fetch_assoc();
    if (!$access_row) { echo json_encode(['status'=>'error','msg'=>'No active plan.']); exit; }

    $vrow = $conn->query("SELECT * FROM plan_videos WHERE id=$vid AND plan_id=$pid AND active=1")->fetch_assoc();
    $prow = $conn->query("SELECT * FROM plans WHERE id=$pid")->fetch_assoc();

    if ($vrow && $prow) {
        $daily_tasks = $prow['daily_tasks'];
        $done_today  = (int)$conn->query("SELECT COUNT(*) as c FROM task_completions WHERE user_id=$user_id AND plan_id=$pid AND DATE(completed_at)=CURDATE()")->fetch_assoc()['c'];
        if ($done_today >= $daily_tasks) {
            echo json_encode(['status'=>'error','msg'=>'Daily limit reached. Come back tomorrow!']);
        } else {
            $earn = $vrow['earn_amount'] > 0 ? $vrow['earn_amount'] : $prow['per_order'];

            // ── Insert task completion record ──
            $conn->query("INSERT INTO task_completions (user_id,video_id,plan_id,earned) VALUES ($user_id,$vid,$pid,$earn)");

            // ── Credit earned amount to user balance ──
            $conn->query("UPDATE users SET balance = balance + $earn, total_earned = total_earned + $earn WHERE id = $user_id");

            // ── Log to account_logs ──
            $desc = $conn->real_escape_string('Task reward: ' . ($vrow['title'] ?? 'Video'));
            $conn->query("INSERT INTO account_logs (user_id,type,category,amount,description) VALUES ($user_id,'income','task',$earn,'$desc')");

            // ── Pay task commissions to upliners (L1, L2, L3) ── ← NEW
            payTaskCommissions($conn, $user_id, $pid, (float)$earn, $vrow['title'] ?? '');

            // Count updated remaining
            $new_done      = $done_today + 1;
            $new_remaining = max(0, (int)$prow['daily_tasks'] - $new_done);

            // Get fresh balance
            $new_balance = (float)$conn->query("SELECT balance FROM users WHERE id=$user_id")->fetch_assoc()['balance'];

            echo json_encode([
                'status'        => 'ok',
                'earned'        => $earn,
                'currency'      => $currency,
                'new_done'      => $new_done,
                'new_remaining' => $new_remaining,
                'new_balance'   => number_format($new_balance, 2),
            ]);
        }
    } else {
        echo json_encode(['status'=>'error','msg'=>'Invalid video.']);
    }
    exit;
}

$videos = [];
if ($plan && $has_access) {
    $pid = (int)$plan['id'];
    $videos = $conn->query("SELECT * FROM plan_videos WHERE plan_id=$pid AND active=1 ORDER BY id ASC")->fetch_all(MYSQLI_ASSOC);
}

$autoplay_video = null;
if ($autoplay && $video_id && $plan && $has_access) {
    $pid = (int)$plan['id'];
    $autoplay_video = $conn->query("SELECT * FROM plan_videos WHERE id=$video_id AND plan_id=$pid AND active=1")->fetch_assoc();
}

$all_plans = $conn->query("SELECT * FROM plans WHERE active=1 ORDER BY sort_order ASC")->fetch_all(MYSQLI_ASSOC);
$tasks_remaining = $plan ? max(0, (int)$plan['daily_tasks'] - $today_done) : 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>WFM - Task List</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Segoe UI',sans-serif;background:linear-gradient(160deg,#b8cba8 0%,#a8bc96 40%,#8faa7a 100%);min-height:100vh;padding-bottom:72px}

/* ── Top Bar ── */
.top-bar{display:flex;align-items:center;justify-content:center;padding:16px 16px 12px}
.top-bar h1{font-size:18px;font-weight:700;color:#1a2a0a;text-align:center}

/* ── Stats Bar ── */
.stats-bar{display:flex;background:#fff;border-bottom:1px solid #eee}
.stat-box{flex:1;text-align:center;padding:18px 10px;border-right:1px solid #eee}
.stat-box:last-child{border-right:none}
.stat-box .sv{font-size:32px;font-weight:800;color:#3eaabb;line-height:1}
.stat-box .sl{font-size:13px;font-weight:600;color:#3eaabb;margin-top:8px}

/* ── Video Grid ── */
.video-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:10px;padding:10px}

/* ── Video Card ── */
.video-card{
  position:relative;
  border-radius:0;
  overflow:hidden;
  cursor:pointer;
  background:#111;
  aspect-ratio:9/13;
  box-shadow:none
}
.video-card img.cover{
  width:100%;height:100%;
  object-fit:cover;display:block;
  transition:transform .2s
}
.video-card:active img.cover{transform:scale(0.98)}

/* Plan badge — top left */
.plan-badge{
  position:absolute;top:8px;left:8px;
  background:#e74c3c;color:#fff;
  font-size:11px;font-weight:700;
  padding:3px 9px;border-radius:4px;
  z-index:2;letter-spacing:.2px
}
.plan-badge.done-badge{background:#27ae60}

/* ── Bottom bar ── */
.card-bottom{
  position:absolute;bottom:0;left:0;right:0;
  background:rgba(0,0,0,0.48);
  display:flex;align-items:center;justify-content:space-between;
  padding:5px 8px;
  z-index:2
}
.card-play{
  width:20px;height:20px;
  border:1.5px solid rgba(255,255,255,.85);
  border-radius:50%;
  display:flex;align-items:center;justify-content:center;
  flex-shrink:0
}
.card-play svg{width:10px;height:10px;fill:#fff;margin-left:1px}
.card-earn{
  font-size:11px;font-weight:700;
  color:#fff;letter-spacing:.2px
}

/* No access blocks */
.info-block{margin:20px 12px;background:rgba(255,255,255,.75);border-radius:16px;padding:30px 20px;text-align:center}
.info-block p{font-size:14px;color:#555;margin-bottom:14px;line-height:1.5}
.info-block a{background:linear-gradient(90deg,#3ecf8e,#2c7be5);color:#fff;padding:11px 30px;border-radius:30px;text-decoration:none;font-weight:700;font-size:14px;display:inline-block}
.info-block .warn{font-size:30px;margin-bottom:10px}

/* ── Video Modal (bottom sheet) ── */
#video-modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.88);z-index:9000;align-items:flex-end;justify-content:center}
#video-modal.open{display:flex}
.bottom-nav{position:fixed;bottom:0;left:0;right:0;height:64px;background:#fff;border-top:1px solid #e0e0e0;display:flex;align-items:center;justify-content:space-around;z-index:1000}
.vm-sheet{width:100%;max-width:600px;background:#fff;border-radius:20px 20px 0 0;overflow:hidden;padding-bottom:calc(64px + env(safe-area-inset-bottom, 0px))}

.vm-video-wrap{position:relative;background:#000;width:100%;overflow:hidden}
#video-player{
  width:100%;
  height:220px;
  display:block;
  background:#000;
  object-fit:contain;
  object-position:center
}

/* Info section */
.vm-info{padding:10px 12px 0;background:#fff}
.vm-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:10px}
.vm-cell{background:#f7f9f7;border-radius:10px;padding:10px 12px}

/* Video Name row */
.vm-label{font-size:14px;font-weight:700;color:#1a1a1a;margin-bottom:2px}
.vm-value{font-size:13px;color:#555;margin-bottom:12px;line-height:1.4}

/* Task Requirements + Reward */
.vm-req-row{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;margin-bottom:0;padding-bottom:14px}
.vm-req-left{flex:1}
.vm-req-left .vm-label{margin-bottom:4px}
.vm-listen-line{font-size:13px;color:#444;margin-bottom:4px;line-height:1.4}
.vm-listened-line{font-size:13px;color:#444;line-height:1.4}

/* Reward Amount box */
.vm-reward{text-align:right;flex-shrink:0}
.vm-reward .vm-label{margin-bottom:6px}
.vm-reward-amt{font-size:22px;font-weight:800;color:#27ae60;letter-spacing:.5px}

/* Divider */
.vm-divider{height:1px;background:#eee;margin:0}

/* Bottom buttons */
.vm-btns{
  display:flex;gap:10px;
  padding:14px 16px 20px;
  background:linear-gradient(180deg,#e8f0e0,#d4e8c8)
}
.vm-btn-reset{
  flex:1;padding:14px;
  background:linear-gradient(90deg,#e74c3c,#c0392b);color:#fff;
  border:none;border-radius:30px;
  font-size:14px;font-weight:600;
  cursor:pointer;font-family:inherit
}
.vm-btn-complete{
  flex:1;padding:14px;
  background:linear-gradient(90deg,#2196f3,#1976d2);
  color:#fff;border:none;border-radius:30px;
  font-size:14px;font-weight:700;
  cursor:pointer;font-family:inherit;
  transition:opacity .2s;
  box-shadow:0 4px 14px rgba(33,150,243,.4)
}
.vm-btn-complete:disabled{
  background:#a0b8d0;
  box-shadow:none;cursor:not-allowed
}

/* ── Daily Limit Popup ── */
#limit-popup{
  display:none;
  position:fixed;inset:0;
  z-index:99999;
  background:rgba(0,0,0,.80);
  align-items:center;justify-content:center
}
#limit-popup.show{display:flex}
.limit-popup-box{
  background:linear-gradient(160deg,#1a1a2e,#16213e,#0f3460);
  border-radius:24px;
  padding:36px 28px 28px;
  text-align:center;
  width:86%;max-width:320px;
  border:1.5px solid rgba(255,255,255,.12);
  box-shadow:0 20px 60px rgba(0,0,0,.5);
  animation:popIn .4s cubic-bezier(.22,.68,0,1.3)
}
.limit-popup-icon{font-size:62px;margin-bottom:10px;animation:swing 1s ease infinite alternate}
@keyframes swing{from{transform:rotate(-10deg)}to{transform:rotate(10deg)}}
.limit-popup-title{
  font-size:20px;font-weight:800;color:#FFD700;
  margin-bottom:10px;text-shadow:0 2px 8px rgba(255,215,0,.3)
}
.limit-popup-msg{
  font-size:14px;color:rgba(255,255,255,.80);
  line-height:1.7;margin-bottom:14px
}
.limit-popup-badge{
  font-size:13px;color:#FFD700;font-weight:700;
  background:rgba(255,215,0,.1);
  border:1px solid rgba(255,215,0,.25);
  border-radius:20px;padding:7px 18px;
  margin-bottom:20px;display:inline-block
}
.limit-popup-btn{
  background:linear-gradient(90deg,#FFD700,#f39c12);
  color:#1a1a2e;border:none;border-radius:30px;
  padding:14px 32px;font-size:15px;font-weight:800;
  cursor:pointer;font-family:inherit;
  box-shadow:0 4px 18px rgba(255,215,0,.4);
  width:100%;letter-spacing:.3px
}

/* ── Earn Popup (success overlay) ── */
#earn-popup{
  display:none;
  position:fixed;inset:0;
  z-index:99999;
  background:rgba(0,0,0,.72);
  align-items:center;justify-content:center
}
#earn-popup.show{display:flex}
.earn-popup-box{
  background:#fff;
  border-radius:24px;
  padding:36px 28px 28px;
  text-align:center;
  width:86%;max-width:320px;
  animation:popIn .4s cubic-bezier(.22,.68,0,1.3)
}
@keyframes popIn{from{transform:scale(.7);opacity:0}to{transform:scale(1);opacity:1}}
.earn-popup-icon{
  font-size:56px;
  margin-bottom:10px;
  animation:bounce .6s ease infinite alternate
}
@keyframes bounce{from{transform:translateY(0)}to{transform:translateY(-8px)}}
.earn-popup-title{
  font-size:15px;font-weight:700;color:#555;
  margin-bottom:8px;text-transform:uppercase;letter-spacing:.5px
}
.earn-popup-amount{
  font-size:42px;font-weight:900;
  color:#27ae60;
  margin-bottom:6px;
  line-height:1
}
.earn-popup-currency{
  font-size:14px;color:#888;font-weight:500;
  margin-bottom:24px
}
.earn-popup-btn{
  background:linear-gradient(90deg,#27ae60,#2ecc71);
  color:#fff;border:none;border-radius:30px;
  padding:13px 40px;font-size:15px;font-weight:700;
  cursor:pointer;font-family:inherit;
  box-shadow:0 4px 14px rgba(39,174,96,.4);
  width:100%
}

/* Toast */
.toast{position:fixed;top:20px;left:50%;transform:translateX(-50%) translateY(-80px);background:#1a2a0a;color:#fff;padding:10px 24px;border-radius:30px;font-size:13px;font-weight:600;z-index:9999;transition:transform .3s;white-space:nowrap;box-shadow:0 4px 20px rgba(0,0,0,.3)}
.toast.show{transform:translateX(-50%) translateY(0)}
.toast.err{background:#c0392b}
.toast.ok{background:#27ae60}

.float-service{position:fixed;bottom:80px;right:10px;display:flex;flex-direction:column;align-items:center;z-index:999;text-decoration:none}
.float-service img{width:52px;height:52px;border-radius:50%;object-fit:cover}
.float-service span{font-size:10px;color:#3a5a2a;font-weight:600;text-align:center;margin-top:2px}

.bn-item{display:flex;flex-direction:column;align-items:center;gap:3px;text-decoration:none;flex:1;padding:6px 0}
.bn-item svg{width:22px;height:22px}
.bn-item span{font-size:10px;font-weight:600}
.bn-item.active span,.bn-item.active svg{color:#3eaabb}
.bn-item:not(.active) span,.bn-item:not(.active) svg{color:#aaa}
</style>
</head>
<body>

<!-- Top Bar -->
<div class="top-bar">
  <h1>Task List</h1>
</div>

<?php if ($plan && $has_access): ?>
<div class="stats-bar">
  <div class="stat-box">
    <div class="sv" id="stat-remaining"><?= $tasks_remaining ?></div>
    <div class="sl">Tasks Remaining Today</div>
  </div>
  <div class="stat-box">
    <div class="sv" id="stat-done"><?= $today_done ?></div>
    <div class="sl">Tasks Completed Today</div>
  </div>
</div>
<?php endif; ?>

<?php if (!$plan): ?>
  <div class="info-block"><div class="warn">🎵</div><p>Join a plan to start completing tasks.</p><a href="job.php">Browse Plans</a></div>
<?php elseif ($plan_expired): ?>
  <div class="info-block"><div class="warn">⏰</div><p>Your <strong><?= htmlspecialchars($plan['name']) ?></strong> plan has expired.</p><a href="job.php">View Plans</a></div>
<?php elseif (!$has_access): ?>
  <div class="info-block"><div class="warn">🔒</div><p>You don't have an active plan.<br>Join to watch videos and earn.</p><a href="job.php">Join a Plan</a></div>
<?php elseif (empty($videos)): ?>
  <div class="info-block"><div class="warn">📹</div><p>No videos yet for <strong><?= htmlspecialchars($plan['name']) ?></strong>.<br>Check back soon!</p></div>
<?php else: ?>

<div class="video-grid">
  <?php foreach($videos as $v):
    $earn  = $v['earn_amount'] > 0 ? $v['earn_amount'] : $plan['per_order'];
    $cover = $v['cover_img'] ?: 'https://eoproject.com/music/10652_905027_905027_Out_of_Flux_-_The_Great_Wild_-_A.jpg';
    $limit_js = ($today_done >= (int)$plan['daily_tasks']) ? 'true' : 'false';
    $onclick = "openVideo({$v['id']},'" . addslashes(htmlspecialchars($v['video_url'])) . "','" . addslashes(htmlspecialchars($v['title'])) . "','" . number_format($earn,3) . "',{$plan['id']},$limit_js)";
  ?>
  <div class="video-card" onclick="<?= $onclick ?>" id="vc-<?= $v['id'] ?>">
    <img src="<?= htmlspecialchars($cover) ?>" class="cover" alt=""
         onerror="this.src='https://via.placeholder.com/300'">

    <div class="plan-badge">
      <?= htmlspecialchars($plan['name']) ?>
    </div>

    <div class="card-bottom">
      <div class="card-play">
        <svg viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg>
      </div>
      <span class="card-earn"><?= $currency ?> +<?= number_format($earn,3) ?></span>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<?php endif; ?>

<!-- ── Video Modal ── -->
<div id="video-modal">
  <div class="vm-sheet">

    <div class="vm-video-wrap">
      <video id="video-player" controls playsinline webkit-playsinline></video>
    </div>

    <div class="vm-info">
      <div class="vm-grid">
        <div class="vm-cell">
          <div class="vm-label">Video Name</div>
          <div class="vm-value" id="vm-title">—</div>
        </div>
        <div class="vm-cell">
          <div class="vm-label">Video Introduction</div>
          <div class="vm-value" id="vm-intro">Music Task</div>
        </div>
        <div class="vm-cell">
          <div class="vm-label">Task Requirements</div>
          <div class="vm-listen-line">Listen for <strong>3 seconds</strong></div>
          <div class="vm-listened-line" id="vm-listened">Currently listened for <strong>0</strong> seconds</div>
        </div>
        <div class="vm-cell">
          <div class="vm-label">Reward Amount</div>
          <div class="vm-reward-amt">+<span id="vm-earn">0.000</span> $</div>
        </div>
      </div>
    </div>

    <div class="vm-divider"></div>

    <div class="vm-btns">
      <button class="vm-btn-reset" onclick="resetVideo()">Reset Task</button>
      <button class="vm-btn-complete" id="vm-complete-btn" disabled onclick="completeTask()">Complete</button>
    </div>

  </div>
</div>

<!-- ── Daily Limit Popup ── -->
<div id="limit-popup">
  <div class="limit-popup-box">
    <div class="limit-popup-icon">⏰</div>
    <div class="limit-popup-title">Daily Limit Reached!</div>
    <div class="limit-popup-msg">You have completed all your tasks for today.<br>Come back tomorrow to earn more!</div>
    <div class="limit-popup-badge">🌟 Great work today! 🌟</div>
    <button class="limit-popup-btn" onclick="closeLimitPopup()">OK, See You Tomorrow!</button>
  </div>
</div>

<!-- ── Earn Popup ── -->
<div id="earn-popup">
  <div class="earn-popup-box">
    <div class="earn-popup-icon">🎉</div>
    <div class="earn-popup-title">Task Completed!</div>
    <div class="earn-popup-amount" id="popup-amount">0.000</div>
    <div class="earn-popup-currency" id="popup-currency">Earned</div>
    <button class="earn-popup-btn" onclick="closeEarnPopup()">✓ Awesome!</button>
  </div>
</div>

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

<a href="<?= htmlspecialchars($support_url) ?>" target="_blank" class="float-service">
  <img src="care.png" alt="" onerror="this.style.display='none'">
  <span>Online Service</span>
</a>

<?php include 'navigation_bottom.php'; ?>

<script>
const REQUIRED = 3;
let _tasksRemaining = <?= $tasks_remaining ?>;
let _vid=null, _pid=null, _earn=null;
let _timer=null, _secsLeft=REQUIRED, _secsWatched=0;

function openVideo(vid, url, title, earn, pid, limitReached) {
  if (limitReached || _tasksRemaining <= 0) { showLimitPopup(); return; }
  _vid = vid; _pid = pid; _earn = earn;
  document.getElementById('vm-title').textContent = title;
  document.getElementById('vm-earn').textContent  = earn;
  _secsWatched = 0;
  updateListened();
  resetCountdown();
  document.getElementById('video-modal').classList.add('open');
  const player = document.getElementById('video-player');
  if (url) { player.src = url; player.play().catch(() => {}); }
  startCountdown();
}

function updateListened() {
  const el = document.getElementById('vm-listened');
  if (el) el.innerHTML = 'Currently listened for <strong>' + _secsWatched + '</strong> seconds';
}

function resetCountdown() {
  clearInterval(_timer);
  _secsLeft = REQUIRED;
  _secsWatched = 0;
  updateListened();
  const btn = document.getElementById('vm-complete-btn');
  btn.disabled = true;
  btn.style.background = '';
  btn.style.boxShadow  = '';
  btn.textContent = 'Complete';
}

function startCountdown() {
  clearInterval(_timer);
  _timer = setInterval(() => {
    const player = document.getElementById('video-player');
    if (player.paused || player.ended) return;
    _secsWatched++;
    updateListened();
    if (_secsWatched === REQUIRED) {
      enableCompleteBtn();
    }
  }, 1000);
}

function enableCompleteBtn() {
  const btn = document.getElementById('vm-complete-btn');
  btn.disabled = false;
  btn.style.background = 'linear-gradient(90deg,#27ae60,#2ecc71)';
  btn.style.boxShadow  = '0 4px 14px rgba(39,174,96,.5)';
  btn.textContent      = 'Complete';
}

function resetVideo() {
  clearInterval(_timer);
  const player = document.getElementById('video-player');
  player.pause(); player.currentTime = 0; player.src = '';
  resetCountdown();
  closeModal();
}

function completeTask() {
  const btn = document.getElementById('vm-complete-btn');
  btn.disabled = true;
  btn.textContent = 'Processing...';

  const _url = window.location.href.split('?')[0];
  fetch(_url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: 'complete_video=' + encodeURIComponent(_vid) + '&plan_id=' + encodeURIComponent(_pid)
  })
  .then(r => {
    if (!r.ok) throw new Error('HTTP ' + r.status);
    return r.text();
  })
  .then(raw => {
    const jsonStart = raw.indexOf('{');
    if (jsonStart === -1) throw new Error('No JSON in response');
    return JSON.parse(raw.substring(jsonStart));
  })
  .then(d => {
    if (d.status === 'ok') {
      const statDone      = document.getElementById('stat-done');
      const statRemaining = document.getElementById('stat-remaining');
      if (statDone)      statDone.textContent      = d.new_done;
      if (statRemaining) statRemaining.textContent = d.new_remaining;
      _tasksRemaining = d.new_remaining;

      closeModal();

      if (d.new_balance !== undefined) {
        const balEl = document.getElementById('live-balance');
        if (balEl) balEl.textContent = d.new_balance;
      }

      if (_tasksRemaining <= 0) {
        document.querySelectorAll('.video-card').forEach(function(c) {
          const oc = c.getAttribute('onclick') || '';
          if (oc.includes('openVideo')) {
            c.setAttribute('onclick', oc.replace(/,(true|false)\)$/, ',true)'));
          }
        });
      }

      showEarnPopup(d.currency, parseFloat(d.earned));

    } else {
      showToast(d.msg || 'Error', 'err');
      btn.disabled = false;
      btn.textContent = 'Complete';
    }
  })
  .catch(() => {
    showToast('Network error. Try again.', 'err');
    btn.disabled = false;
    btn.textContent = 'Complete';
  });
}

function showLimitPopup() {
  document.getElementById('limit-popup').classList.add('show');
}
function closeLimitPopup() {
  document.getElementById('limit-popup').classList.remove('show');
}
document.getElementById('limit-popup').addEventListener('click', function(e) {
  if (e.target === this) closeLimitPopup();
});

function showEarnPopup(currency, amount) {
  document.getElementById('popup-amount').textContent   = '+' + amount.toFixed(3);
  document.getElementById('popup-currency').textContent = currency + ' Earned Successfully!';
  document.getElementById('earn-popup').classList.add('show');
  setTimeout(closeEarnPopup, 2500);
}

function closeEarnPopup() {
  document.getElementById('earn-popup').classList.remove('show');
}

document.getElementById('earn-popup').addEventListener('click', function (e) {
  if (e.target === this) closeEarnPopup();
});

function closeModal() {
  clearInterval(_timer);
  const player = document.getElementById('video-player');
  player.pause(); player.src = '';
  document.getElementById('video-modal').classList.remove('open');
  resetCountdown();
}

document.getElementById('video-modal').addEventListener('click', function (e) {
  if (e.target === this) closeModal();
});

function showToast(msg, type) {
  const t = document.getElementById('toast');
  t.textContent = msg;
  t.className = 'toast ' + (type || '') + ' show';
  setTimeout(() => { t.className = 'toast ' + (type || ''); }, 3000);
}

<?php if ($autoplay && $autoplay_video): ?>
window.addEventListener('DOMContentLoaded', function () {
  const v = <?= json_encode([
    'id'    => $autoplay_video['id'],
    'url'   => $autoplay_video['video_url'],
    'title' => $autoplay_video['title'],
    'earn'  => number_format($autoplay_video['earn_amount'] > 0 ? $autoplay_video['earn_amount'] : ($plan['per_order'] ?? 0), 3),
    'pid'   => $plan['id']
  ]) ?>;
  openVideo(v.id, v.url, v.title, v.earn, v.pid);
});
<?php endif; ?>
</script>
</body>
</html>