<?php
require_once '../includes/config.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
requireAdminLogin();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && verify_csrf()) {
    $iid = (int)$_POST['inv_id'];
    $action = $_POST['action'] ?? '';
    if ($action === 'mature') {
        $inv = $pdo->prepare("SELECT * FROM investments WHERE id=? LIMIT 1"); $inv->execute([$iid]); $i=$inv->fetch();
        if ($i) {
            $returns = round((float)$i['principal_amount'] * ($i['interest_rate']/100) * ($i['duration_months']/12), 2);
            $total   = (float)$i['principal_amount'] + $returns;
            $pdo->prepare("UPDATE investments SET status='matured',expected_returns=?,actual_returns=?,matured_at=NOW() WHERE id=?")->execute([$returns,$returns,$iid]);
            creditAccount($pdo,(int)$i['user_id'],$total,'Investment Matured: '.$i['plan_name'].' (Ref:'.$i['reference_number'].')');
            addNotification($pdo,(int)$i['user_id'],'Investment Matured','Your '.$i['plan_name'].' investment has matured. '.money($total).' credited to your account.','success');
            flash('success','Investment marked as matured and payout credited.');
        }
    }
    if ($action === 'cancel') {
        $inv=$pdo->prepare("SELECT * FROM investments WHERE id=? LIMIT 1");$inv->execute([$iid]);$i=$inv->fetch();
        if ($i) {
            $pdo->prepare("UPDATE investments SET status='cancelled' WHERE id=?")->execute([$iid]);
            creditAccount($pdo,(int)$i['user_id'],(float)$i['principal_amount'],'Investment Refund: '.$i['reference_number']);
            addNotification($pdo,(int)$i['user_id'],'Investment Cancelled','Your investment has been cancelled and principal refunded.','info');
            flash('success','Investment cancelled and principal refunded.');
        }
    }
    header('Location: /admin/investments.php'); exit;
}

$sf = $_GET['status'] ?? 'active';
$invs = $pdo->prepare("SELECT i.*, CONCAT(u.first_name,' ',u.last_name) AS user_name FROM investments i JOIN users u ON i.user_id=u.id WHERE i.status=? ORDER BY i.created_at DESC");
$invs->execute([$sf]); $invList=$invs->fetchAll();

// Stats
$totalInvested = (float)$pdo->query("SELECT COALESCE(SUM(principal_amount),0) FROM investments WHERE status='active'")->fetchColumn();
$totalMatured  = (float)$pdo->query("SELECT COALESCE(SUM(actual_returns),0) FROM investments WHERE status='matured'")->fetchColumn();

$pageTitle = 'Investments';
?>
<?php include '../includes/header.php'; ?>
<div class="page-title"><i class="fa fa-chart-line me-2 text-danger"></i>Investment Management</div>

<div class="row g-3 mb-4">
  <div class="col-md-3"><div class="stat-card green"><div class="label">Active Investments</div><div class="value"><?= count($invList) ?></div><div class="icon" style="position:absolute;right:1rem;top:1rem;"><i class="fa fa-chart-line"></i></div></div></div>
  <div class="col-md-3"><div class="stat-card dark"><div class="label">Total Invested</div><div class="value"><?= money($totalInvested) ?></div></div></div>
  <div class="col-md-3"><div class="stat-card gold"><div class="label">Total Returns Paid</div><div class="value"><?= money($totalMatured) ?></div></div></div>
</div>

<ul class="nav nav-tabs mb-4">
  <?php foreach (['active','matured','cancelled'] as $s): ?>
  <li class="nav-item"><a class="nav-link <?= $sf===$s?'active':'' ?>" href="?status=<?= $s ?>"><?= ucfirst($s) ?></a></li>
  <?php endforeach; ?>
</ul>
<div class="card">
  <div class="table-responsive">
    <table class="table table-hover mb-0 small">
      <thead><tr><th>User</th><th>Plan</th><th>Principal</th><th>Rate</th><th>Term</th><th>Start</th><th>Matures</th><th>Actions</th></tr></thead>
      <tbody>
      <?php if (empty($invList)): ?><tr><td colspan="8" class="text-center py-4 text-muted">No <?= $sf ?> investments.</td></tr>
      <?php else: foreach ($invList as $i): ?>
      <tr>
        <td><?= sanitize($i['user_name']) ?></td>
        <td><strong><?= sanitize($i['plan_name']) ?></strong></td>
        <td class="fw-bold"><?= money((float)$i['principal_amount']) ?></td>
        <td><?= $i['interest_rate'] ?>%</td>
        <td><?= $i['duration_months'] ?> mo</td>
        <td><?= $i['start_date'] ?></td>
        <td><?= $i['maturity_date'] ?></td>
        <td>
          <?php if ($i['status']==='active'): ?>
          <form method="POST" class="d-flex gap-1">
            <?= csrf_field() ?><input type="hidden" name="inv_id" value="<?= $i['id'] ?>">
            <button name="action" value="mature" class="btn btn-xs btn-success" data-confirm="Mark as matured and credit payout?">Mature</button>
            <button name="action" value="cancel" class="btn btn-xs btn-outline-danger" data-confirm="Cancel and refund principal?">Cancel</button>
          </form>
          <?php else: ?><span class="text-muted"><?= ucfirst($i['status']) ?></span><?php endif; ?>
        </td>
      </tr>
      <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>
</div>
<?php include '../includes/footer.php'; ?>
