<?php
// pages/meus-investimentos.php — Histórico e Extrato de Investimentos

if ($_settings->userdata('id') == '') {
    echo '<script>location.replace(\'/\');</script>'; exit();
}
$customer_id = (int) $_settings->userdata('id');

require_once BASE_APP . 'includes/wallet-functions.php';
require_once BASE_APP . 'classes/Investment.php';

$inv_class = new Investment();

// Todos os investimentos
$investments = $inv_class->get_user_investments($customer_id);

// Rendimentos recentes
$yields = $inv_class->get_yield_history($customer_id, 30);

// Totais
$totals = $conn->query(
    "SELECT
        COUNT(*) as total,
        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
     FROM investments WHERE customer_id=$customer_id"
)->fetch_assoc();

$total_yield_credits = (float)($conn->query(
    "SELECT COALESCE(SUM(amount),0) as t FROM investment_yields WHERE customer_id=$customer_id"
)->fetch_assoc()['t'] ?? 0);

// Status labels
$status_map = [1 => 'Ativo', 2 => 'Concluído', 3 => 'Cancelado'];
$status_cls = [1 => 'text-success', 2 => 'text-primary', 3 => 'text-danger'];
?>

<style>
.meus-inv-wrap { font-family:'Inter',sans-serif; }
.inv-hist-card {
  border-radius:18px; border:none;
  box-shadow:0 4px 20px rgba(0,0,0,.07); margin-bottom:1rem;
}
.inv-hist-header { border-radius:16px 16px 0 0; padding:1.25rem 1.5rem; color:#fff; }
.yield-bar-sm { height:8px; border-radius:50px; background:rgba(255,255,255,.25); overflow:hidden; }
.yield-fill-sm { height:100%; border-radius:50px; background:#fff; }
.stat-box { border-radius:14px; padding:1rem; }
.yield-row { border-radius:10px; padding:.6rem .75rem; transition:.15s; }
.yield-row:hover { background:#f8f7ff; }
.yield-icon { font-size:1.2rem; }
.tabs-mini .nav-link { border-radius:50px !important; font-weight:600; font-size:.85rem; }
.tabs-mini .nav-link.active { background:#6c5ce7!important; color:#fff!important; border:none; }
.tabs-mini .nav-link:not(.active) { color:#6c5ce7; border:1px solid #6c5ce7; }
</style>

<div class="container app-main meus-inv-wrap pb-5">

  <!-- Título -->
  <div class="app-title mb-3">
    <h1>📊 Meus Investimentos</h1>
    <a href="/investir" class="app-title-desc text-decoration-none" style="color:#6c5ce7">
      + Novo Investimento
    </a>
  </div>

  <!-- Stats -->
  <div class="row g-2 mb-4">
    <div class="col-6 col-md-3">
      <div class="stat-box" style="background:linear-gradient(135deg,#6c5ce7,#a29bfe);color:#fff">
        <div class="small opacity-80">📈 Ativos</div>
        <div class="fw-bold fs-4"><?= $totals['ativos'] ?></div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="stat-box" style="background:linear-gradient(135deg,#00b09b,#96c93d);color:#fff">
        <div class="small opacity-80">✅ Concluídos</div>
        <div class="fw-bold fs-4"><?= $totals['concluidos'] ?></div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="stat-box" style="background:linear-gradient(135deg,#fdcb6e,#e17055);color:#fff">
        <div class="small opacity-80">💰 Total Investido</div>
        <div class="fw-bold fs-5">R$ <?= number_format($totals['total_invested'],2,',','.') ?></div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="stat-box" style="background:linear-gradient(135deg,#fd79a8,#e17055);color:#fff">
        <div class="small opacity-80">💎 Total Ganho</div>
        <div class="fw-bold fs-5">R$ <?= number_format($totals['total_earned'],2,',','.') ?></div>
      </div>
    </div>
  </div>

  <!-- Abas -->
  <ul class="nav tabs-mini gap-2 mb-4">
    <li class="nav-item"><a class="nav-link active" href="#meus" data-bs-toggle="tab">📁 Investimentos</a></li>
    <li class="nav-item"><a class="nav-link" href="#rendimentos" data-bs-toggle="tab">📈 Rendimentos</a></li>
  </ul>

  <div class="tab-content">

    <!-- Investimentos -->
    <div class="tab-pane fade show active" id="meus">
      <?php if ($investments->num_rows === 0): ?>
        <div class="text-center text-muted py-5">
          <div style="font-size:3rem">💎</div>
          <h5>Nenhum investimento ainda</h5>
          <a href="/investir" class="btn btn-primary rounded-pill mt-2 fw-bold">
            Começar a Investir
          </a>
        </div>
      <?php else: ?>
        <?php while ($inv = $investments->fetch_assoc()):
          $color    = $inv['color'] ?: '#6c5ce7';
          $pct      = $inv['cap_limit'] > 0
                      ? min(100, round(($inv['amount_earned'] / $inv['cap_limit']) * 100, 1))
                      : 0;
          $daily_earn = round($inv['amount_invested'] * ($inv['daily_rate']/100), 2);
          $st_label  = $status_map[$inv['status']] ?? '—';
          $st_cls    = $status_cls[$inv['status']] ?? '';
          $yield_q   = $conn->query(
              "SELECT COUNT(*) as cnt, MAX(created_at) as last
               FROM investment_yields WHERE investment_id={$inv['id']}"
          )->fetch_assoc();
        ?>
        <div class="inv-hist-card">
          <div class="inv-hist-header"
               style="background:linear-gradient(135deg,<?= $color ?>,<?= $color ?>aa)">
            <div class="d-flex justify-content-between align-items-start mb-2">
              <div>
                <div class="fw-black fs-5">
                  <?= $inv['icon'] ?> <?= htmlspecialchars($inv['plan_name']) ?>
                </div>
                <div class="opacity-80 small">Ativado em <?= date('d/m/Y', strtotime($inv['created_at'])) ?></div>
              </div>
              <div class="text-end">
                <div class="opacity-80 small">Taxa dia</div>
                <div class="fw-black fs-4"><?= $inv['daily_rate'] ?>%</div>
              </div>
            </div>

            <div class="d-flex justify-content-between small opacity-85 mb-1">
              <span>R$ <?= number_format($inv['amount_earned'],2,',','.') ?> ganhos</span>
              <span><?= $pct ?>%</span>
            </div>
            <div class="yield-bar-sm mb-2">
              <div class="yield-fill-sm" style="width:<?= $pct ?>%"></div>
            </div>
            <div class="d-flex justify-content-between small opacity-70">
              <span>💰 R$ <?= number_format($inv['amount_invested'],2,',','.') ?> investidos</span>
              <span>🏁 Teto: R$ <?= number_format($inv['cap_limit'],2,',','.') ?></span>
            </div>
          </div>

          <div class="p-3 bg-white" style="border-radius:0 0 18px 18px">
            <div class="row g-2 text-center mb-3">
              <div class="col-4">
                <div class="text-muted" style="font-size:.72rem">Rendimento/dia</div>
                <div class="fw-bold small text-success">≈R$ <?= number_format($daily_earn,2,',','.') ?></div>
              </div>
              <div class="col-4">
                <div class="text-muted" style="font-size:.72rem">Dias rendendo</div>
                <div class="fw-bold small"><?= $yield_q['cnt'] ?> dias</div>
              </div>
              <div class="col-4">
                <div class="text-muted" style="font-size:.72rem">Status</div>
                <div class="fw-bold small <?= $st_cls ?>"><?= $st_label ?></div>
              </div>
            </div>

            <?php if ($inv['status'] == 2): ?>
              <div class="alert alert-success rounded-3 small mb-2 py-2">
                🎉 Plano concluído em <?= $inv['ended_at'] ? date('d/m/Y', strtotime($inv['ended_at'])) : '—' ?>!
                Ganhou R$ <?= number_format($inv['amount_earned'],2,',','.') ?>.
                <a href="/investir" class="fw-bold">Renove agora →</a>
              </div>
            <?php endif; ?>

            <?php if ($inv['status'] == 1): ?>
              <!-- Próximo yield -->
              <div class="d-flex align-items-center gap-2 p-2 rounded-3"
                   style="background:#f8f7ff;font-size:.78rem">
                <span>⏰</span>
                <span>Próximo rendimento:
                  <strong>R$ <?= number_format($daily_earn,2,',','.') ?></strong>
                  amanhã às 3h</span>
              </div>
            <?php endif; ?>
          </div>
        </div>
        <?php endwhile; ?>
      <?php endif; ?>
    </div>

    <!-- Rendimentos -->
    <div class="tab-pane fade" id="rendimentos">
      <div class="card" style="border-radius:18px;border:none;box-shadow:0 4px 20px rgba(0,0,0,.07)">
        <div class="card-body p-4">
          <div class="d-flex justify-content-between align-items-center mb-3">
            <h6 class="fw-bold mb-0">📈 Últimos 30 Rendimentos</h6>
            <span class="fw-bold text-success">
              Total: R$ <?= number_format($total_yield_credits,2,',','.') ?>
            </span>
          </div>

          <?php if ($yields->num_rows === 0): ?>
            <p class="text-muted text-center small py-4">Nenhum rendimento ainda. Ative um plano!</p>
          <?php else: ?>
            <div class="d-flex flex-column gap-1">
              <?php while ($y = $yields->fetch_assoc()): ?>
              <div class="d-flex align-items-center gap-3 yield-row">
                <span class="yield-icon"><?= $y['icon'] ?></span>
                <div style="flex:1">
                  <div class="small fw-semibold"><?= htmlspecialchars($y['plan_name']) ?></div>
                  <div class="text-muted" style="font-size:.72rem">
                    Dia <?= $y['day_number'] ?>
                    · <?= date('d/m/Y H:i', strtotime($y['created_at'])) ?>
                  </div>
                </div>
                <div class="fw-bold text-success">+R$ <?= number_format($y['amount'],2,',','.') ?></div>
              </div>
              <?php endwhile; ?>
            </div>
          <?php endif; ?>
        </div>
      </div>
    </div>

  </div><!-- /tab-content -->

</div>
