<?php
require_once 'db.php';
require_once 'auth_check.php';
require_once 'currency.php';

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

// ── Safe currency formatter fallback ─────────────────────
if (!function_exists('fmt_currency')) {
    function fmt_currency($amount) {
        return 'TZS ' . number_format((float)$amount, 2);
    }
}

$msg = ''; $msg_type = '';

// ── Check tables exist ────────────────────────────────────
$tables_ok = true;
$chk = $conn->query("SHOW TABLES LIKE 'investment_plans'");
if (!$chk || $chk->num_rows === 0) {
    $tables_ok = false;
}
$chk2 = $conn->query("SHOW TABLES LIKE 'investments'");
if (!$chk2 || $chk2->num_rows === 0) {
    $tables_ok = false;
}

// ── Handle invest POST ────────────────────────────────────
if ($tables_ok && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['invest_plan_id'])) {
    $plan_id = (int)$_POST['invest_plan_id'];
    $amount  = (float)($_POST['invest_amount'] ?? 0);

    $res  = $conn->query("SELECT * FROM investment_plans WHERE id=$plan_id AND active=1");
    $plan = ($res) ? $res->fetch_assoc() : null;

    if (!$plan) {
        $msg = 'Investment plan not found or inactive.';
        $msg_type = 'danger';
    } elseif ($amount < $plan['min_amount']) {
        $msg = 'Minimum investment for this plan is ' . fmt_currency($plan['min_amount']);
        $msg_type = 'danger';
    } elseif ($amount > $plan['max_amount']) {
        $msg = 'Maximum investment for this plan is ' . fmt_currency($plan['max_amount']);
        $msg_type = 'danger';
    } else {
        $ures = $conn->query("SELECT * FROM users WHERE id=$user_id");
        $user = ($ures) ? $ures->fetch_assoc() : null;

        if (!$user || $user['balance'] < $amount) {
            $msg = 'Insufficient balance. Your balance is ' . fmt_currency($user['balance'] ?? 0);
            $msg_type = 'danger';
        } else {
            $conn->query("UPDATE users SET balance = balance - $amount WHERE id=$user_id");
            $ends_at      = date('Y-m-d H:i:s', strtotime("+{$plan['cycle_days']} days"));
            $total_return = $amount + ($amount * ($plan['daily_rate'] / 100) * $plan['cycle_days']);
            $pname        = $conn->real_escape_string($plan['name']);

            $conn->query("INSERT INTO investments
                (user_id, plan_id, plan_name, amount, daily_rate, cycle_days, total_return, started_at, ends_at)
                VALUES ($user_id, $plan_id, '$pname', $amount, {$plan['daily_rate']}, {$plan['cycle_days']}, $total_return, NOW(), '$ends_at')");

            $desc = $conn->real_escape_string("Investment in {$plan['name']} plan");
            $conn->query("INSERT INTO account_logs (user_id, type, category, amount, description)
                VALUES ($user_id, 'expense', 'deposit', $amount, '$desc')");

            $msg = "Investment of " . fmt_currency($amount) . " in <strong>{$plan['name']}</strong> started! 🎉";
            $msg_type = 'success';
        }
    }
}

// ── Fetch data safely ─────────────────────────────────────
$ures = $conn->query("SELECT * FROM users WHERE id=$user_id");
$user = ($ures) ? $ures->fetch_assoc() : ['balance'=>0,'full_name'=>'User'];

$plans          = [];
$my_investments = [];

if ($tables_ok) {
    $pres = $conn->query("SELECT * FROM investment_plans WHERE active=1 ORDER BY sort_order ASC, id ASC");
    if ($pres) $plans = $pres->fetch_all(MYSQLI_ASSOC);

    $ires = $conn->query("SELECT * FROM investments WHERE user_id=$user_id ORDER BY started_at DESC");
    if ($ires) $my_investments = $ires->fetch_all(MYSQLI_ASSOC);
}

// Summary stats
$total_invested = 0; $total_earning = 0; $active_count = 0;
foreach ($my_investments as $inv) {
    if ($inv['status'] === 'active') {
        $total_invested += $inv['amount'];
        $total_earning  += $inv['total_return'];
        $active_count++;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Investments</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.11.3/font/bootstrap-icons.min.css">
<style>
  :root {
    --bg:     #080b14;
    --bg2:    #0e1220;
    --bg3:    #141829;
    --card:   #131726;
    --border: #1e2540;
    --accent: #6c63ff;
    --gold:   #f5a623;
    --green:  #00d4aa;
    --red:    #ff4f6a;
    --text:   #e8eaf6;
    --muted:  #6a7595;
  }
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
  html, body { width: 100%; min-height: 100vh; }
  body {
    background: var(--bg);
    color: var(--text);
    font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
    padding-bottom: 90px;
  }

  /* ── Topbar ── */
  .topbar {
    background: var(--bg3);
    border-bottom: 1px solid var(--border);
    padding: 13px 16px;
    display: flex; align-items: center; justify-content: space-between;
    position: sticky; top: 0; z-index: 200;
  }
  .topbar-left   { display: flex; align-items: center; gap: 10px; }
  .back-btn      { color: var(--muted); font-size: 20px; text-decoration: none; line-height: 1; }
  .topbar-title  { font-weight: 700; font-size: 16px; }
  .balance-chip  {
    background: rgba(108,99,255,.18);
    color: #a9a3ff; border-radius: 20px;
    padding: 5px 12px; font-size: 12px; font-weight: 600;
    display: flex; align-items: center; gap: 5px;
    white-space: nowrap;
  }

  /* ── Alerts ── */
  .alert-msg {
    margin: 10px 14px; border-radius: 12px;
    padding: 12px 14px; font-size: 13px;
    display: flex; align-items: flex-start; gap: 8px;
  }
  .alert-success { background: rgba(0,212,170,.12); color: var(--green); border: 1px solid rgba(0,212,170,.3); }
  .alert-danger  { background: rgba(255,79,106,.12); color: var(--red);   border: 1px solid rgba(255,79,106,.3); }
  .alert-warning { background: rgba(245,166,35,.12); color: var(--gold);  border: 1px solid rgba(245,166,35,.3); }

  /* ── Stats row ── */
  .stats-row {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10px; padding: 14px;
  }
  .stat-box {
    background: var(--card); border: 1px solid var(--border);
    border-radius: 14px; padding: 13px 12px; text-align: center;
  }
  .stat-box .lbl  { font-size: 10px; color: var(--muted); text-transform: uppercase; letter-spacing: .5px; margin-bottom: 5px; }
  .stat-box .val  { font-size: 14px; font-weight: 700; word-break: break-all; }

  /* ── Section heading ── */
  .sec-head {
    display: flex; align-items: center; gap: 8px;
    padding: 14px 14px 8px;
    font-size: 14px; font-weight: 700;
  }
  .sec-dot { width: 7px; height: 7px; border-radius: 50%; flex-shrink: 0; }

  /* ── Plan cards scroll ── */
  .plans-wrap {
    overflow-x: auto; padding: 0 14px 10px;
    display: flex; gap: 12px;
    -webkit-overflow-scrolling: touch;
    scrollbar-width: none;
  }
  .plans-wrap::-webkit-scrollbar { display: none; }

  .plan-card {
    flex-shrink: 0; width: 210px;
    border-radius: 18px; padding: 18px 16px;
    cursor: pointer; position: relative; overflow: hidden;
    border: 2px solid transparent;
    transition: transform .2s, box-shadow .2s;
  }
  .plan-card:active { transform: scale(.97); }
  .plan-card::before {
    content: ''; position: absolute; inset: 0;
    background: rgba(0,0,0,.28); z-index: 0;
    border-radius: inherit;
  }
  .plan-card > * { position: relative; z-index: 1; }

  .plan-name  { font-size: 17px; font-weight: 800; color: #fff; margin-bottom: 12px; }
  .plan-desc  { font-size: 11px; color: rgba(255,255,255,.65); margin-bottom: 10px; }
  .plan-row   {
    display: flex; justify-content: space-between; align-items: center;
    font-size: 11.5px; margin-bottom: 6px;
  }
  .plan-row .pl { color: rgba(255,255,255,.6); }
  .plan-row .pv { font-weight: 700; color: #fff; font-size: 12px; }
  .plan-row .pv.hi { color: #ffe96a; font-size: 14px; }
  .plan-row .pv.gr { color: #b8ffea; }

  .plan-btn {
    width: 100%; margin-top: 12px;
    background: rgba(255,255,255,.2);
    border: 1px solid rgba(255,255,255,.35);
    color: #fff; border-radius: 9px; padding: 8px;
    font-size: 13px; font-weight: 700; cursor: pointer;
    transition: background .2s;
  }
  .plan-btn:active { background: rgba(255,255,255,.35); }

  /* ── My investment cards ── */
  .inv-card {
    background: var(--card); border: 1px solid var(--border);
    border-radius: 14px; padding: 14px; margin: 0 14px 10px;
  }
  .inv-head {
    display: flex; justify-content: space-between; align-items: center;
    margin-bottom: 11px;
  }
  .inv-name   { font-weight: 700; font-size: 14px; display: flex; align-items: center; gap: 6px; }
  .inv-badge  { font-size: 10px; padding: 3px 9px; border-radius: 20px; font-weight: 700; }
  .b-active    { background: rgba(0,212,170,.15);  color: var(--green); }
  .b-completed { background: rgba(245,166,35,.15); color: var(--gold);  }
  .b-cancelled { background: rgba(255,79,106,.15); color: var(--red);   }

  .inv-row {
    display: flex; justify-content: space-between; align-items: center;
    font-size: 12px; padding: 5px 0;
    border-bottom: 1px solid rgba(255,255,255,.04);
  }
  .inv-row:last-of-type { border-bottom: none; }
  .inv-row .ik { color: var(--muted); }
  .inv-row .iv { font-weight: 600; font-size: 12.5px; }

  .prog-wrap  { height: 5px; background: rgba(255,255,255,.07); border-radius: 10px; margin-top: 10px; overflow: hidden; }
  .prog-fill  { height: 100%; border-radius: 10px; background: linear-gradient(90deg, var(--accent), var(--green)); }
  .prog-lbl   { display: flex; justify-content: space-between; font-size: 10px; color: var(--muted); margin-top: 4px; }

  /* ── Empty state ── */
  .empty-state {
    text-align: center; padding: 36px 20px; color: var(--muted);
  }
  .empty-state i   { font-size: 38px; margin-bottom: 10px; display: block; }
  .empty-state p   { font-size: 13px; }

  /* ── Modal ── */
  .modal-content  { background: var(--bg3) !important; border: 1px solid var(--border) !important; border-radius: 20px !important; }
  .modal-header   { border-bottom: 1px solid var(--border) !important; padding: 16px 20px !important; }
  .modal-body     { padding: 18px 20px !important; }
  .modal-footer   { border-top: 1px solid var(--border) !important; padding: 14px 20px !important; flex-direction: column; gap: 8px; }

  .amt-wrap {
    background: var(--bg2); border: 1px solid var(--border);
    border-radius: 12px; padding: 12px 14px;
    display: flex; align-items: center; gap: 8px;
    transition: border .2s;
  }
  .amt-wrap:focus-within { border-color: var(--accent); }
  .amt-cur  { font-size: 11px; color: var(--muted); font-weight: 700; white-space: nowrap; }
  .amt-inp  {
    flex: 1; background: none; border: none; outline: none;
    color: var(--text); font-size: 22px; font-weight: 700;
    width: 100%; min-width: 0;
  }
  .amt-inp::placeholder { color: var(--muted); }

  .quick-row  { display: flex; gap: 7px; margin-top: 9px; }
  .qbtn       {
    flex: 1; background: var(--bg2); border: 1px solid var(--border);
    color: var(--muted); border-radius: 8px; padding: 7px 4px;
    font-size: 11px; font-weight: 700; cursor: pointer;
    transition: all .2s; text-align: center;
  }
  .qbtn:active { border-color: var(--accent); color: var(--accent); background: rgba(108,99,255,.12); }

  .ret-box    {
    background: rgba(0,212,170,.07); border: 1px solid rgba(0,212,170,.2);
    border-radius: 12px; padding: 13px 14px; margin-top: 14px;
  }
  .ret-row    { display: flex; justify-content: space-between; font-size: 12.5px; padding: 3px 0; }
  .ret-row .rk { color: var(--muted); }
  .ret-row .rv { font-weight: 600; }
  .ret-total  {
    display: flex; justify-content: space-between;
    font-weight: 800; font-size: 15px;
    border-top: 1px solid rgba(0,212,170,.2);
    margin-top: 8px; padding-top: 8px;
  }
  .ret-total .rtv { color: var(--green); }

  .valid-note { font-size: 12px; color: var(--red); margin-top: 9px; display: none; }

  .confirm-btn {
    width: 100%;
    background: linear-gradient(135deg, var(--accent), #8b7cf8);
    border: none; color: #fff; border-radius: 12px;
    padding: 13px; font-size: 14px; font-weight: 700;
    cursor: pointer; transition: opacity .2s;
  }
  .confirm-btn:disabled { opacity: .4; cursor: not-allowed; }
  .bal-note { font-size: 11px; color: var(--muted); text-align: center; }

  .support-link {
    display: block; text-align: center;
    padding: 16px; font-size: 13px;
    color: var(--muted); text-decoration: none;
  }
</style>
</head>
<body>

<!-- Topbar -->
<div class="topbar">
  <div class="topbar-left">
    <a href="dashboard.php" class="back-btn"><i class="bi bi-arrow-left"></i></a>
    <span class="topbar-title"><i class="bi bi-graph-up-arrow me-1" style="color:var(--accent)"></i> Investments</span>
  </div>
  <div class="balance-chip">
    <i class="bi bi-wallet2"></i>
    <?= fmt_currency($user['balance'] ?? 0) ?>
  </div>
</div>

<!-- ── Table missing warning ── -->
<?php if (!$tables_ok): ?>
<div class="alert-msg alert-warning" style="margin-top:14px">
  <i class="bi bi-exclamation-triangle-fill" style="flex-shrink:0"></i>
  <div>Investment tables not found. Please run <strong>investment_migration.sql</strong> on your database first.</div>
</div>
<?php endif; ?>

<!-- ── Flash message ── -->
<?php if ($msg): ?>
<div class="alert-msg alert-<?= $msg_type ?>">
  <i class="bi bi-<?= $msg_type === 'success' ? 'check-circle-fill' : 'exclamation-triangle-fill' ?>" style="flex-shrink:0;margin-top:1px"></i>
  <div><?= $msg ?></div>
</div>
<?php endif; ?>

<!-- ── Stats ── -->
<div class="stats-row">
  <div class="stat-box">
    <div class="lbl">Active</div>
    <div class="val" style="color:var(--accent)"><?= $active_count ?></div>
  </div>
  <div class="stat-box">
    <div class="lbl">Invested</div>
    <div class="val"><?= fmt_currency($total_invested) ?></div>
  </div>
  <div class="stat-box">
    <div class="lbl">Est. Return</div>
    <div class="val" style="color:var(--green)"><?= fmt_currency($total_earning) ?></div>
  </div>
</div>

<!-- ── Plans ── -->
<div class="sec-head">
  <div class="sec-dot" style="background:var(--accent)"></div>
  Investment Plans
</div>

<?php if (!$tables_ok || empty($plans)): ?>
  <div class="empty-state">
    <i class="bi bi-inbox"></i>
    <p><?= !$tables_ok ? 'Run the SQL migration to enable investment plans.' : 'No investment plans available yet.' ?></p>
  </div>
<?php else: ?>
<div class="plans-wrap">
  <?php foreach ($plans as $p):
    $total_pct = round($p['daily_rate'] * $p['cycle_days'], 1);
  ?>
  <div class="plan-card"
    style="background: linear-gradient(140deg, <?= htmlspecialchars($p['color_from']) ?>, <?= htmlspecialchars($p['color_to']) ?>)"
    onclick="openInvest(<?= htmlspecialchars(json_encode($p), ENT_QUOTES) ?>)">

    <div class="plan-name"><?= htmlspecialchars($p['name']) ?></div>
    <?php if (!empty($p['description'])): ?>
      <div class="plan-desc"><?= htmlspecialchars($p['description']) ?></div>
    <?php endif; ?>

    <div class="plan-row">
      <span class="pl">Minimum Amount</span>
      <span class="pv">TZS <?= number_format($p['min_amount']) ?></span>
    </div>
    <div class="plan-row">
      <span class="pl">Maximum Amount</span>
      <span class="pv">TZS <?= number_format($p['max_amount']) ?></span>
    </div>
    <div class="plan-row">
      <span class="pl">Daily Increase</span>
      <span class="pv hi"><?= $p['daily_rate'] ?>%</span>
    </div>
    <div class="plan-row">
      <span class="pl">Project Cycle</span>
      <span class="pv"><?= $p['cycle_days'] ?> days</span>
    </div>
    <div class="plan-row" style="margin-top:4px">
      <span class="pl">Total Return</span>
      <span class="pv gr"><?= $total_pct ?>% profit</span>
    </div>

    <button class="plan-btn" type="button">
      <i class="bi bi-lightning-charge-fill"></i> Invest Now
    </button>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>

<!-- ── My Investments ── -->
<div class="sec-head" style="margin-top:6px">
  <div class="sec-dot" style="background:var(--gold)"></div>
  My Investments
  <span style="font-size:11px;color:var(--muted);font-weight:400">(<?= count($my_investments) ?>)</span>
</div>

<?php if (empty($my_investments)): ?>
  <div class="empty-state">
    <i class="bi bi-currency-dollar"></i>
    <p>No investments yet.<br>Pick a plan above to get started!</p>
  </div>
<?php else: ?>
  <?php foreach ($my_investments as $inv):
    $now         = time();
    $start       = strtotime($inv['started_at']);
    $end         = strtotime($inv['ends_at'] ?? '+1 day');
    $duration    = max(1, $end - $start);
    $elapsed     = min($now - $start, $duration);
    $progress    = min(100, round(($elapsed / $duration) * 100));
    $days_left   = max(0, ceil(($end - $now) / 86400));
    $days_passed = max(0, floor($elapsed / 86400));
    $daily_earn  = $inv['amount'] * ($inv['daily_rate'] / 100);
  ?>
  <div class="inv-card">
    <div class="inv-head">
      <div class="inv-name">
        <i class="bi bi-bar-chart-fill" style="color:var(--accent)"></i>
        <?= htmlspecialchars($inv['plan_name'] ?? 'Plan #'.$inv['plan_id']) ?>
      </div>
      <span class="inv-badge b-<?= $inv['status'] ?>"><?= ucfirst($inv['status']) ?></span>
    </div>

    <div class="inv-row">
      <span class="ik">Principal</span>
      <span class="iv"><?= fmt_currency($inv['amount']) ?></span>
    </div>
    <div class="inv-row">
      <span class="ik">Daily Earning</span>
      <span class="iv" style="color:var(--green)"><?= fmt_currency($daily_earn) ?>/day</span>
    </div>
    <div class="inv-row">
      <span class="ik">Total Return</span>
      <span class="iv" style="color:var(--gold)"><?= fmt_currency($inv['total_return']) ?></span>
    </div>
    <div class="inv-row">
      <span class="ik">Start Date</span>
      <span class="iv"><?= date('d M Y', $start) ?></span>
    </div>
    <div class="inv-row">
      <span class="ik">Maturity Date</span>
      <span class="iv"><?= date('d M Y', $end) ?></span>
    </div>
    <?php if ($inv['status'] === 'active'): ?>
    <div class="inv-row">
      <span class="ik">Days Remaining</span>
      <span class="iv" style="color:<?= $days_left <= 7 ? 'var(--gold)' : 'var(--text)' ?>">
        <?= $days_left > 0 ? $days_left.' days' : '<span style="color:var(--green)">Matured!</span>' ?>
      </span>
    </div>
    <div class="prog-wrap">
      <div class="prog-fill" style="width:<?= $progress ?>%"></div>
    </div>
    <div class="prog-lbl">
      <span><?= $progress ?>% complete</span>
      <span><?= $days_passed ?>/<?= $inv['cycle_days'] ?> days</span>
    </div>
    <?php endif; ?>
  </div>
  <?php endforeach; ?>
<?php endif; ?>

<a href="<?= htmlspecialchars($support_url) ?>" class="support-link" target="_blank">
  <i class="bi bi-headset me-1"></i> Contact Support
</a>

<!-- ── Invest Modal ── -->
<div class="modal fade" id="investModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered" style="margin:16px auto;max-width:420px">
    <div class="modal-content">
      <div class="modal-header">
        <div>
          <div id="mPlanName" style="font-weight:800;font-size:17px"></div>
          <div id="mPlanSub"  style="font-size:11px;color:var(--muted);margin-top:2px"></div>
        </div>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST" onsubmit="return validateForm()">
        <div class="modal-body">
          <input type="hidden" name="invest_plan_id" id="mPlanId">
          <div style="font-size:11px;color:var(--muted);margin-bottom:7px;font-weight:700;text-transform:uppercase;letter-spacing:.5px">
            Amount (TZS)
          </div>
          <div class="amt-wrap">
            <span class="amt-cur">TZS</span>
            <input type="number" name="invest_amount" id="mAmt" class="amt-inp"
              placeholder="Enter amount" step="100" oninput="calcPreview()">
          </div>
          <div class="quick-row" id="quickRow"></div>

          <div class="ret-box" id="retBox" style="display:none">
            <div class="ret-row"><span class="rk">Principal</span><span class="rv" id="rPrincipal"></span></div>
            <div class="ret-row"><span class="rk">Daily Earning</span><span class="rv" style="color:var(--green)" id="rDaily"></span></div>
            <div class="ret-row"><span class="rk">Total Profit</span><span class="rv" style="color:var(--gold)" id="rProfit"></span></div>
            <div class="ret-row"><span class="rk">Cycle</span><span class="rv" id="rCycle"></span></div>
            <div class="ret-total">
              <span>Total Return</span>
              <span class="rtv" id="rTotal"></span>
            </div>
          </div>
          <div class="valid-note" id="vNote"></div>
        </div>
        <div class="modal-footer">
          <button type="submit" class="confirm-btn" id="cBtn" disabled>
            <i class="bi bi-lightning-charge-fill me-1"></i> Confirm Investment
          </button>
          <div class="bal-note">Balance: <strong style="color:var(--text)"><?= fmt_currency($user['balance'] ?? 0) ?></strong></div>
        </div>
      </form>
    </div>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/js/bootstrap.bundle.min.js"></script>
<script>
const BAL = <?= (float)($user['balance'] ?? 0) ?>;
let CP = null; // current plan

const tzsFmt = n => 'TZS ' + (+n).toLocaleString('en-US',{minimumFractionDigits:2,maximumFractionDigits:2});
const shortFmt = n => n >= 1e6 ? (n/1e6).toFixed(1)+'M' : n >= 1e3 ? (n/1e3).toFixed(n%1e3?1:0)+'K' : String(n);

function openInvest(p) {
  CP = p;
  document.getElementById('mPlanId').value   = p.id;
  document.getElementById('mPlanName').textContent = p.name + ' Plan';
  document.getElementById('mPlanSub').textContent  = p.daily_rate + '% daily · ' + p.cycle_days + ' day cycle';
  document.getElementById('mAmt').value = '';
  document.getElementById('retBox').style.display = 'none';
  document.getElementById('vNote').style.display  = 'none';
  document.getElementById('cBtn').disabled = true;

  // quick buttons
  const qr = document.getElementById('quickRow');
  qr.innerHTML = '';
  const min = +p.min_amount, max = +p.max_amount;
  const pts = [...new Set([min, Math.round(min+(max-min)*.25), Math.round(min+(max-min)*.5), max])];
  pts.forEach(a => {
    const b = document.createElement('button');
    b.type = 'button'; b.className = 'qbtn';
    b.textContent = shortFmt(a);
    b.onclick = () => { document.getElementById('mAmt').value = a; calcPreview(); };
    qr.appendChild(b);
  });

  bootstrap.Modal.getOrCreateInstance(document.getElementById('investModal')).show();
}

function calcPreview() {
  const amt  = +document.getElementById('mAmt').value || 0;
  const note = document.getElementById('vNote');
  const box  = document.getElementById('retBox');
  const btn  = document.getElementById('cBtn');
  note.style.display = 'none'; box.style.display = 'none'; btn.disabled = true;
  if (!CP || amt <= 0) return;

  if (amt < +CP.min_amount) {
    note.textContent = '⚠ Minimum: TZS ' + (+CP.min_amount).toLocaleString();
    note.style.display = 'block'; return;
  }
  if (amt > +CP.max_amount) {
    note.textContent = '⚠ Maximum: TZS ' + (+CP.max_amount).toLocaleString();
    note.style.display = 'block'; return;
  }
  if (amt > BAL) {
    note.textContent = '⚠ Insufficient balance (' + tzsFmt(BAL) + ')';
    note.style.display = 'block'; return;
  }

  const daily  = amt * (CP.daily_rate / 100);
  const profit = daily * CP.cycle_days;
  const total  = amt + profit;
  document.getElementById('rPrincipal').textContent = tzsFmt(amt);
  document.getElementById('rDaily').textContent     = tzsFmt(daily) + '/day';
  document.getElementById('rProfit').textContent    = tzsFmt(profit);
  document.getElementById('rCycle').textContent     = CP.cycle_days + ' days';
  document.getElementById('rTotal').textContent     = tzsFmt(total);
  box.style.display = ''; btn.disabled = false;
}

function validateForm() {
  const amt = +document.getElementById('mAmt').value || 0;
  if (!CP || amt <= 0 || amt < +CP.min_amount || amt > +CP.max_amount || amt > BAL) {
    calcPreview(); return false;
  }
  return true;
}
</script>

<?php include 'navigation_bottom.php'; ?>
</body>
</html>