<?php
// pages/investimentos.php — Página de Planos de Investimento

if ($_settings->userdata('id') == '') {
    echo '<script>location.replace(\'/entrar?redirect=/investir\');</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();
$wallet    = wallet_get($customer_id);

// Planos disponíveis
$plans = $conn->query(
    "SELECT * FROM investment_plans WHERE is_active=1 ORDER BY sort_order ASC, min_amount ASC"
);

// Investimento ativo
$active_inv = $conn->query(
    "SELECT i.*, p.name as plan_name, p.color, p.icon, p.min_amount as plan_min
     FROM investments i JOIN investment_plans p ON i.plan_id=p.id
     WHERE i.customer_id=$customer_id AND i.status=1
     ORDER BY i.id DESC LIMIT 1"
)->fetch_assoc();

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

// Processar ativação via POST
$flash_msg   = '';
$flash_type  = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['plan_id'])) {
    $pid    = (int)$_POST['plan_id'];
    $custom = !empty($_POST['custom_amount'])
              ? (float)str_replace(['.', ','], ['', '.'], $_POST['custom_amount'])
              : null;
    $result = $inv_class->activate_plan($customer_id, $pid, $custom);
    $flash_msg  = $result['msg'];
    $flash_type = $result['status'] === 'success' ? 'success' : 'danger';
    if ($result['status'] === 'success') {
        // Recarrega carteira e investimento
        $wallet    = wallet_get($customer_id);
        $active_inv = $conn->query(
            "SELECT i.*, p.name as plan_name, p.color, p.icon, p.min_amount as plan_min
             FROM investments i JOIN investment_plans p ON i.plan_id=p.id
             WHERE i.customer_id=$customer_id AND i.status=1
             ORDER BY i.id DESC LIMIT 1"
        )->fetch_assoc();
    }
}

// Quantidade de planos
$plans->data_seek(0);
$plans_arr = [];
while ($p = $plans->fetch_assoc()) $plans_arr[] = $p;
?>

<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800;900&display=swap');
.inv-wrap { font-family:'Inter',sans-serif; }

/* ── Hero ─────────────────────────────────────────────── */
.inv-hero {
  background: linear-gradient(135deg,#0f3460 0%,#16213e 50%,#1a1a2e 100%);
  border-radius:20px; color:#fff; padding:2rem; position:relative; overflow:hidden;
}
.inv-hero::before {
  content:''; position:absolute; top:-60px; right:-60px;
  width:250px; height:250px; border-radius:50%;
  background:radial-gradient(circle,rgba(108,92,231,.25) 0%,transparent 70%);
}
.inv-hero::after {
  content:''; position:absolute; bottom:-40px; left:20%;
  width:180px; height:180px; border-radius:50%;
  background:radial-gradient(circle,rgba(0,176,155,.2) 0%,transparent 70%);
}

/* ── Plano card ───────────────────────────────────────── */
.plan-card {
  border-radius:20px; border:2px solid #e8e5f5; background:#fff;
  transition:all .3s ease; cursor:pointer; overflow:hidden;
  box-shadow:0 4px 20px rgba(0,0,0,.06);
}
.plan-card:hover {
  transform:translateY(-6px);
  box-shadow:0 16px 40px rgba(0,0,0,.12);
}
.plan-card.featured { border-color:transparent; }
.plan-card.active-plan {
  border:2px solid transparent;
  background: linear-gradient(#fff,#fff) padding-box,
              linear-gradient(135deg,#6c5ce7,#00b09b) border-box;
}

/* ── Header do plano ──────────────────────────────────── */
.plan-header {
  padding:1.5rem 1.5rem 1rem;
  border-radius:18px 18px 0 0;
}
.plan-icon { font-size:2.5rem; margin-bottom:.5rem; display:block; }
.plan-name { font-weight:900; font-size:1.25rem; }

/* ── Rate big ─────────────────────────────────────────── */
.rate-big {
  font-size:3rem; font-weight:900; line-height:1;
  background:linear-gradient(135deg,#6c5ce7,#00b09b);
  -webkit-background-clip:text; -webkit-text-fill-color:transparent;
}
.rate-label { font-size:.8rem; color:#636e72; font-weight:600; }

/* ── Barra de progresso ───────────────────────────────── */
.cap-bar { height:10px; border-radius:50px; background:#f0eeff; overflow:hidden; }
.cap-fill { height:100%; border-radius:50px; transition:width .8s ease; }

/* ── Botão activate ───────────────────────────────────── */
.btn-activate {
  width:100%; border-radius:14px; padding:.9rem; font-weight:800;
  font-size:1rem; border:none; transition:all .25s;
}
.btn-activate:hover:not(:disabled) {
  transform:translateY(-2px);
  box-shadow:0 8px 20px rgba(0,0,0,.15);
}

/* ── Banner popular ───────────────────────────────────── */
.popular-banner {
  background:linear-gradient(90deg,#6c5ce7,#a29bfe);
  color:#fff; text-align:center; font-size:.7rem;
  font-weight:800; letter-spacing:1.5px; padding:5px;
}

/* ── Investimento ativo ───────────────────────────────── */
.active-inv-card {
  border-radius:20px; overflow:hidden;
  box-shadow:0 8px 32px rgba(0,0,0,.1);
}
.active-inv-header { padding:1.5rem; color:#fff; }
.yield-bar { height:14px; border-radius:50px; background:rgba(255,255,255,.2); overflow:hidden; }
.yield-fill { height:100%; border-radius:50px; background:#fff; transition:width .8s ease; }

/* ── Modal ────────────────────────────────────────────── */
.plan-modal .modal-content { border-radius:20px; border:none; }
.plan-modal .modal-header  { border:none; }

/* ── Como funciona ────────────────────────────────────── */
.how-card { border-radius:16px; border:none; background:#f8f7ff;
            border:2px solid #e8e5f5; }
.step-num { width:36px; height:36px; border-radius:50%; font-weight:800;
            display:flex; align-items:center; justify-content:center;
            background:linear-gradient(135deg,#6c5ce7,#a29bfe); color:#fff; flex-shrink:0; }
</style>

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

  <!-- ── Título ─────────────────────────────────────── -->
  <div class="app-title mb-3">
    <h1>📈 Investimentos</h1>
    <div class="app-title-desc" style="color:#424b58">Rendimento diário automático</div>
  </div>

  <?php if ($flash_msg): ?>
    <div class="alert alert-<?= $flash_type ?> rounded-4 mb-3">
      <?= $flash_type === 'success' ? '✅' : '⚠️' ?> <?= htmlspecialchars($flash_msg) ?>
    </div>
  <?php endif; ?>

  <!-- ── Hero / Saldo ──────────────────────────────── -->
  <div class="inv-hero mb-4">
    <div class="row align-items-center">
      <div class="col">
        <div class="small opacity-70 mb-1">💼 Saldo Disponível</div>
        <div class="fw-black" style="font-size:2.2rem">
          R$ <?= number_format((float)$wallet['balance_available'], 2, ',', '.') ?>
        </div>
        <div class="small opacity-70 mt-1">
          📈 Total ganho em rendimentos:
          <strong>R$ <?= number_format($total_yields, 2, ',', '.') ?></strong>
        </div>
      </div>
      <div class="col-auto">
        <a href="/depositar" class="btn btn-warning rounded-pill fw-bold">
          + Depositar
        </a>
      </div>
    </div>
  </div>

  <!-- ── Investimento Ativo ─────────────────────────── -->
  <?php if ($active_inv): ?>
  <?php
    $pct_earned = $active_inv['cap_limit'] > 0
                  ? min(100, round(($active_inv['amount_earned'] / $active_inv['cap_limit']) * 100, 1))
                  : 0;
    $days_total   = $active_inv['cap_limit'] > 0 && $active_inv['daily_rate'] > 0
                    ? ceil(($active_inv['cap_percent'] / 100) / ($active_inv['daily_rate'] / 100))
                    : '—';
    $plan_color   = $active_inv['color'] ?: '#6c5ce7';
  ?>
  <div class="active-inv-card mb-4">
    <div class="active-inv-header" style="background:linear-gradient(135deg,<?= $plan_color ?>,<?= $plan_color ?>cc)">
      <div class="d-flex align-items-start justify-content-between mb-3">
        <div>
          <div class="opacity-80 small mb-1">📈 Plano Ativo</div>
          <div class="fw-black fs-4">
            <?= $active_inv['icon'] ?> <?= htmlspecialchars($active_inv['plan_name']) ?>
          </div>
        </div>
        <div class="text-end">
          <div class="opacity-80 small">Taxa Diária</div>
          <div class="fw-black fs-3"><?= $active_inv['daily_rate'] ?>%</div>
        </div>
      </div>

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

    <div class="p-3 bg-white">
      <div class="row g-2 text-center">
        <div class="col-4">
          <div class="small text-muted">Rendimento/dia</div>
          <div class="fw-bold text-success">
            ≈ R$ <?= number_format($active_inv['amount_invested'] * ($active_inv['daily_rate']/100), 2, ',', '.') ?>
          </div>
        </div>
        <div class="col-4">
          <div class="small text-muted">Previsão teto</div>
          <div class="fw-bold">~<?= $days_total ?> dias</div>
        </div>
        <div class="col-4">
          <div class="small text-muted">Iniciado em</div>
          <div class="fw-bold small"><?= date('d/m/Y', strtotime($active_inv['created_at'])) ?></div>
        </div>
      </div>

      <div class="d-flex gap-2 mt-3">
        <a href="/meus-investimentos" class="btn btn-outline-primary btn-sm rounded-3 flex-fill">
          📊 Ver Histórico
        </a>
        <?php
          // Mostra upgrade se próximo plano disponível
          $next_plan = $conn->query(
              "SELECT * FROM investment_plans WHERE min_amount > {$active_inv['amount_invested']}
               AND is_active=1 ORDER BY min_amount ASC LIMIT 1"
          )->fetch_assoc();
          if ($next_plan):
            $diff = round($next_plan['min_amount'] - $active_inv['amount_invested'], 2);
        ?>
        <button class="btn btn-warning btn-sm rounded-3 flex-fill fw-bold"
                data-bs-toggle="modal" data-bs-target="#upgradeModal"
                data-inv="<?= $active_inv['id'] ?>"
                data-plan="<?= $next_plan['id'] ?>"
                data-name="<?= $next_plan['name'] ?>"
                data-diff="<?= number_format($diff,2,',','.') ?>"
                data-rate="<?= $next_plan['daily_rate'] ?>"
                onclick="fillUpgradeModal(this)">
          🚀 Upgrade (só R$ <?= number_format($diff,2,',','.') ?>)
        </button>
        <?php endif; ?>
      </div>
    </div>
  </div>
  <?php endif; ?>

  <!-- ── Planos ─────────────────────────────────────── -->
  <h5 class="fw-bold mb-3">
    <?= $active_inv ? '🔄 Todos os Planos' : '💎 Escolha seu Plano' ?>
  </h5>

  <div class="row g-3 mb-4">
    <?php foreach ($plans_arr as $p):
      $color      = $p['color'] ?: '#6c5ce7';
      $is_active  = ($active_inv && $active_inv['plan_id'] == $p['id'] && $active_inv['status'] == 1);
      $cap_example = round($p['min_amount'] * ($p['cap_percent'] / 100), 2);
      $days_est    = $p['daily_rate'] > 0 ? ceil(($p['cap_percent'] / 100) / ($p['daily_rate'] / 100)) : 0;
    ?>
    <div class="col-12 col-md-6">
      <div class="plan-card <?= $p['featured'] ? 'featured':'' ?> <?= $is_active ? 'active-plan':'' ?>">

        <?php if ($p['featured']): ?>
          <div class="popular-banner">⭐ MAIS POPULAR</div>
        <?php endif; ?>

        <?php if ($is_active): ?>
          <div style="background:linear-gradient(90deg,#00b09b,#96c93d);color:#fff;
                      text-align:center;font-size:.7rem;font-weight:800;letter-spacing:1px;padding:5px">
            ✅ SEU PLANO ATUAL
          </div>
        <?php endif; ?>

        <!-- Header colorido -->
        <div class="plan-header text-white"
             style="background:linear-gradient(135deg,<?= $color ?>,<?= $color ?>bb)">
          <span class="plan-icon"><?= $p['icon'] ?></span>
          <div class="plan-name"><?= htmlspecialchars($p['name']) ?></div>
          <?php if ($p['description']): ?>
            <div class="small opacity-80 mt-1"><?= htmlspecialchars($p['description']) ?></div>
          <?php endif; ?>
        </div>

        <div class="p-4">
          <!-- Taxa destaque -->
          <div class="text-center mb-3">
            <div class="rate-big"><?= $p['daily_rate'] ?>%</div>
            <div class="rate-label">ao dia</div>
          </div>

          <!-- Detalhes -->
          <div class="d-flex flex-column gap-2 mb-4 small">
            <div class="d-flex justify-content-between">
              <span class="text-muted">💰 Investimento mín.</span>
              <strong>R$ <?= number_format($p['min_amount'],2,',','.') ?></strong>
            </div>
            <?php if ($p['max_amount'] > 0): ?>
            <div class="d-flex justify-content-between">
              <span class="text-muted">📊 Investimento máx.</span>
              <strong>R$ <?= number_format($p['max_amount'],2,',','.') ?></strong>
            </div>
            <?php endif; ?>
            <div class="d-flex justify-content-between">
              <span class="text-muted">🏁 Teto de ganho</span>
              <strong><?= $p['cap_percent'] ?>% (<?= $days_est ?>≈ dias)</strong>
            </div>
            <div class="d-flex justify-content-between text-success">
              <span>📈 Ganho máximo (exemplo)</span>
              <strong>R$ <?= number_format($cap_example,2,',','.') ?></strong>
            </div>
          </div>

          <!-- Barra de lucro visual -->
          <div class="small text-muted mb-1">
            Crescimento até o teto
          </div>
          <div class="cap-bar mb-4">
            <div class="cap-fill"
                 style="width:0%;background:linear-gradient(90deg,<?= $color ?>,<?= $color ?>90)"
                 data-target="100"></div>
          </div>

          <!-- Botão -->
          <?php if ($is_active): ?>
            <button class="btn-activate btn-outline-success" disabled>
              ✅ Plano Ativo
            </button>
          <?php else: ?>
            <button class="btn-activate text-white fw-bold"
                    style="background:linear-gradient(135deg,<?= $color ?>,<?= $color ?>bb)"
                    data-bs-toggle="modal" data-bs-target="#activateModal"
                    data-plan-id="<?= $p['id'] ?>"
                    data-plan-name="<?= htmlspecialchars($p['name']) ?>"
                    data-min="<?= $p['min_amount'] ?>"
                    data-max="<?= $p['max_amount'] ?>"
                    data-rate="<?= $p['daily_rate'] ?>"
                    data-cap="<?= $p['cap_percent'] ?>"
                    data-icon="<?= $p['icon'] ?>"
                    data-color="<?= $color ?>"
                    onclick="fillModal(this)">
              <?= $p['icon'] ?> Ativar Plano
            </button>
          <?php endif; ?>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>

  <!-- ── Como Funciona ─────────────────────────────── -->
  <div class="how-card p-4">
    <h6 class="fw-bold mb-3">🎯 Como funciona o investimento?</h6>
    <div class="d-flex flex-column gap-3">
      <?php
      $steps = [
        ['1', 'Escolha um plano', 'Selecione o plano que melhor se encaixa no seu objetivo e deposite o valor.'],
        ['2', 'Rendimento diário automático', 'O sistema credita o rendimento automaticamente todo dia na sua carteira.'],
        ['3', 'Teto e renovação', 'Ao atingir o teto (ex: 200%), o plano encerra. Renove ou faça upgrade!'],
        ['4', 'Ganhos em cascata', 'Seus indicados também geram rendimento para você via rede unilevel.'],
      ];
      foreach ($steps as [$num, $title, $desc]):
      ?>
      <div class="d-flex gap-3 align-items-start">
        <div class="step-num"><?= $num ?></div>
        <div>
          <div class="fw-semibold"><?= $title ?></div>
          <div class="small text-muted"><?= $desc ?></div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>

</div><!-- /container -->

<!-- ── Modal: Ativar Plano ── -->
<div class="modal fade plan-modal" id="activateModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title fw-bold" id="modal-title">Ativar Plano</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST">
        <input type="hidden" name="plan_id" id="modal-plan-id">
        <div class="modal-body">
          <!-- Resumo do plano -->
          <div class="p-3 rounded-4 mb-3 text-white text-center" id="modal-header-bg">
            <div style="font-size:2.5rem" id="modal-icon">💎</div>
            <div class="fw-bold fs-5" id="modal-plan-name">Plano</div>
            <div class="opacity-80 small" id="modal-plan-details"></div>
          </div>

          <!-- Saldo disponível -->
          <div class="d-flex justify-content-between align-items-center mb-3 p-3 rounded-3"
               style="background:#f8f7ff">
            <span class="small fw-semibold">💼 Saldo Disponível</span>
            <span class="fw-bold">R$ <?= number_format((float)$wallet['balance_available'],2,',','.') ?></span>
          </div>

          <!-- Valor -->
          <div class="mb-3">
            <label class="form-label fw-semibold">Valor a Investir</label>
            <div class="input-group">
              <span class="input-group-text">R$</span>
              <input type="text" id="modal-amount" name="custom_amount"
                     class="form-control text-center fw-bold"
                     style="font-size:1.3rem;border-radius:0 10px 10px 0 !important;"
                     placeholder="0,00" required>
            </div>
            <small class="text-muted" id="modal-range-hint"></small>
          </div>

          <!-- Preview de ganho -->
          <div class="rounded-4 p-3" style="background:#f0fff8;border:1px solid #b2eadf">
            <div class="d-flex justify-content-between small mb-1">
              <span>📈 Rendimento diário</span>
              <strong id="preview-daily">R$ 0,00</strong>
            </div>
            <div class="d-flex justify-content-between small">
              <span>🏁 Total ao atingir teto</span>
              <strong id="preview-cap">R$ 0,00</strong>
            </div>
          </div>
        </div>
        <div class="modal-footer border-0">
          <button type="button" class="btn btn-outline-secondary rounded-3" data-bs-dismiss="modal">Cancelar</button>
          <button type="submit" class="btn text-white rounded-3 fw-bold px-4" id="modal-submit-btn"
                  style="background:linear-gradient(135deg,#6c5ce7,#a29bfe);border:none">
            💎 Confirmar Investimento
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- ── Modal: Upgrade ── -->
<div class="modal fade plan-modal" id="upgradeModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header border-0">
        <h5 class="modal-title fw-bold">🚀 Upgrade de Plano</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form method="POST" action="/classes/Investment.php?f=upgrade">
        <input type="hidden" name="investment_id" id="upg-inv-id">
        <input type="hidden" name="new_plan_id"   id="upg-plan-id">
        <div class="modal-body">
          <div class="alert alert-warning rounded-4 small mb-3">
            <div id="upg-info"></div>
          </div>
          <div class="d-flex justify-content-between p-3 rounded-3 mb-2"
               style="background:#f8f7ff">
            <span class="small fw-semibold">💼 Saldo Disponível</span>
            <span class="fw-bold">R$ <?= number_format((float)$wallet['balance_available'],2,',','.') ?></span>
          </div>
        </div>
        <div class="modal-footer border-0">
          <button type="button" class="btn btn-outline-secondary rounded-3" data-bs-dismiss="modal">Cancelar</button>
          <button type="submit" class="btn btn-warning rounded-3 fw-bold px-4">🚀 Confirmar Upgrade</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
// Anima barras dos planos quando visível
const bars = document.querySelectorAll('.cap-fill');
setTimeout(() => {
  bars.forEach(b => b.style.width = '100%');
}, 400);

// ── Preenche modal de ativação ──────────────────────────
let currentRate = 0, currentCap = 0;

function fillModal(btn) {
  const pid   = btn.dataset.planId;
  const name  = btn.dataset.planName;
  const min   = parseFloat(btn.dataset.min);
  const max   = parseFloat(btn.dataset.max);
  const rate  = parseFloat(btn.dataset.rate);
  const cap   = parseFloat(btn.dataset.cap);
  const icon  = btn.dataset.icon;
  const color = btn.dataset.color;

  currentRate = rate;
  currentCap  = cap;

  document.getElementById('modal-plan-id').value  = pid;
  document.getElementById('modal-title').textContent = icon + ' ' + name;
  document.getElementById('modal-icon').textContent   = icon;
  document.getElementById('modal-plan-name').textContent = name;
  document.getElementById('modal-plan-details').textContent =
    rate + '% ao dia · Teto ' + cap + '%';
  document.getElementById('modal-header-bg').style.background =
    'linear-gradient(135deg,' + color + ',' + color + 'bb)';
  document.getElementById('modal-submit-btn').style.background =
    'linear-gradient(135deg,' + color + ',' + color + 'bb)';

  let hint = 'Mínimo: R$ ' + min.toFixed(2).replace('.',',');
  if (max > 0) hint += ' · Máximo: R$ ' + max.toFixed(2).replace('.',',');
  document.getElementById('modal-range-hint').textContent = hint;

  // Pré-preenche com o mínimo
  const amtEl = document.getElementById('modal-amount');
  amtEl.value = min.toFixed(2).replace('.',',');
  amtEl.min   = min;
  if (max > 0) amtEl.max = max;
  updatePreview();
}

function updatePreview() {
  const raw    = document.getElementById('modal-amount').value.replace(',','.');
  const amount = parseFloat(raw) || 0;
  const daily  = amount * (currentRate / 100);
  const capAmt = amount * (currentCap / 100);

  document.getElementById('preview-daily').textContent =
    'R$ ' + daily.toFixed(2).replace('.',',');
  document.getElementById('preview-cap').textContent =
    'R$ ' + capAmt.toFixed(2).replace('.',',');
}

document.getElementById('modal-amount').addEventListener('input', function() {
  let v = this.value.replace(/\D/g,'');
  if (!v) { this.value=''; updatePreview(); return; }
  v = (parseInt(v)/100).toFixed(2);
  this.value = v.replace('.',',');
  updatePreview();
});

// ── Preenche modal de upgrade ───────────────────────────
function fillUpgradeModal(btn) {
  document.getElementById('upg-inv-id').value  = btn.dataset.inv;
  document.getElementById('upg-plan-id').value = btn.dataset.plan;
  document.getElementById('upg-info').innerHTML =
    'Você está fazendo upgrade para <strong>' + btn.dataset.name + '</strong>.<br>' +
    'Paga apenas a diferença de <strong>R$ ' + btn.dataset.diff + '</strong>.<br>' +
    'Nova taxa diária: <strong>' + btn.dataset.rate + '% ao dia</strong>.';
}
</script>
