<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
require_once 'includes/auth.php';
requireUserLogin();
$currentUser = currentUser($pdo);
$uid = (int)$_SESSION['user_id'];
$error = ''; $success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && verify_csrf()) {
    $tier      = $_POST['plan_tier'] ?? 'starter';
    $amount    = (float)$_POST['principal_amount'] ?? 0;
    $payout    = $_POST['payout_frequency'] ?? 'monthly';

    $plans = ['starter'=>['Starter',5,6],'basic'=>['Basic',8,12],'silver'=>['Silver',10,12],'gold'=>['Gold',13,24],'platinum'=>['Platinum',15,36],'vip'=>['VIP',18,60]];
    [$planName,$rate,$duration] = $plans[$tier] ?? ['Starter',5,6];

    if ($amount <= 0) { $error = 'Enter a valid investment amount.'; goto done; }
    if ((float)$currentUser['available_balance'] < $amount) { $error = 'Insufficient balance for this investment.'; goto done; }

    $ref   = generateRef('INV');
    $start = date('Y-m-d');
    $maturity = date('Y-m-d', strtotime("+$duration months"));
    $pdo->prepare("INSERT INTO investments (user_id,reference_number,plan_name,plan_tier,principal_amount,interest_rate,duration_months,payout_frequency,status,start_date,maturity_date) VALUES (?,?,?,?,?,?,?,?,'active',?,?)")->execute([$uid,$ref,$planName,$tier,$amount,$rate,$duration,$payout,$start,$maturity]);
    $pdo->prepare("UPDATE users SET account_balance=account_balance-?,available_balance=available_balance-? WHERE id=?")->execute([$amount,$amount,$uid]);
    $pdo->prepare("INSERT INTO transactions (user_id,transaction_type,amount,currency,description,reference_number,status,processed_at) VALUES (?,'debit',?,(SELECT currency FROM users WHERE id=? LIMIT 1),'Investment: $planName Plan',?,'completed',NOW())")->execute([$uid,$amount,$uid,$ref]);
    addNotification($pdo,$uid,'Investment Activated',"Your $planName plan investment of ".money($amount,$currentUser['currency'])." has been activated. Matures: $maturity",'success');
    $success = "Investment activated! Reference: <strong>$ref</strong>. Expected return at $rate% for $duration months.";
}
done:

$invs = $pdo->prepare("SELECT * FROM investments WHERE user_id=? ORDER BY created_at DESC");
$invs->execute([$uid]); $invList = $invs->fetchAll();
$pageTitle = 'Investments';
?>
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= $pageTitle ?> | <?= SITE_NAME ?></title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link rel="stylesheet" href="/assets/css/style.css">
</head><body>
<?php include 'includes/header.php'; ?>
<div class="page-wrapper"><div class="container">
<div class="d-flex justify-content-between align-items-center mb-3">
  <div class="page-title mb-0"><i class="fa fa-chart-line me-2 text-danger"></i>Investment Plans</div>
  <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#investModal"><i class="fa fa-plus me-1"></i>Invest Now</button>
</div>
<?php if ($error): ?><div class="alert alert-danger"><?= sanitize($error) ?></div><?php endif; ?>
<?php if ($success): ?><div class="alert alert-success"><?= $success ?></div><?php endif; ?>

<!-- Plans Grid -->
<div class="row g-3 mb-4">
<?php $plans=[
  ['starter','Starter','5%','6 months','Monthly','$100 min','primary'],
  ['basic','Basic','8%','12 months','Monthly','$500 min','dark'],
  ['silver','Silver','10%','12 months','Quarterly','$1,000 min','blue'],
  ['gold','Gold','13%','24 months','Quarterly','$5,000 min','gold'],
  ['platinum','Platinum','15%','36 months','On Maturity','$10,000 min','primary'],
  ['vip','VIP','18%','60 months','On Maturity','$50,000 min','dark'],
];
foreach ($plans as [$tier,$name,$rate,$dur,$freq,$min,$cls]): ?>
<div class="col-6 col-md-4">
  <div class="stat-card <?= $cls ?> h-100" style="cursor:pointer;" onclick="selectPlan('<?= $tier ?>')">
    <div class="label"><?= $name ?> Plan</div>
    <div class="value"><?= $rate ?> APR</div>
    <div class="small mt-2 opacity-85"><?= $dur ?> &bull; <?= $freq ?></div>
    <div class="small opacity-75"><?= $min ?></div>
  </div>
</div>
<?php endforeach; ?>
</div>

<div class="card">
  <div class="card-header">My Investments</div>
  <div class="table-responsive">
    <table class="table table-hover mb-0">
      <thead><tr><th>Ref</th><th>Plan</th><th>Principal</th><th>Rate</th><th>Payout</th><th>Start</th><th>Matures</th><th>Status</th></tr></thead>
      <tbody>
      <?php if (empty($invList)): ?>
      <tr><td colspan="8" class="text-center py-4 text-muted">No active investments.</td></tr>
      <?php else: foreach ($invList as $inv): ?>
      <tr>
        <td><code class="small"><?= sanitize($inv['reference_number']) ?></code></td>
        <td><?= sanitize($inv['plan_name']) ?></td>
        <td><?= money((float)$inv['principal_amount'],$currentUser['currency']) ?></td>
        <td><?= $inv['interest_rate'] ?>%</td>
        <td><?= ucfirst(str_replace('_',' ',$inv['payout_frequency'])) ?></td>
        <td class="small"><?= $inv['start_date'] ?></td>
        <td class="small"><?= $inv['maturity_date'] ?></td>
        <td><?= statusBadge($inv['status']) ?></td>
      </tr>
      <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>
</div>
</div></div>
<?php include 'includes/footer.php'; ?>
<!-- Invest Modal -->
<div class="modal fade" id="investModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
  <div class="modal-header"><h5 class="modal-title">Invest Now</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
  <form method="POST"><div class="modal-body">
    <?= csrf_field() ?>
    <div class="mb-3"><label class="form-label">Investment Plan</label>
      <select name="plan_tier" id="planTier" class="form-select">
        <option value="starter">Starter – 5% APR (6 months)</option>
        <option value="basic">Basic – 8% APR (12 months)</option>
        <option value="silver">Silver – 10% APR (12 months)</option>
        <option value="gold">Gold – 13% APR (24 months)</option>
        <option value="platinum">Platinum – 15% APR (36 months)</option>
        <option value="vip">VIP – 18% APR (60 months)</option>
      </select>
    </div>
    <div class="mb-3"><label class="form-label">Amount (<?= $currentUser['currency'] ?>)</label>
      <div class="input-group"><span class="input-group-text">$</span><input type="number" name="principal_amount" class="form-control amount-input" step="100" min="100" required></div>
      <small class="text-muted">Available: <?= money((float)$currentUser['available_balance'],$currentUser['currency']) ?></small>
    </div>
    <div class="mb-3"><label class="form-label">Payout Frequency</label>
      <select name="payout_frequency" class="form-select">
        <option value="monthly">Monthly</option><option value="quarterly">Quarterly</option><option value="on_maturity">On Maturity</option>
      </select>
    </div>
  </div>
  <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button><button class="btn btn-primary fw-bold">Activate Investment</button></div>
  </form>
</div></div></div>
<script>
function selectPlan(tier) {
  document.getElementById('planTier').value = tier;
  new bootstrap.Modal(document.getElementById('investModal')).show();
}
</script>
</body></html>
