<?php
// admin/investments/index.php — Painel Admin de Investimentos
require_once '../../settings.php';
if (!$_settings->userdata('type') || $_settings->userdata('type') != 1) {
    header('Location: /admin'); exit();
}

// Stats globais
$stats = $conn->query("SELECT
    COUNT(CASE WHEN status=1 THEN 1 END)               as ativos,
    COUNT(CASE WHEN status=2 THEN 1 END)               as concluidos,
    COALESCE(SUM(amount_invested),0)                   as total_invested,
    COALESCE(SUM(amount_earned),0)                     as total_earned,
    COUNT(DISTINCT customer_id)                        as investors
    FROM investments")->fetch_assoc();

$yield_today = $conn->query(
    "SELECT COALESCE(SUM(amount),0) as t FROM investment_yields WHERE DATE(created_at)=CURDATE()"
)->fetch_assoc()['t'];

// Planos
$plans = $conn->query(
    "SELECT p.*,
            COUNT(i.id) as total_investors,
            COALESCE(SUM(i.amount_invested),0) as total_invested,
            COUNT(CASE WHEN i.status=1 THEN 1 END) as active_investors
     FROM investment_plans p
     LEFT JOIN investments i ON p.id=i.plan_id
     GROUP BY p.id
     ORDER BY p.sort_order ASC, p.min_amount ASC"
);

// Investimentos recentes
$recent = $conn->query(
    "SELECT i.*, p.name as plan_name, p.icon, p.color,
             c.firstname, c.lastname, c.phone
     FROM investments i
     JOIN investment_plans p ON i.plan_id=p.id
     JOIN customer_list c ON i.customer_id=c.id
     ORDER BY i.created_at DESC LIMIT 20"
);

if (($_POST['action'] ?? '') === 'run_yields_now') {
    require_once '../../classes/Investment.php';
    $inv_c = new Investment();
    $log   = $inv_c->process_daily_yields();
    $msg   = "✅ " . count($log) . " rendimentos processados!";
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Investimentos — Admin</title>
<link rel="stylesheet" href="/admin/assets/css/bootstrap/bootstrap.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
<style>
body { background:#f4f6fb; font-family:'Inter',sans-serif; }
.admin-card { border-radius:14px; border:none; box-shadow:0 2px 12px rgba(0,0,0,.06); }
.stat-card  { border-radius:12px; border:none; color:#fff; padding:1.2rem; }
.plan-pill  { border-radius:12px; padding:.75rem 1rem; border:2px solid #e8e5f5; background:#fff; }
.plan-icon  { font-size:1.5rem; }
.badge-s1   { background:rgba(0,200,100,.12); color:#00b894; }
.badge-s2   { background:rgba(108,92,231,.12); color:#6c5ce7; }
.badge-s3   { background:rgba(220,50,50,.12);  color:#d63031; }
</style>
</head>
<body>
<div class="container-fluid py-4 px-4">

  <div class="d-flex align-items-center justify-content-between mb-4">
    <div>
      <h4 class="fw-bold mb-0">📈 Gestão de Investimentos</h4>
      <small class="text-muted">Planos, rendimentos e investidores</small>
    </div>
    <div class="d-flex gap-2">
      <form method="POST" class="m-0">
        <button name="action" value="run_yields_now"
                class="btn btn-outline-success btn-sm rounded-3 fw-bold"
                onclick="return confirm('Processar rendimentos AGORA?')">
          ⚡ Processar Yields
        </button>
      </form>
      <a href="create.php" class="btn btn-primary btn-sm rounded-3 fw-bold">+ Novo Plano</a>
    </div>
  </div>

  <?php if (!empty($msg)): ?>
    <div class="alert alert-success rounded-3 mb-3"><?= $msg ?></div>
  <?php endif; ?>

  <!-- Stats -->
  <div class="row g-3 mb-4">
    <div class="col-6 col-md-2">
      <div class="stat-card" style="background:linear-gradient(135deg,#6c5ce7,#a29bfe)">
        <div class="small opacity-80">📈 Ativos</div>
        <div class="fs-3 fw-bold"><?= number_format($stats['ativos']) ?></div>
      </div>
    </div>
    <div class="col-6 col-md-2">
      <div class="stat-card" style="background:linear-gradient(135deg,#00b09b,#96c93d)">
        <div class="small opacity-80">✅ Concluídos</div>
        <div class="fs-3 fw-bold"><?= number_format($stats['concluidos']) ?></div>
      </div>
    </div>
    <div class="col-6 col-md-2">
      <div class="stat-card" style="background:linear-gradient(135deg,#fdcb6e,#e17055)">
        <div class="small opacity-80">👥 Investidores</div>
        <div class="fs-3 fw-bold"><?= number_format($stats['investors']) ?></div>
      </div>
    </div>
    <div class="col-6 col-md-2">
      <div class="stat-card" style="background:linear-gradient(135deg,#fd79a8,#e17055)">
        <div class="small opacity-80">💰 Total Captado</div>
        <div class="fs-4 fw-bold">R$ <?= number_format($stats['total_invested'],2,',','.') ?></div>
      </div>
    </div>
    <div class="col-6 col-md-2">
      <div class="stat-card" style="background:linear-gradient(135deg,#2d3436,#636e72)">
        <div class="small opacity-80">💎 Total Pago</div>
        <div class="fs-4 fw-bold">R$ <?= number_format($stats['total_earned'],2,',','.') ?></div>
      </div>
    </div>
    <div class="col-6 col-md-2">
      <div class="stat-card" style="background:linear-gradient(135deg,#0f3460,#16213e)">
        <div class="small opacity-80">📅 Yield Hoje</div>
        <div class="fs-4 fw-bold">R$ <?= number_format($yield_today,2,',','.') ?></div>
      </div>
    </div>
  </div>

  <div class="row g-4">

    <!-- Planos -->
    <div class="col-md-5">
      <div class="admin-card p-4">
        <div class="d-flex justify-content-between align-items-center mb-3">
          <h6 class="fw-bold mb-0">💎 Planos Disponíveis</h6>
          <a href="create.php" class="btn btn-sm btn-primary rounded-3">+ Novo</a>
        </div>
        <?php if ($plans->num_rows === 0): ?>
          <p class="text-muted text-center small py-3">Nenhum plano criado ainda.</p>
        <?php else: ?>
          <div class="d-flex flex-column gap-2">
          <?php while ($pl = $plans->fetch_assoc()): ?>
            <div class="plan-pill d-flex align-items-center gap-3">
              <div class="plan-icon"><?= $pl['icon'] ?></div>
              <div style="flex:1">
                <div class="fw-semibold"><?= htmlspecialchars($pl['name']) ?></div>
                <div class="text-muted" style="font-size:.72rem">
                  R$ <?= number_format($pl['min_amount'],2,',','.') ?>
                  · <?= $pl['daily_rate'] ?>%/dia
                  · Teto <?= $pl['cap_percent'] ?>%
                  · <span class="fw-semibold text-primary"><?= $pl['active_investors'] ?> ativos</span>
                  / <?= $pl['total_investors'] ?> total
                </div>
              </div>
              <div class="d-flex gap-1">
                <a href="create.php?id=<?= $pl['id'] ?>" class="btn btn-xs btn-outline-primary"
                   style="padding:3px 8px;border-radius:8px;font-size:.72rem">✏️</a>
                <?php if ($pl['is_active']): ?>
                  <span class="badge rounded-pill" style="background:#f0fff8;color:#00b894;font-size:.65rem">Ativo</span>
                <?php else: ?>
                  <span class="badge rounded-pill" style="background:#fff5f0;color:#e17055;font-size:.65rem">Inativo</span>
                <?php endif; ?>
              </div>
            </div>
          <?php endwhile; ?>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Investimentos Recentes -->
    <div class="col-md-7">
      <div class="admin-card">
        <div class="card-body p-4">
          <h6 class="fw-bold mb-3">📋 Investimentos Recentes</h6>
          <div class="table-responsive">
            <table class="table align-middle table-sm mb-0">
              <thead class="table-light">
                <tr>
                  <th>Investidor</th>
                  <th>Plano</th>
                  <th>Investido</th>
                  <th>Ganho</th>
                  <th>%</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                <?php while ($r = $recent->fetch_assoc()):
                  $pct = $r['cap_limit'] > 0
                         ? min(100, round(($r['amount_earned'] / $r['cap_limit']) * 100))
                         : 0;
                  $slabel = ['1'=>'Ativo','2'=>'Concluído','3'=>'Cancelado'][$r['status']] ?? '—';
                  $scls   = ['1'=>'badge-s1','2'=>'badge-s2','3'=>'badge-s3'][$r['status']] ?? '';
                ?>
                <tr>
                  <td>
                    <div class="fw-semibold small"><?= htmlspecialchars($r['firstname'].' '.$r['lastname'][0].'.') ?></div>
                    <div class="text-muted" style="font-size:.7rem"><?= $r['phone'] ?></div>
                  </td>
                  <td class="small"><?= $r['icon'] ?> <?= htmlspecialchars($r['plan_name']) ?></td>
                  <td class="small fw-semibold">R$ <?= number_format($r['amount_invested'],2,',','.') ?></td>
                  <td class="small text-success fw-semibold">R$ <?= number_format($r['amount_earned'],2,',','.') ?></td>
                  <td>
                    <div class="d-flex align-items-center gap-1">
                      <div style="height:6px;width:60px;background:#f0eeff;border-radius:50px;overflow:hidden">
                        <div style="height:100%;width:<?= $pct ?>%;background:#6c5ce7;border-radius:50px"></div>
                      </div>
                      <small><?= $pct ?>%</small>
                    </div>
                  </td>
                  <td><span class="badge rounded-pill px-2 py-1 <?= $scls ?>"><?= $slabel ?></span></td>
                </tr>
                <?php endwhile; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

  </div><!-- /row -->
</div>
<script src="/admin/assets/js/bootstrap.bundle.min.js"></script>
</body>
</html>
