<?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'] ?? '#';

// ── Fetch user balances ──────────────────────────────────────
$_urow = $conn->query("SELECT security_deposit, balance FROM users WHERE id=$user_id")->fetch_assoc();
$security_deposit = (float)($_urow['security_deposit'] ?? 0);
$user_balance     = (float)($_urow['balance'] ?? 0);

$available_for_plan = $security_deposit;

// Handle join plan POST
$msg = ''; $msg_type = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['join_plan_id'])) {
    $plan_id = (int)$_POST['join_plan_id'];
    $plan    = $conn->query("SELECT * FROM plans WHERE id=$plan_id AND active=1")->fetch_assoc();

    if (!$plan) {
        $msg = 'Plan not found.'; $msg_type = 'error';
    } elseif ($plan['is_free']) {
        $msg = 'This plan is auto-assigned.'; $msg_type = 'error';
    } elseif ($security_deposit <= 0) {
        $msg = 'You need to make a security deposit before joining a paid plan.'; $msg_type = 'error';
    } elseif ($security_deposit < (float)$plan['price']) {
        $needed = number_format((float)$plan['price'] - $security_deposit, 2);
        $msg = 'Security deposit yako haitosha. Unahitaji ' . $currency . ' ' . number_format((float)$plan['price'], 2) . ' (pungufu ' . $currency . ' ' . $needed . '). Tafadhali deposit kwanza.';
        $msg_type = 'error';
    } else {
        $exists = $conn->query("SELECT id FROM user_plans WHERE user_id=$user_id AND plan_id=$plan_id AND active=1 AND (expires_at IS NULL OR expires_at>NOW())")->fetch_assoc();
        if ($exists) {
            $msg = 'You already have this plan.'; $msg_type = 'error';
        } else {
            // Deactivate old plans
            $conn->query("UPDATE user_plans SET active=0 WHERE user_id=$user_id AND active=1");
            // Join new plan
            $conn->query("INSERT INTO user_plans (user_id,plan_id,active,expires_at) VALUES ($user_id,$plan_id,1,NULL)");
            // Deduct from security_deposit
            $conn->query("UPDATE users SET security_deposit = security_deposit - {$plan['price']} WHERE id=$user_id");

            // ── Pay referral commissions to upliners (L1, L2, L3) ── ← NEW
            payReferralCommissions($conn, $user_id, $plan_id);

            // Refresh security_deposit value
            $security_deposit   = $security_deposit - (float)$plan['price'];
            $available_for_plan = $security_deposit;

            $msg = 'Successfully joined ' . htmlspecialchars($plan['name']) . '!'; $msg_type = 'success';
            // Refresh active plan
            $active_plan = $conn->query("SELECT p.*,up.expires_at,up.joined_at FROM user_plans up JOIN plans p ON p.id=up.plan_id WHERE up.user_id=$user_id AND up.active=1 AND (up.expires_at IS NULL OR up.expires_at>NOW()) ORDER BY p.sort_order DESC LIMIT 1")->fetch_assoc();
        }
    }
}

// Fetch all active plans
$plans = $conn->query("SELECT * FROM plans WHERE active=1 ORDER BY sort_order ASC")->fetch_all(MYSQLI_ASSOC);
?>
<!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 - Job Plans</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<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:80px}

/* Banner */
.banner{width:calc(100% - 16px);margin:4px 8px 0;border-radius:14px;overflow:hidden}
.banner img{width:100%;height:190px;object-fit:cover;display:block}

/* Identity card */
.identity-card{background:linear-gradient(135deg,rgba(30,30,50,.78),rgba(60,60,90,.65));margin:12px;border-radius:16px;padding:18px 20px;color:#fff;backdrop-filter:blur(6px)}
.identity-card .id-top{font-size:17px;font-weight:700;margin-bottom:12px}
.identity-card .id-row{display:flex;justify-content:space-between;align-items:flex-end}
.identity-card .id-left p{font-size:13px;opacity:.88;margin-bottom:4px}
.identity-card .id-right{text-align:right;font-size:12px;opacity:.78;line-height:1.8}

/* Alert */
.alert{margin:0 12px 10px;padding:10px 14px;border-radius:10px;font-size:13px;font-weight:500;line-height:1.5}
.alert.success{background:#e6f9f0;color:#1a7a4a;border:1px solid #a0ddb8}
.alert.error{background:#fde8e8;color:#c0392b;border:1px solid #f5b0b0}

/* ── Plan Card ── */
.plan-card{
  margin:8px 12px;border-radius:18px;overflow:hidden;
  position:relative;padding:14px 14px 14px 16px;color:#fff;
  box-shadow:0 3px 14px rgba(0,0,0,.22);min-height:120px;
  display:flex;flex-direction:column;
}
.plan-card::after{
  content:'';position:absolute;inset:0;pointer-events:none;
  background:linear-gradient(120deg,rgba(255,255,255,.10) 0%,transparent 40%,rgba(255,255,255,.04) 100%);
}
.card-row{display:flex;align-items:flex-start;justify-content:space-between;width:100%;position:relative;z-index:1;flex:1}
.card-left{flex:1;min-width:0;display:flex;flex-direction:column;padding-right:8px}
.card-name{font-size:18px;font-weight:800;color:#fff;line-height:1.2;margin-bottom:3px;text-shadow:0 1px 4px rgba(0,0,0,.2)}
.card-price{font-size:15px;font-weight:700;color:#FFD700;margin-bottom:8px;text-shadow:0 1px 4px rgba(0,0,0,.25)}
.card-details p{font-size:12px;color:#fff;text-shadow:0 1px 3px rgba(0,0,0,.2);line-height:1.5}

.card-right{display:flex;flex-direction:column;align-items:flex-end;justify-content:space-between;flex-shrink:0;min-width:110px;align-self:stretch}

/* Current badge */
.current-badge{background:rgba(255,255,255,.22);border:1.5px solid rgba(255,255,255,.55);color:#fff;font-size:12px;font-weight:700;padding:6px 14px;border-radius:20px;white-space:nowrap}

/* Join Now button */
.pc-join-btn{
  font-family:'Segoe UI',sans-serif;font-size:13px;font-weight:700;
  color:#fff;background:#000;border:none;cursor:pointer;
  padding:7px 16px;border-radius:20px;white-space:nowrap;
  text-align:center;transition:background .2s;
  box-shadow:0 2px 8px rgba(0,0,0,.3)
}
.pc-join-btn:hover{background:#222}

/* Deposit button */
.pc-deposit-btn{
  font-family:'Segoe UI',sans-serif;font-size:13px;font-weight:700;
  color:#FFD700;background:#000;border:none;cursor:pointer;
  padding:7px 16px;border-radius:20px;white-space:nowrap;
  text-align:center;transition:background .2s;
  box-shadow:0 2px 8px rgba(0,0,0,.3);
  text-decoration:none;display:inline-block
}
.pc-deposit-btn:hover{background:#222}

/* Badge image */
.card-img-wrap{margin-top:auto;display:flex;align-items:flex-end;justify-content:flex-end}
.card-img-wrap img{height:80px;width:auto;max-width:100px;object-fit:cover;border-radius:50%;border:2.5px solid rgba(255,255,255,.45);box-shadow:0 2px 8px rgba(0,0,0,.25);filter:drop-shadow(0 4px 12px rgba(0,0,0,.45))}
.card-badge-emoji{font-size:68px;line-height:1;filter:drop-shadow(0 4px 14px rgba(0,0,0,.5));user-select:none}

/* ── MODAL ── */
.modal-bg{display:none;position:fixed;inset:0;z-index:500;background:rgba(0,0,0,.88);backdrop-filter:blur(6px);align-items:center;justify-content:center;padding:20px}
.modal-bg.open{display:flex;animation:bgIn .2s ease}
@keyframes bgIn{from{opacity:0}to{opacity:1}}

.modal-sheet{width:100%;max-width:420px;background:#140a24;border-radius:20px;border:1px solid rgba(160,32,200,.3);padding:0 0 26px;animation:sheetUp .3s cubic-bezier(.22,.68,0,1.2);max-height:88vh;overflow-y:auto}
@keyframes sheetUp{from{transform:scale(.93);opacity:0}to{transform:scale(1);opacity:1}}

.modal-handle{width:34px;height:3px;border-radius:2px;background:rgba(255,255,255,.1);margin:13px auto 12px}
.modal-head{padding:0 16px 12px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid rgba(255,255,255,.07)}
.modal-plan-name{font-size:20px;font-weight:700;font-style:italic;color:#fff}
.modal-close{width:30px;height:30px;border-radius:50%;background:rgba(255,255,255,.07);border:none;color:rgba(255,255,255,.5);font-size:13px;cursor:pointer;display:flex;align-items:center;justify-content:center}
.modal-close:hover{background:rgba(255,255,255,.13);color:#fff}

.m-amount-box{margin:13px 16px;background:rgba(160,32,200,.14);border:1px solid rgba(160,32,200,.35);border-radius:11px;padding:14px 16px;display:flex;align-items:center;justify-content:space-between}
.mab-lbl{font-size:9px;color:rgba(255,255,255,.38);text-transform:uppercase;letter-spacing:1px;margin-bottom:3px}
.mab-val{font-size:26px;font-weight:700;font-style:italic;color:#fff}
.mab-cur{font-size:10px;color:#c084fc}

.m-balance-warn{margin:0 16px 12px;background:rgba(231,76,60,.15);border:1px solid rgba(231,76,60,.4);border-radius:10px;padding:10px 14px;font-size:12px;color:#ff9090;line-height:1.6}
.m-balance-ok{margin:0 16px 12px;background:rgba(39,174,96,.15);border:1px solid rgba(39,174,96,.4);border-radius:10px;padding:10px 14px;font-size:12px;color:#6effa8;line-height:1.6}

.m-preview{display:flex;gap:7px;margin:0 16px 14px}
.prev-box{flex:1;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.08);border-radius:9px;padding:9px 7px;text-align:center}
.prev-lbl{font-size:7px;color:rgba(255,255,255,.32);text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px}
.prev-val{font-size:12px;font-weight:700;color:#fff}
.prev-val.gld{color:#FFD700}
.prev-val.grn{color:#4ade80}

.confirm-btn{
  width:calc(100% - 32px);margin:0 16px;
  padding:14px;border-radius:10px;border:none;
  background:linear-gradient(to right,#6a0dad,#cd9b6a);
  color:#fff;font-size:17px;font-weight:700;font-style:italic;
  font-family:'Segoe UI',sans-serif;cursor:pointer;
  display:flex;align-items:center;justify-content:center;gap:8px;
  transition:transform .15s,box-shadow .2s;
  box-shadow:0 4px 18px rgba(106,13,173,.4)
}
.confirm-btn:hover{transform:translateY(-1px)}
.confirm-btn:active{transform:scale(.98)}
.confirm-btn:disabled{background:#555;cursor:not-allowed;box-shadow:none;transform:none}

.deposit-modal-btn{
  width:calc(100% - 32px);margin:10px 16px 0;
  padding:13px;border-radius:10px;border:none;
  background:linear-gradient(to right,#f39c12,#e67e22);
  color:#fff;font-size:15px;font-weight:700;
  font-family:'Segoe UI',sans-serif;cursor:pointer;
  display:flex;align-items:center;justify-content:center;gap:8px;
  text-decoration:none
}

.spin{display:inline-block;width:13px;height:13px;border:2px solid rgba(255,255,255,.2);border-top-color:#fff;border-radius:50%;animation:spinA .6s linear infinite}
@keyframes spinA{to{transform:rotate(360deg)}}

/* Float */
.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}

/* Bottom Nav */
.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}
.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>

<!-- Banner -->
<div class="banner">
  <img src="home.png" alt="WFM" onerror="this.src='https://eoproject.com/sn17/68e00c534caee.jpg'">
</div>

<!-- Identity Card -->
<div class="identity-card">
  <div class="id-top">Your Identity: <?= htmlspecialchars($active_plan['name'] ?? 'None') ?></div>
  <div class="id-row">
    <div class="id-left">
      <p>Daily Tasks: <?= $active_plan['daily_tasks'] ?? 0 ?> times</p>
    </div>
    <div class="id-right">
      Effective Date<br>
      <?php if ($active_plan): ?>
        <?= $active_plan['expires_at'] ? 'Expires: '.date('Y-m-d', strtotime($active_plan['expires_at'])) : 'Permanent Validity' ?>
      <?php else: ?>
        —
      <?php endif; ?>
    </div>
  </div>
</div>

<?php if ($msg): ?>
<div class="alert <?= $msg_type ?>"><?= $msg ?></div>
<?php endif; ?>

<!-- Plan Cards -->
<?php
$badge_emojis = ['🥇','🥈','🥉','🏅','🏆','👑','💎','⭐','🎯'];
foreach ($plans as $i => $pl):
  $is_current    = $active_plan && $active_plan['id'] == $pl['id'];
  $plan_price    = (float)$pl['price'];
  $can_afford    = ($pl['is_free'] || $security_deposit >= $plan_price);
  $has_badge_img = !empty($pl['badge_img']);
  $badge_emoji   = $badge_emojis[$i % count($badge_emojis)];

  $sort = (int)$pl['sort_order'];
  if (!empty($pl['color_from']) && !empty($pl['color_to'])) {
    $bg = 'linear-gradient(135deg,' . htmlspecialchars($pl['color_from']) . ',' . htmlspecialchars($pl['color_to']) . ')';
  } elseif ($sort <= 0) {
    $bg = 'linear-gradient(to right,#7f8fa6,#a4b2c4)';
  } elseif ($sort <= 1) {
    $bg = 'linear-gradient(to right,#6a0dad,#7b2fbe 20%,#8b4a8b 45%,#a0735a 65%,#b8895a 80%,#cd9b6a)';
  } elseif ($sort <= 3) {
    $bg = 'linear-gradient(to right,#5c0fa8,#7428b8 20%,#904878 45%,#a86850 65%,#bc8255 80%,#d09a6a)';
  } elseif ($sort <= 5) {
    $bg = 'linear-gradient(to right,#720bb5,#8535c0 20%,#985580 45%,#ac7258 65%,#c08860 80%,#d4a070)';
  } else {
    $bg = 'linear-gradient(to right,#6a0dad,#8535c0 20%,#985580 45%,#b8895a 80%,#cd9b6a)';
  }
?>
<div class="plan-card" style="background:<?= $bg ?>">
  <div class="card-row">

    <!-- LEFT -->
    <div class="card-left">
      <div class="card-name"><?= htmlspecialchars($pl['name']) ?></div>
      <div class="card-price"><?= number_format($plan_price, 0) ?> <?= $currency ?></div>
      <div class="card-details">
        <p>Daily Tasks: <?= $pl['daily_tasks'] ?> times</p>
        <p>Per Order: <?= number_format($pl['per_order'], 1) ?> <?= $currency ?></p>
        <p>Daily Earnings: <?= number_format($pl['daily_earnings'], 1) ?> <?= $currency ?></p>
        <?php if ($pl['duration_days'] > 0): ?>
        <p>Duration: <?= $pl['duration_days'] ?> days</p>
        <?php endif; ?>
      </div>
    </div>

    <!-- RIGHT -->
    <div class="card-right">

      <?php if ($is_current): ?>
        <span class="current-badge">✓ Current Level</span>

      <?php elseif ($pl['is_free']): ?>
        <span class="current-badge" style="background:rgba(255,255,255,.1)">Free</span>

      <?php elseif ($can_afford): ?>
        <button class="pc-join-btn" onclick='openModal(<?= json_encode([
          "id"             => (int)$pl["id"],
          "name"           => $pl["name"],
          "price"          => $plan_price,
          "daily_tasks"    => (int)$pl["daily_tasks"],
          "per_order"      => (float)$pl["per_order"],
          "daily_earnings" => (float)$pl["daily_earnings"],
          "can_afford"     => true,
          "deposit"        => $security_deposit,
        ]) ?>)'>Join Now</button>

      <?php else: ?>
        <a href="deposit.php" class="pc-deposit-btn">Deposit</a>

      <?php endif; ?>

      <div class="card-img-wrap">
        <?php if ($has_badge_img): ?>
          <img src="<?= htmlspecialchars($pl['badge_img']) ?>"
               alt="<?= htmlspecialchars($pl['name']) ?>"
               onerror="this.style.display='none';this.nextElementSibling.style.display='block'">
          <span class="card-badge-emoji" style="display:none"><?= $badge_emoji ?></span>
        <?php else: ?>
          <span class="card-badge-emoji"><?= $badge_emoji ?></span>
        <?php endif; ?>
      </div>

    </div>
  </div>
</div>
<?php endforeach; ?>

<!-- Float Service -->
<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>

<!-- ── MODAL ── -->
<div id="joinModal" class="modal-bg" onclick="backdropClick(event)">
  <div class="modal-sheet">
    <div class="modal-handle"></div>
    <div class="modal-head">
      <div class="modal-plan-name" id="mPlanName">—</div>
      <button class="modal-close" onclick="closeModal()">&#x2715;</button>
    </div>

    <div class="m-amount-box">
      <div>
        <div class="mab-lbl">Plan Price (deducted from Security Deposit)</div>
        <div class="mab-val" id="mAmount">—</div>
      </div>
      <div class="mab-cur"><?= htmlspecialchars($currency) ?></div>
    </div>

    <div id="mBalanceMsg"></div>

    <div class="m-preview">
      <div class="prev-box">
        <div class="prev-lbl">Daily Tasks</div>
        <div class="prev-val" id="pTasks">—</div>
      </div>
      <div class="prev-box">
        <div class="prev-lbl">Per Order</div>
        <div class="prev-val gld" id="pPer">—</div>
      </div>
      <div class="prev-box">
        <div class="prev-lbl">Daily Earn</div>
        <div class="prev-val grn" id="pDaily">—</div>
      </div>
    </div>

    <form method="POST" id="joinForm" onsubmit="return handleSubmit()">
      <input type="hidden" name="join_plan_id" id="fPlanId">
      <button type="submit" class="confirm-btn" id="confirmBtn">
        <i class="fas fa-play-circle"></i> Confirm Join
      </button>
    </form>

    <a href="deposit.php" class="deposit-modal-btn" id="depositModalBtn" style="display:none">
      <i class="fas fa-wallet"></i> Go to Deposit
    </a>
  </div>
</div>

<!-- Bottom Nav -->
<?php include 'navigation_bottom.php'; ?>

<script>
const CUR          = '<?= addslashes($currency) ?>';
const USER_DEPOSIT = <?= $security_deposit ?>;
let busy = false;

function fmt(n) {
  return parseFloat(n).toLocaleString(undefined, {minimumFractionDigits:1, maximumFractionDigits:1}) + ' ' + CUR;
}

function openModal(plan) {
  busy = false;
  document.getElementById('fPlanId').value         = plan.id;
  document.getElementById('mPlanName').textContent = plan.name;
  document.getElementById('mAmount').textContent   = Number(plan.price).toLocaleString();
  document.getElementById('pTasks').textContent    = plan.daily_tasks + ' times';
  document.getElementById('pPer').textContent      = fmt(plan.per_order);
  document.getElementById('pDaily').textContent    = fmt(plan.daily_earnings);

  const confirmBtn = document.getElementById('confirmBtn');
  const depositBtn = document.getElementById('depositModalBtn');
  const balanceMsg = document.getElementById('mBalanceMsg');

  if (plan.can_afford) {
    const remaining = (plan.deposit - plan.price).toFixed(2);
    balanceMsg.className = 'm-balance-ok';
    balanceMsg.innerHTML =
      '✅ Security Deposit yako: <strong>' + CUR + ' ' + Number(plan.deposit).toFixed(2) + '</strong><br>' +
      'Baada ya kununua itabaki: <strong>' + CUR + ' ' + remaining + '</strong>';
    confirmBtn.disabled      = false;
    depositBtn.style.display = 'none';
  } else {
    const needed = (plan.price - plan.deposit).toFixed(2);
    balanceMsg.className = 'm-balance-warn';
    balanceMsg.innerHTML =
      '⚠️ Security Deposit yako: <strong>' + CUR + ' ' + Number(plan.deposit).toFixed(2) + '</strong><br>' +
      'Unahitaji <strong>' + CUR + ' ' + needed + '</strong> zaidi. Tafadhali deposit kwanza.';
    confirmBtn.disabled      = true;
    depositBtn.style.display = 'flex';
  }

  document.getElementById('joinModal').classList.add('open');
  document.body.style.overflow = 'hidden';
}

function closeModal() {
  document.getElementById('joinModal').classList.remove('open');
  document.body.style.overflow = '';
  busy = false;
}

function backdropClick(e) {
  if (e.target === document.getElementById('joinModal')) closeModal();
}

function handleSubmit() {
  if (busy) return false;
  busy = true;
  const btn = document.getElementById('confirmBtn');
  btn.disabled = true;
  btn.innerHTML = '<span class="spin"></span> Processing…';
  return true;
}
</script>
</body>
</html>