<?php
session_start();
if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit(); }
require_once 'db.php';

$user_id = intval($_SESSION['user_id']);

// PRG flash messages
$success = $_SESSION['invest_success'] ?? null;
$error   = $_SESSION['invest_error']   ?? null;
unset($_SESSION['invest_success'], $_SESSION['invest_error']);

// Active plans
$plans = [];
$res = mysqli_query($conn, "SELECT * FROM investment_plans WHERE status='active' ORDER BY min_amount ASC");
while ($r = mysqli_fetch_assoc($res)) $plans[] = $r;

// Commission rates
$commission_rates = ['level1'=>10.00,'level2'=>6.00,'level3'=>4.00];
$cr = mysqli_query($conn, "SELECT level, percentage FROM commission_settings WHERE level IN (1,2,3)");
while ($r = mysqli_fetch_assoc($cr)) $commission_rates['level'.$r['level']] = floatval($r['percentage']);

// Current wallet balance
$urow = mysqli_fetch_assoc(mysqli_query($conn, "SELECT balance FROM users WHERE id=$user_id"));
$user_balance = floatval($urow['balance'] ?? 0);

// ────────────────────────────────────────────────────────────────────────────
// HANDLE INVESTMENT POST
// ────────────────────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $amount  = floatval($_POST['amount']);
    $plan_id = intval($_POST['plan_id']);

    $pres = mysqli_query($conn, "SELECT * FROM investment_plans WHERE id=$plan_id AND status='active'");
    $sel  = mysqli_fetch_assoc($pres);

    if (!$sel) {
        $_SESSION['invest_error'] = "Invalid plan selected. Please try again.";
        header("Location: ".$_SERVER['PHP_SELF']); exit();
    }

    $min_amt = floatval($sel['min_amount']);
    $max_amt = floatval($sel['max_amount']);

    if ($amount < $min_amt || $amount > $max_amt) {
        $_SESSION['invest_error'] = "Amount must be between ZMW ".number_format($min_amt,2)." and ZMW ".number_format($max_amt,2).".";
        header("Location: ".$_SERVER['PHP_SELF']); exit();
    }

    mysqli_begin_transaction($conn);
    try {
        // Lock user row — get live balance
        $brow    = mysqli_fetch_assoc(mysqli_query($conn, "SELECT balance FROM users WHERE id=$user_id FOR UPDATE"));
        $cur_bal = floatval($brow['balance']);

        if ($amount > $cur_bal) {
            throw new Exception("Insufficient balance. You have ZMW ".number_format($cur_bal,2)." but tried to invest ZMW ".number_format($amount,2).". Please deposit more funds first.");
        }

        $roi_pct  = floatval($sel['roi_percentage']);
        $duration = intval($sel['duration_days']);
        $ret_type = $sel['return_type'];
        $profit   = round(($amount * $roi_pct) / 100, 2);
        $total_rt = ($ret_type === 'flexible') ? round($amount + $profit, 2) : $profit;
        $maturity = date('Y-m-d H:i:s', strtotime("+{$duration} days"));

        // Deduct balance immediately
        $ok = mysqli_query($conn,
            "UPDATE users SET balance = balance - $amount
             WHERE id = $user_id AND balance >= $amount");
        if (!$ok || mysqli_affected_rows($conn) === 0) {
            throw new Exception("Failed to deduct balance. Please try again.");
        }

        // Insert investment record
        $stmt = mysqli_prepare($conn,
            "INSERT INTO investments (user_id,plan_id,amount,profit,total_return,maturity_date,return_type,status)
             VALUES (?,?,?,?,?,?,?,'running')");
        mysqli_stmt_bind_param($stmt,'iidddss',$user_id,$plan_id,$amount,$profit,$total_rt,$maturity,$ret_type);
        if (!mysqli_stmt_execute($stmt)) throw new Exception("Database error: ".mysqli_error($conn));
        $inv_id = mysqli_insert_id($conn);
        mysqli_stmt_close($stmt);

        // Referral commissions (3 levels)
        $cur_id = $user_id;
        for ($lvl=1; $lvl<=3; $lvl++) {
            $rr = mysqli_fetch_assoc(mysqli_query($conn,"SELECT referrer_id FROM users WHERE id=$cur_id"));
            if (!$rr || !$rr['referrer_id']) break;
            $up  = intval($rr['referrer_id']);
            $rt  = floatval($commission_rates["level$lvl"]);
            $com = round(($amount * $rt) / 100, 2);
            if ($com > 0) {
                mysqli_query($conn,"INSERT INTO referral_commissions (user_id,from_user_id,investment_id,level,percentage,amount,status) VALUES ($up,$user_id,$inv_id,$lvl,$rt,$com,'paid')");
                mysqli_query($conn,"INSERT INTO profits (user_id,amount,source) VALUES ($up,$com,'Level $lvl Referral Commission')");
                mysqli_query($conn,"UPDATE users SET total_referral_earnings=total_referral_earnings+$com, balance=balance+$com WHERE id=$up");
            }
            $cur_id = $up;
        }

        mysqli_commit($conn);

        $new_bal = $cur_bal - $amount;
        $_SESSION['invest_success'] =
            "✅ You have invested ZMW ".number_format($amount,2)." in ".$sel['name'].". ".
            ($ret_type==='fixed'
                ? "Daily profits will be credited to your balance."
                : "ZMW ".number_format($total_rt,2)." (capital + profit) will be returned on maturity day.").
            " Your new balance: ZMW ".number_format($new_bal,2).".";

    } catch (Exception $e) {
        mysqli_rollback($conn);
        $_SESSION['invest_error'] = $e->getMessage();
    }
    header("Location: ".$_SERVER['PHP_SELF']); exit();
}

// Re-fetch balance after redirect
$urow = mysqli_fetch_assoc(mysqli_query($conn, "SELECT balance FROM users WHERE id=$user_id"));
$user_balance = floatval($urow['balance'] ?? 0);

$plan_themes = [
    ['bg'=>'linear-gradient(135deg,#0f2027,#203a43,#2c5364)','border'=>'#2c5364','accent'=>'#00d4ff','roi_bg'=>'rgba(0,212,255,0.1)','roi_border'=>'#00d4ff','icon'=>'fas fa-gem','label'=>'Starter'],
    ['bg'=>'linear-gradient(135deg,#1a0533,#2d0a5e,#4a0080)','border'=>'#7b2fff','accent'=>'#b44dff','roi_bg'=>'rgba(180,77,255,0.1)','roi_border'=>'#b44dff','icon'=>'fas fa-crown','label'=>'Silver'],
    ['bg'=>'linear-gradient(135deg,#1a2f00,#2e5000,#3d6b00)','border'=>'#5cb800','accent'=>'#7fff00','roi_bg'=>'rgba(127,255,0,0.1)','roi_border'=>'#7fff00','icon'=>'fas fa-leaf','label'=>'Growth'],
    ['bg'=>'linear-gradient(135deg,#2d0a00,#5c1a00,#8c2900)','border'=>'#ff6600','accent'=>'#ff8c00','roi_bg'=>'rgba(255,140,0,0.1)','roi_border'=>'#ff8c00','icon'=>'fas fa-fire','label'=>'Premium'],
    ['bg'=>'linear-gradient(135deg,#001a33,#003366,#004d99)','border'=>'#0099ff','accent'=>'#33bbff','roi_bg'=>'rgba(51,187,255,0.1)','roi_border'=>'#33bbff','icon'=>'fas fa-shield-alt','label'=>'Pro'],
    ['bg'=>'linear-gradient(135deg,#1a001a,#33003d,#4d0066)','border'=>'#ff33cc','accent'=>'#ff66dd','roi_bg'=>'rgba(255,102,221,0.1)','roi_border'=>'#ff66dd','icon'=>'fas fa-star','label'=>'Elite'],
    ['bg'=>'linear-gradient(135deg,#1a1a00,#333300,#4d4d00)','border'=>'#cccc00','accent'=>'#FFD700','roi_bg'=>'rgba(255,215,0,0.1)','roi_border'=>'#FFD700','icon'=>'fas fa-trophy','label'=>'Gold'],
    ['bg'=>'linear-gradient(135deg,#001a1a,#003333,#004d4d)','border'=>'#00cccc','accent'=>'#00ffff','roi_bg'=>'rgba(0,255,255,0.1)','roi_border'=>'#00ffff','icon'=>'fas fa-rocket','label'=>'Platinum'],
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Plans - MaxTrade</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{background:#000;color:#fff;font-family:Arial,sans-serif;padding-bottom:70px;font-size:11px}
.header{background:#111;padding:10px 12px;text-align:center;border-bottom:1px solid #1a1a1a}
.header h1{color:#fff;font-size:16px}
.msg{padding:12px 14px;margin:10px;border-radius:8px;font-size:11px;display:flex;align-items:flex-start;gap:8px;line-height:1.5}
.msg-ok{background:#0d2e0d;border:1px solid #1a5c1a;color:#4ade80}
.msg-er{background:#2e0d0d;border:1px solid #5c1a1a;color:#f87171}
/* Wallet bar */
.wallet-bar{margin:10px;border-radius:12px;background:linear-gradient(135deg,#1a1200,#3d2e00);border:1px solid rgba(255,215,0,.35);padding:14px 16px;display:flex;align-items:center;justify-content:space-between}
.wb-label{font-size:10px;color:#888;margin-bottom:3px}
.wb-amount{font-size:24px;font-weight:800;color:#FFD700;letter-spacing:-0.5px}
.wb-note{font-size:9px;color:#555;margin-top:3px}
.wb-btn{background:#FFD700;color:#000;font-weight:800;font-size:10px;padding:9px 16px;border-radius:8px;text-decoration:none;display:flex;align-items:center;gap:4px;white-space:nowrap}
/* Plan type tabs */
.hiw{margin:0 10px 10px;border-radius:10px;overflow:hidden}
.hiw-tabs{display:grid;grid-template-columns:1fr 1fr}
.hiw-tab{padding:10px 8px;text-align:center;font-size:10px;font-weight:700;cursor:pointer;transition:opacity .2s}
.tab-fixed{background:#0d1b3e;border:1px solid rgba(59,130,246,.3);color:#60a5fa;border-radius:8px 0 0 0}
.tab-flex{background:#0d2e18;border:1px solid rgba(16,185,129,.3);color:#34d399;border-radius:0 8px 0 0}
.hiw-tab:not(.active){opacity:.4}
.hiw-panel{display:none;padding:12px;font-size:10px;line-height:1.7}
.hiw-panel.active{display:block}
.panel-fixed{background:#0d1b3e;border:1px solid rgba(59,130,246,.2);border-top:none;border-radius:0 0 8px 8px}
.panel-flex{background:#0d2e18;border:1px solid rgba(16,185,129,.2);border-top:none;border-radius:0 0 8px 8px}
.hiw-title{font-size:12px;font-weight:800;margin-bottom:8px;display:flex;align-items:center;gap:5px}
.hiw-row{display:flex;gap:7px;margin-bottom:6px}
.hiw-num{width:18px;height:18px;border-radius:50%;font-size:9px;font-weight:800;display:flex;align-items:center;justify-content:center;flex-shrink:0;margin-top:2px}
.panel-fixed .hiw-num{background:#3b82f6;color:#fff}
.panel-flex .hiw-num{background:#10b981;color:#fff}
.hiw-txt{color:rgba(255,255,255,.65)}
.hiw-txt strong{color:#fff}
.hiw-eg{border-radius:6px;padding:8px 10px;margin-top:8px;font-size:9px}
.panel-fixed .hiw-eg{background:rgba(59,130,246,.1);border:1px solid rgba(59,130,246,.25)}
.panel-flex .hiw-eg{background:rgba(16,185,129,.1);border:1px solid rgba(16,185,129,.25)}
.eg-title{font-weight:800;font-size:10px;margin-bottom:5px}
.eg-row{display:flex;justify-content:space-between;padding:2px 0;border-bottom:1px solid rgba(255,255,255,.05)}
.eg-row:last-child{border-bottom:none}
.eg-row span:first-child{color:rgba(255,255,255,.45)}
/* Plans */
.plans-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:10px;padding:10px}
.plan-card{border-radius:10px;padding:10px;box-shadow:0 4px 15px rgba(0,0,0,.6);border:1px solid #333;transition:transform .3s;position:relative;overflow:hidden}
.plan-card:hover{transform:translateY(-2px)}
.plan-badge{position:absolute;top:8px;right:8px;font-size:7px;font-weight:bold;padding:2px 6px;border-radius:10px;text-transform:uppercase}
.plan-card h3{font-size:12px;display:flex;align-items:center;gap:4px;margin-bottom:3px}
.type-tag{display:inline-flex;align-items:center;gap:3px;padding:2px 6px;border-radius:4px;font-size:7px;font-weight:800;margin-bottom:5px}
.tag-f{background:rgba(59,130,246,.2);border:1px solid rgba(59,130,246,.35);color:#60a5fa}
.tag-x{background:rgba(16,185,129,.2);border:1px solid rgba(16,185,129,.35);color:#34d399}
.earn-box{padding:7px 9px;border-radius:6px;margin:5px 0}
.earn-row{display:flex;justify-content:space-between;align-items:center;font-size:9px;padding:2px 0}
.earn-row span:first-child{color:rgba(255,255,255,.45)}
.earn-row span:last-child{font-weight:800}
.earn-total{font-size:13px;font-weight:800;margin-top:4px;padding-top:4px;border-top:1px solid rgba(255,255,255,.1);display:flex;justify-content:space-between;align-items:center}
.earn-total span:first-child{font-size:9px;color:rgba(255,255,255,.5)}
.pd{display:flex;justify-content:space-between;margin:3px 0;padding:3px 0;border-bottom:1px solid rgba(255,255,255,.07);font-size:9px}
.pd:last-of-type{border-bottom:none}
.pd span:first-child{color:#888}
.pd span:last-child{color:#fff;font-weight:bold}
.need-more{font-size:8px;color:#666;text-align:center;margin:3px 0;padding:3px;background:rgba(255,255,255,.04);border-radius:4px}
.invest-btn{width:100%;padding:8px;border:none;border-radius:6px;font-weight:bold;cursor:pointer;margin-top:8px;font-size:10px;display:flex;align-items:center;justify-content:center;gap:4px;color:#000;transition:opacity .2s}
.invest-btn:hover{opacity:.85}
.invest-btn:disabled{opacity:.35;cursor:not-allowed}
/* Commission */
.comm-box{background:#111;border:1px solid #1e1e1e;border-radius:8px;padding:10px;margin:0 10px 10px;font-size:10px}
.comm-title{color:#FFD700;font-weight:bold;margin-bottom:6px;display:flex;align-items:center;gap:4px;font-size:11px}
.comm-row{display:flex;justify-content:space-between;padding:4px 0;font-size:9px;border-bottom:1px solid #1a1a1a}
.comm-row:last-child{border-bottom:none}
.comm-row span:first-child{color:#888}
.comm-row span:last-child{color:#FFD700;font-weight:bold}
/* Modal */
.modal{display:none;position:fixed;z-index:1000;left:0;top:0;width:100%;height:100%;background:rgba(0,0,0,.93);overflow-y:auto}
.modal-inner{background:#111;margin:5% auto 30px;padding:18px;border-radius:14px;width:92%;max-width:360px;box-shadow:0 8px 40px rgba(0,0,0,.9);border:1px solid #2a2a2a}
.modal-hdr{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px}
.modal-title{font-size:16px;font-weight:800}
.close-btn{color:#aaa;font-size:26px;cursor:pointer;line-height:1}
.close-btn:hover{color:#fff}
.modal-bal{background:#0a0a0a;border:1px solid #1e1e1e;border-radius:8px;padding:10px 14px;margin-bottom:12px;display:flex;justify-content:space-between;align-items:center}
.modal-bal-label{font-size:10px;color:#666}
.modal-bal-amount{font-size:18px;font-weight:800;color:#FFD700}
.pte{border-radius:8px;padding:10px 12px;margin-bottom:10px;font-size:9px;line-height:1.7}
.pte-f{background:rgba(59,130,246,.1);border:1px solid rgba(59,130,246,.3)}
.pte-x{background:rgba(16,185,129,.1);border:1px solid rgba(16,185,129,.3)}
.pte-title{font-size:11px;font-weight:800;margin-bottom:6px;display:flex;align-items:center;gap:4px}
.pte-f .pte-title{color:#60a5fa}
.pte-x .pte-title{color:#34d399}
.pte-row{display:flex;gap:5px;margin-bottom:3px;color:rgba(255,255,255,.6)}
.form-lbl{display:block;color:#888;font-size:10px;margin:10px 0 5px}
.amt-wrap{position:relative}
.amt-input{width:100%;padding:13px 55px 13px 12px;background:#000;border:1px solid #2a2a2a;border-radius:8px;color:#fff;font-size:20px;font-weight:700}
.amt-input:focus{outline:none;border-color:#FFD700}
.cur-tag{position:absolute;right:12px;top:50%;transform:translateY(-50%);color:#444;font-size:11px;font-weight:700}
.range-hint{font-size:9px;color:#444;margin-top:5px}
.insuf-warn{display:none;background:rgba(248,65,65,.08);border:1px solid rgba(248,65,65,.3);border-radius:6px;padding:9px 12px;margin-top:8px;font-size:10px;color:#f87171;line-height:1.5}
.insuf-warn a{color:#ff8c00;font-weight:700;text-decoration:none}
.preview-box{background:#050f05;border:1px solid #1a3d1a;border-radius:8px;padding:10px 12px;margin-top:10px;font-size:9px;display:none}
.pv-title{font-size:10px;font-weight:700;color:#4ade80;margin-bottom:6px}
.pv-row{display:flex;justify-content:space-between;padding:4px 0;border-bottom:1px solid rgba(255,255,255,.05)}
.pv-row:last-child{border-bottom:none}
.pv-row span:first-child{color:#666}
.pv-row span:last-child{font-weight:bold}
.pv-divider{height:1px;background:rgba(255,255,255,.08);margin:6px 0}
.confirm-btn{width:100%;padding:14px;color:#000;border:none;border-radius:9px;font-weight:800;cursor:pointer;margin-top:12px;font-size:13px;display:flex;align-items:center;justify-content:center;gap:6px;transition:opacity .2s}
.confirm-btn:hover{opacity:.88}
.confirm-btn:disabled{background:#2a2a2a!important;color:#555;cursor:not-allowed}
</style>
</head>
<body>

<div class="header"><h1><i class="fas fa-chart-line"></i> Investment Plans</h1></div>

<?php if($success): ?><div class="msg msg-ok"><i class="fas fa-check-circle" style="flex-shrink:0;margin-top:1px"></i><span><?= htmlspecialchars($success) ?></span></div><?php endif; ?>
<?php if($error):   ?><div class="msg msg-er"><i class="fas fa-exclamation-circle" style="flex-shrink:0;margin-top:1px"></i><span><?= htmlspecialchars($error) ?></span></div><?php endif; ?>

<!-- Wallet balance -->
<div class="wallet-bar">
    <div>
        <div class="wb-label"><i class="fas fa-wallet" style="margin-right:4px;opacity:.6"></i>Wallet Balance</div>
        <div class="wb-amount">ZMW <?= number_format($user_balance,2) ?></div>
        <div class="wb-note">Deducted when you invest &bull; Profits credited daily</div>
    </div>
    <a href="deposit.php" class="wb-btn"><i class="fas fa-plus"></i> Add Funds</a>
</div>

<!-- Plan type explanation tabs -->
<div class="hiw">
    <div class="hiw-tabs">
        <div class="hiw-tab tab-fixed active" onclick="showTab('fixed')"><i class="fas fa-lock"></i> Profit Only</div>
        <div class="hiw-tab tab-flex"         onclick="showTab('flex')"><i class="fas fa-gem"></i> Profit + Capital</div>
    </div>
    <div class="hiw-panel panel-fixed active" id="tab-fixed">
        <div class="hiw-title" style="color:#60a5fa"><i class="fas fa-lock"></i> Profit-Only Plans (Fixed)</div>
        <div class="hiw-row"><div class="hiw-num">1</div><div class="hiw-txt">Your capital is <strong>deducted from your balance immediately</strong> and locked for the full duration.</div></div>
        <div class="hiw-row"><div class="hiw-num">2</div><div class="hiw-txt">Your profit = <strong>Capital × Return %</strong>. It is credited to your balance over the plan duration.</div></div>
        <div class="hiw-row"><div class="hiw-num">3</div><div class="hiw-txt">On maturity the plan closes. <strong>Capital is NOT returned</strong> — only the profit is earned.</div></div>
        <div class="hiw-eg">
            <div class="eg-title" style="color:#60a5fa">📊 Example: Invest ZMW 100 at 20% return</div>
            <div class="eg-row"><span>Capital deducted now</span><span style="color:#f87171">- ZMW 100.00</span></div>
            <div class="eg-row"><span>Your profit (100 × 20%)</span><span style="color:#4ade80">+ ZMW 20.00</span></div>
            <div class="eg-row"><span>Capital returned?</span><span style="color:#f87171">❌ No</span></div>
            <div class="eg-row"><span>Total you earn</span><span style="color:#4ade80">ZMW 20.00</span></div>
        </div>
    </div>
    <div class="hiw-panel panel-flex" id="tab-flex">
        <div class="hiw-title" style="color:#34d399"><i class="fas fa-gem"></i> Profit + Capital Plans (Flexible)</div>
        <div class="hiw-row"><div class="hiw-num">1</div><div class="hiw-txt">Your capital is <strong>deducted from your balance immediately</strong> when you invest.</div></div>
        <div class="hiw-row"><div class="hiw-num">2</div><div class="hiw-txt">Your profit = <strong>Capital × Return %</strong>. On maturity day: <strong>Capital + Profit</strong> is paid back to you in one lump sum.</div></div>
        <div class="hiw-row"><div class="hiw-num">3</div><div class="hiw-txt">After payout you can withdraw or reinvest straight away.</div></div>
        <div class="hiw-eg">
            <div class="eg-title" style="color:#34d399">📊 Example: Invest ZMW 100 at 20% return</div>
            <div class="eg-row"><span>Capital deducted now</span><span style="color:#f87171">- ZMW 100.00</span></div>
            <div class="eg-row"><span>Your profit (100 × 20%)</span><span style="color:#4ade80">+ ZMW 20.00</span></div>
            <div class="eg-row"><span>Capital returned?</span><span style="color:#34d399">✅ Yes</span></div>
            <div class="eg-row"><span>Total payout on maturity</span><span style="color:#4ade80">ZMW 120.00</span></div>
        </div>
    </div>
</div>

<!-- Referral commissions -->
<div class="comm-box">
    <div class="comm-title"><i class="fas fa-users"></i> Referral Commission Structure</div>
    <div class="comm-row"><span>Level 1 (Direct referrals)</span><span><?= $commission_rates['level1'] ?>%</span></div>
    <div class="comm-row"><span>Level 2 (2nd generation)</span><span><?= $commission_rates['level2'] ?>%</span></div>
    <div class="comm-row"><span>Level 3 (3rd generation)</span><span><?= $commission_rates['level3'] ?>%</span></div>
</div>

<!-- Plan cards -->
<div class="plans-grid">
<?php foreach($plans as $i=>$plan):
    $th       = $plan_themes[$i % count($plan_themes)];
    $is_fixed = $plan['return_type']==='fixed';
    $min_amt  = floatval($plan['min_amount']);
    $roi_pct  = floatval($plan['roi_percentage']);
    $dur      = intval($plan['duration_days']);
    // Earnings preview based on minimum investment
    $eg_profit = round($min_amt * $roi_pct / 100, 2);
    $eg_total  = $is_fixed ? $eg_profit : round($min_amt + $eg_profit, 2);
    $can       = ($user_balance >= $min_amt);
?>
<div class="plan-card" style="background:<?= $th['bg'] ?>;border-color:<?= $th['border'] ?>">
    <span class="plan-badge" style="background:<?= $th['accent'] ?>;color:#000"><?= $th['label'] ?></span>
    <h3 style="color:<?= $th['accent'] ?>"><i class="<?= $th['icon'] ?>"></i> <?= htmlspecialchars($plan['name']) ?></h3>
    <?php if($is_fixed): ?>
    <span class="type-tag tag-f"><i class="fas fa-lock"></i> Profit Only</span>
    <?php else: ?>
    <span class="type-tag tag-x"><i class="fas fa-gem"></i> Profit + Capital</span>
    <?php endif ?>
    <div class="earn-box" style="background:<?= $th['roi_bg'] ?>;border:1px solid <?= $th['roi_border'] ?>">
        <div class="earn-row">
            <span>Invest (min)</span>
            <span style="color:rgba(255,255,255,.7)">ZMW <?= number_format($min_amt,2) ?></span>
        </div>
        <div class="earn-row">
            <span>Profit earned (<?= $roi_pct ?>%)</span>
            <span style="color:<?= $th['accent'] ?>">+ ZMW <?= number_format($eg_profit,2) ?></span>
        </div>
        <?php if($is_fixed): ?>
        <div class="earn-row">
            <span>Capital returned?</span>
            <span style="color:#f87171">No</span>
        </div>
        <?php endif ?>
        <div class="earn-total">
            <span><?= $is_fixed ? "You earn in {$dur} days" : "You get back in {$dur} day".($dur>1?'s':'') ?></span>
            <span style="color:<?= $th['accent'] ?>">ZMW <?= number_format($eg_total,2) ?></span>
        </div>
    </div>
    <div class="pd"><span><i class="fas fa-arrow-down"></i> Min</span><span>ZMW <?= number_format($plan['min_amount']) ?></span></div>
    <div class="pd"><span><i class="fas fa-arrow-up"></i> Max</span><span>ZMW <?= number_format($plan['max_amount']) ?></span></div>
    <div class="pd"><span><i class="fas fa-calendar"></i> Duration</span><span><?= $plan['duration_days'] ?> days</span></div>
    <div class="pd"><span><i class="fas fa-undo"></i> Returns</span><span><?= $is_fixed ? 'Profit only' : 'Capital + Profit' ?></span></div>
    <?php if(!$can): ?>
    <div class="need-more"><i class="fas fa-info-circle"></i> You need at least ZMW <?= number_format($plan['min_amount'],2) ?></div>
    <?php endif ?>
    <button class="invest-btn" style="background:<?= $th['accent'] ?>"
            onclick='openModal(<?= json_encode($plan) ?>,<?= json_encode($th) ?>)'
            <?= !$can ? 'disabled' : '' ?>>
        <i class="fas fa-rocket"></i> <?= $can ? 'Invest Now' : 'Insufficient Balance' ?>
    </button>
</div>
<?php endforeach ?>
</div>

<!-- Investment Modal -->
<div id="investModal" class="modal">
<div class="modal-inner">
    <div class="modal-hdr">
        <h2 class="modal-title" id="modalTitle"></h2>
        <span class="close-btn" onclick="closeModal()">&times;</span>
    </div>

    <div class="modal-bal">
        <div>
            <div class="modal-bal-label"><i class="fas fa-wallet" style="margin-right:4px"></i>Your Wallet Balance</div>
        </div>
        <div class="modal-bal-amount">ZMW <?= number_format($user_balance,2) ?></div>
    </div>

    <div id="planTypeBox" class="pte"></div>

    <form method="POST" id="investForm" onsubmit="return handleSubmit()">
        <input type="hidden" name="plan_id" id="fPlanId">
        <input type="hidden" id="fRoi">
        <input type="hidden" id="fType">
        <input type="hidden" id="fDur">
        <input type="hidden" id="fMin">
        <input type="hidden" id="fMax">

        <label class="form-lbl"><i class="fas fa-coins" style="color:#FFD700;margin-right:3px"></i>Investment Amount (ZMW)</label>
        <div class="amt-wrap">
            <input type="number" name="amount" id="amtInput" class="amt-input"
                   placeholder="0.00" required step="0.01" min="0"
                   oninput="updatePreview()">
            <span class="cur-tag">ZMW</span>
        </div>
        <div class="range-hint" id="rangeHint"></div>

        <div class="insuf-warn" id="insufWarn">
            <i class="fas fa-exclamation-triangle"></i>
            Amount exceeds your balance of ZMW <?= number_format($user_balance,2) ?>.
            <a href="deposit.php"> Deposit more funds →</a>
        </div>

        <div class="preview-box" id="previewBox">
            <div class="pv-title"><i class="fas fa-calculator"></i> Investment Breakdown</div>
            <div class="pv-row">
                <span>Amount deducted now</span>
                <span id="pvDeduct" style="color:#f87171">- ZMW 0.00</span>
            </div>
            <!-- Profit-Only (fixed) plan rows -->
            <div id="fixedPv">
                <div class="pv-row"><span>Your profit (<span id="pvRoiPct">0</span>%)</span><span id="pvTotProfit" style="color:#4ade80">+ ZMW 0.00</span></div>
                <div class="pv-divider"></div>
                <div class="pv-row"><span>Capital returned?</span><span style="color:#f87171">❌ No</span></div>
                <div class="pv-row"><span><strong>Total you earn in <span id="pvDurText">0</span> days</strong></span><span id="pvEarn" style="color:#4ade80;font-size:12px">ZMW 0.00</span></div>
            </div>
            <!-- Profit + Capital (flexible) plan rows -->
            <div id="flexPv" style="display:none">
                <div class="pv-row"><span>Your profit (<span id="pvRoiPctF">0</span>%)</span><span id="pvFlexP" style="color:#4ade80">+ ZMW 0.00</span></div>
                <div class="pv-row"><span>Capital returned</span><span id="pvCap" style="color:#34d399">+ ZMW 0.00</span></div>
                <div class="pv-divider"></div>
                <div class="pv-row"><span><strong>Total payout on maturity</strong></span><span id="pvTotal" style="color:#4ade80;font-size:12px">ZMW 0.00</span></div>
            </div>
        </div>

        <button type="submit" class="confirm-btn" id="confirmBtn">
            <i class="fas fa-check-circle"></i> Confirm Investment
        </button>
    </form>
</div>
</div>

<script>
const USER_BAL = <?= $user_balance ?>;
let cur = null, busy = false;

function showTab(t) {
    document.querySelectorAll('.hiw-tab').forEach(el => el.classList.remove('active'));
    document.querySelectorAll('.hiw-panel').forEach(el => el.classList.remove('active'));
    document.getElementById('tab-'+t).classList.add('active');
    document.querySelector('.tab-'+t).classList.add('active');
}

function openModal(plan, th) {
    cur = plan; busy = false;
    document.getElementById('fPlanId').value = plan.id;
    document.getElementById('fRoi').value    = plan.roi_percentage;
    document.getElementById('fType').value   = plan.return_type;
    document.getElementById('fDur').value    = plan.duration_days;
    document.getElementById('fMin').value    = plan.min_amount;
    document.getElementById('fMax').value    = plan.max_amount;

    const ttl = document.getElementById('modalTitle');
    ttl.textContent = plan.name; ttl.style.color = th.accent;

    document.getElementById('rangeHint').textContent =
        'Range: ZMW ' + parseFloat(plan.min_amount).toLocaleString() +
        ' – ZMW ' + parseFloat(plan.max_amount).toLocaleString();
    document.getElementById('amtInput').value = '';
    document.getElementById('previewBox').style.display  = 'none';
    document.getElementById('insufWarn').style.display   = 'none';

    const btn = document.getElementById('confirmBtn');
    btn.style.background = th.accent; btn.disabled = false;
    btn.innerHTML = '<i class="fas fa-check-circle"></i> Confirm Investment';

    const box = document.getElementById('planTypeBox');
    if (plan.return_type === 'fixed') {
        box.className = 'pte pte-f';
        box.innerHTML =
            '<div class="pte-title"><i class="fas fa-lock"></i> Profit-Only Plan</div>' +
            '<div class="pte-row"><span style="color:#60a5fa;margin-right:4px">•</span><span style="color:rgba(255,255,255,.65)">Your capital is <strong style="color:#fff">deducted immediately</strong> and locked for ' + plan.duration_days + ' day' + (plan.duration_days > 1 ? 's' : '') + '</span></div>' +
            '<div class="pte-row"><span style="color:#60a5fa;margin-right:4px">•</span><span style="color:rgba(255,255,255,.65)">Profit = <strong style="color:#60a5fa">Amount × ' + plan.roi_percentage + '%</strong>, credited to your balance over the plan duration</span></div>' +
            '<div class="pte-row"><span style="color:#f87171;margin-right:4px">•</span><span style="color:#f87171">Capital is <strong>NOT returned</strong> — profit only</span></div>';
    } else {
        box.className = 'pte pte-x';
        box.innerHTML =
            '<div class="pte-title"><i class="fas fa-gem"></i> Profit + Capital Plan</div>' +
            '<div class="pte-row"><span style="color:#34d399;margin-right:4px">•</span><span style="color:rgba(255,255,255,.65)">Capital deducted now, plan runs for <strong style="color:#fff">' + plan.duration_days + ' day' + (plan.duration_days > 1 ? 's' : '') + '</strong></span></div>' +
            '<div class="pte-row"><span style="color:#34d399;margin-right:4px">•</span><span style="color:rgba(255,255,255,.65)">On maturity: you receive <strong style="color:#34d399">Capital + ' + plan.roi_percentage + '% profit</strong> in one lump sum</span></div>' +
            '<div class="pte-row"><span style="color:#34d399;margin-right:4px">✅</span><span style="color:#34d399"><strong>Your full capital is returned plus profit</strong></span></div>';
    }

    document.getElementById('investModal').style.display = 'block';
}

function updatePreview() {
    if (!cur) return;
    const amt = parseFloat(document.getElementById('amtInput').value) || 0;
    const min = parseFloat(cur.min_amount);
    const max = parseFloat(cur.max_amount);
    const btn = document.getElementById('confirmBtn');
    const iw  = document.getElementById('insufWarn');

    if (amt > USER_BAL && amt > 0) {
        iw.style.display = 'block';
        btn.disabled = true;
    } else {
        iw.style.display = 'none';
        btn.disabled = (amt <= 0 || amt < min || amt > max);
    }

    if (amt <= 0) { document.getElementById('previewBox').style.display = 'none'; return; }

    const roi    = parseFloat(cur.roi_percentage);
    const dur    = parseInt(cur.duration_days);
    // Core formula: profit = amount × roi%  (same for both plan types)
    const profit = parseFloat(((amt * roi) / 100).toFixed(2));

    document.getElementById('pvDeduct').textContent = '- ZMW ' + amt.toFixed(2);

    if (cur.return_type === 'fixed') {
        document.getElementById('pvRoiPct').textContent     = roi;
        document.getElementById('pvTotProfit').textContent  = '+ ZMW ' + profit.toFixed(2);
        document.getElementById('pvDurText').textContent    = dur;
        document.getElementById('pvEarn').textContent       = 'ZMW ' + profit.toFixed(2);
        document.getElementById('fixedPv').style.display   = 'block';
        document.getElementById('flexPv').style.display    = 'none';
    } else {
        const total = parseFloat((amt + profit).toFixed(2));
        document.getElementById('pvRoiPctF').textContent   = roi;
        document.getElementById('pvFlexP').textContent     = '+ ZMW ' + profit.toFixed(2);
        document.getElementById('pvCap').textContent       = '+ ZMW ' + amt.toFixed(2);
        document.getElementById('pvTotal').textContent     = 'ZMW ' + total.toFixed(2);
        document.getElementById('fixedPv').style.display  = 'none';
        document.getElementById('flexPv').style.display   = 'block';
    }
    document.getElementById('previewBox').style.display = 'block';
}

function handleSubmit() {
    if (busy) return false;
    const amt = parseFloat(document.getElementById('amtInput').value) || 0;
    if (amt <= 0 || amt > USER_BAL) return false;
    busy = true;
    const btn = document.getElementById('confirmBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing…';
    return true;
}

function closeModal() {
    document.getElementById('investModal').style.display = 'none';
    cur = null; busy = false;
}
window.onclick = e => { if (e.target === document.getElementById('investModal')) closeModal(); };
setTimeout(() => {
    document.querySelectorAll('.msg').forEach(m => {
        m.style.transition = 'opacity .5s'; m.style.opacity = '0';
        setTimeout(() => m.remove(), 500);
    });
}, 6000);
var np = document.querySelector('.nav-item[href="plans.php"]');
if (np) np.classList.add('active');
</script>
<?php include 'bottom-nav.php'; ?>
</body>
</html>