<?php
// admin/investments/create.php — Criar/Editar Plano de Investimento
require_once '../../settings.php';
if (!$_settings->userdata('type') || $_settings->userdata('type') != 1) {
    header('Location: /admin'); exit();
}

$plan    = null;
$edit_id = (int)($_GET['id'] ?? 0);

if ($edit_id) {
    $plan = $conn->query("SELECT * FROM investment_plans WHERE id=$edit_id")->fetch_assoc();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_once '../../classes/Investment.php';
    $inv_c  = new Investment();
    $result = $inv_c->save_plan();
    if ($result['status'] === 'success') {
        header('Location: index.php?msg=Plano+salvo!'); exit();
    } else {
        $error = $result['msg'];
    }
}

// Ícones sugeridos
$icons = ['💎','💰','🏆','🚀','⭐','🔥','💵','📈','🌟','💫','🎯','🏅','✨','🥇','💡'];
$colors = ['#6c5ce7','#00b09b','#e17055','#fdcb6e','#fd79a8','#0f3460','#2d3436','#00cec9','#e84393','#6ab04c'];
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= $edit_id ? 'Editar' : 'Novo' ?> Plano — 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; }
.form-card { border-radius:16px; border:none; box-shadow:0 4px 20px rgba(0,0,0,.07); }
.section-h  { background:linear-gradient(90deg,#6c5ce7,#a29bfe); color:#fff;
              padding:.75rem 1.25rem; border-radius:10px; margin-bottom:1rem; }
.form-control,.form-select { border-radius:10px!important; border:1.5px solid #e8e5f5!important; }
.form-control:focus,.form-select:focus {
  border-color:#6c5ce7!important;
  box-shadow:0 0 0 4px rgba(108,92,231,.12)!important;
}
.icon-btn  { width:44px;height:44px;border-radius:12px;border:2px solid #e8e5f5;
             background:#fff;font-size:1.4rem;cursor:pointer;transition:.2s; }
.icon-btn:hover,.icon-btn.selected { border-color:#6c5ce7;background:#f0eeff; }
.color-dot { width:32px;height:32px;border-radius:50%;cursor:pointer;transition:.2s;
             border:3px solid transparent; }
.color-dot.selected { border-color:#2d3436;transform:scale(1.15); }

/* Preview do plano */
.plan-preview {
  border-radius:18px; overflow:hidden;
  box-shadow:0 4px 20px rgba(0,0,0,.1);
}
.plan-prev-header { padding:1.5rem; color:#fff; }
.rate-big-prev { font-size:2.6rem; font-weight:900;
  background:linear-gradient(135deg,#6c5ce7,#00b09b);
  -webkit-background-clip:text; -webkit-text-fill-color:transparent; }
</style>
</head>
<body>
<div class="container-fluid py-4 px-4" style="max-width:900px">

  <div class="d-flex justify-content-between align-items-center mb-4">
    <div>
      <h4 class="fw-bold mb-0">💎 <?= $edit_id ? 'Editar' : 'Criar' ?> Plano de Investimento</h4>
      <small class="text-muted">Configure taxas, teto e aparência do plano</small>
    </div>
    <a href="index.php" class="btn btn-outline-secondary btn-sm rounded-3">← Voltar</a>
  </div>

  <?php if (!empty($error)): ?>
    <div class="alert alert-danger rounded-4"><?= htmlspecialchars($error) ?></div>
  <?php endif; ?>

  <div class="row g-4">
    <div class="col-md-7">
      <form method="POST" id="plan-form">
        <?php if ($edit_id): ?>
          <input type="hidden" name="id" value="<?= $edit_id ?>">
        <?php endif; ?>

        <!-- Informações -->
        <div class="form-card card mb-4">
          <div class="card-body p-4">
            <div class="section-h">📝 Identificação do Plano</div>
            <div class="mb-3">
              <label class="form-label fw-semibold">Nome do Plano *</label>
              <input type="text" name="name" class="form-control"
                     placeholder="Ex: Bronze, Prata, Ouro, Diamante..."
                     value="<?= htmlspecialchars($plan['name'] ?? '') ?>" required
                     oninput="updatePreview()">
            </div>
            <div class="mb-3">
              <label class="form-label fw-semibold">Descrição</label>
              <input type="text" name="description" class="form-control"
                     placeholder="Breve descrição do plano"
                     value="<?= htmlspecialchars($plan['description'] ?? '') ?>"
                     oninput="updatePreview()">
            </div>

            <!-- Ícone -->
            <label class="form-label fw-semibold">Ícone</label>
            <div class="d-flex flex-wrap gap-2 mb-3">
              <?php foreach ($icons as $ic): ?>
                <button type="button" class="icon-btn <?= ($plan['icon'] ?? '💎') === $ic ? 'selected':'' ?>"
                        onclick="selectIcon(this, '<?= $ic ?>')"><?= $ic ?></button>
              <?php endforeach; ?>
            </div>
            <input type="hidden" name="icon" id="sel-icon" value="<?= $plan['icon'] ?? '💎' ?>">

            <!-- Cor -->
            <label class="form-label fw-semibold">Cor do Plano</label>
            <div class="d-flex flex-wrap gap-2 mb-1">
              <?php foreach ($colors as $c): ?>
                <div class="color-dot <?= ($plan['color'] ?? '#6c5ce7') === $c ? 'selected':'' ?>"
                     style="background:<?= $c ?>"
                     onclick="selectColor(this, '<?= $c ?>')"></div>
              <?php endforeach; ?>
            </div>
            <input type="hidden" name="color" id="sel-color" value="<?= $plan['color'] ?? '#6c5ce7' ?>">
          </div>
        </div>

        <!-- Financeiro -->
        <div class="form-card card mb-4">
          <div class="card-body p-4">
            <div class="section-h">💰 Configuração Financeira</div>

            <div class="row g-3 mb-3">
              <div class="col-6">
                <label class="form-label fw-semibold">Valor Mínimo (R$) *</label>
                <div class="input-group">
                  <span class="input-group-text">R$</span>
                  <input type="text" name="min_amount" class="form-control"
                         placeholder="50,00"
                         value="<?= $edit_id ? number_format($plan['min_amount'],2,',','.'):'' ?>"
                         required oninput="updatePreview()">
                </div>
              </div>
              <div class="col-6">
                <label class="form-label fw-semibold">Valor Máximo (R$)</label>
                <div class="input-group">
                  <span class="input-group-text">R$</span>
                  <input type="text" name="max_amount" class="form-control"
                         placeholder="0 = ilimitado"
                         value="<?= $edit_id && $plan['max_amount'] > 0 ? number_format($plan['max_amount'],2,',','.'):'' ?>">
                </div>
              </div>
            </div>

            <div class="row g-3 mb-3">
              <div class="col-6">
                <label class="form-label fw-semibold">Taxa Diária (%) *</label>
                <div class="input-group">
                  <input type="text" name="daily_rate" class="form-control text-center fw-bold"
                         placeholder="3"
                         value="<?= $plan['daily_rate'] ?? '' ?>"
                         required oninput="updatePreview()">
                  <span class="input-group-text">% / dia</span>
                </div>
              </div>
              <div class="col-6">
                <label class="form-label fw-semibold">Teto de Ganho (%) *</label>
                <div class="input-group">
                  <input type="text" name="cap_percent" class="form-control text-center fw-bold"
                         placeholder="200"
                         value="<?= $plan['cap_percent'] ?? '' ?>"
                         required oninput="updatePreview()">
                  <span class="input-group-text">%</span>
                </div>
                <small class="text-muted">Ex: 200% = dobra o capital</small>
              </div>
            </div>

            <div class="alert alert-info rounded-3 small" id="calc-info">
              Preencha os campos acima para ver o cálculo.
            </div>
          </div>
        </div>

        <!-- Opções -->
        <div class="form-card card mb-4">
          <div class="card-body p-4">
            <div class="section-h">⚙️ Opções</div>
            <div class="row g-3">
              <div class="col-6">
                <label class="form-label fw-semibold">Status</label>
                <select name="is_active" class="form-select">
                  <option value="1" <?= ($plan['is_active'] ?? 1) == 1 ? 'selected':'' ?>>✅ Ativo</option>
                  <option value="0" <?= ($plan['is_active'] ?? 1) == 0 ? 'selected':'' ?>>❌ Inativo</option>
                </select>
              </div>
              <div class="col-6">
                <label class="form-label fw-semibold">Ordem de exibição</label>
                <input type="number" name="sort_order" class="form-control"
                       value="<?= $plan['sort_order'] ?? 0 ?>" min="0">
              </div>
            </div>
            <div class="d-flex gap-3 mt-3">
              <div class="form-check">
                <input type="checkbox" name="featured" id="featured" class="form-check-input"
                       <?= !empty($plan['featured']) ? 'checked':'' ?>>
                <label class="form-check-label" for="featured">⭐ Plano em destaque</label>
              </div>
              <div class="form-check">
                <input type="checkbox" name="allow_multiple" id="allow_multiple" class="form-check-input"
                       <?= !empty($plan['allow_multiple']) ? 'checked':'' ?>>
                <label class="form-check-label" for="allow_multiple">Permitir múltiplas ativações</label>
              </div>
            </div>
          </div>
        </div>

        <div class="d-flex gap-2 justify-content-end">
          <a href="index.php" class="btn btn-outline-secondary rounded-4 px-4">Cancelar</a>
          <button type="submit" class="btn btn-primary rounded-4 px-5 fw-bold"
                  style="background:linear-gradient(90deg,#6c5ce7,#a29bfe);border:none">
            <?= $edit_id ? '💾 Salvar' : '🚀 Criar Plano' ?>
          </button>
        </div>
      </form>
    </div>

    <!-- Preview ao vivo -->
    <div class="col-md-5">
      <div class="form-card p-4" style="position:sticky;top:20px">
        <h6 class="fw-bold mb-3">👁 Preview ao Vivo</h6>
        <div class="plan-preview">
          <div class="plan-prev-header" id="prev-header"
               style="background:linear-gradient(135deg,<?= $plan['color'] ?? '#6c5ce7' ?>,<?= $plan['color'] ?? '#6c5ce7' ?>bb)">
            <span style="font-size:2.5rem" id="prev-icon"><?= $plan['icon'] ?? '💎' ?></span>
            <div class="fw-black fs-5 mt-1" id="prev-name">
              <?= htmlspecialchars($plan['name'] ?? 'Nome do Plano') ?>
            </div>
            <div class="opacity-80 small" id="prev-desc">
              <?= htmlspecialchars($plan['description'] ?? 'Descrição') ?>
            </div>
          </div>
          <div class="p-4 bg-white">
            <div class="text-center mb-3">
              <div class="rate-big-prev" id="prev-rate"><?= $plan['daily_rate'] ?? '0' ?>%</div>
              <div class="text-muted small fw-semibold">ao dia</div>
            </div>
            <div class="d-flex flex-column gap-2 small">
              <div class="d-flex justify-content-between">
                <span class="text-muted">💰 Mínimo</span>
                <strong id="prev-min">R$ <?= $edit_id ? number_format($plan['min_amount'],2,',','.') : '—' ?></strong>
              </div>
              <div class="d-flex justify-content-between">
                <span class="text-muted">🏁 Teto</span>
                <strong id="prev-cap"><?= $plan['cap_percent'] ?? '—' ?>%</strong>
              </div>
              <div class="d-flex justify-content-between text-success">
                <span>📈 Rendimento diário (ex.)</span>
                <strong id="prev-daily">R$ —</strong>
              </div>
              <div class="d-flex justify-content-between text-success">
                <span>💎 Ganho máximo (ex.)</span>
                <strong id="prev-total">R$ —</strong>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</div>

<script src="/admin/assets/js/bootstrap.bundle.min.js"></script>
<script>
function selectIcon(el, icon) {
  document.querySelectorAll('.icon-btn').forEach(b => b.classList.remove('selected'));
  el.classList.add('selected');
  document.getElementById('sel-icon').value = icon;
  document.getElementById('prev-icon').textContent = icon;
}

function selectColor(el, color) {
  document.querySelectorAll('.color-dot').forEach(d => d.classList.remove('selected'));
  el.classList.add('selected');
  document.getElementById('sel-color').value = color;
  document.getElementById('prev-header').style.background =
    'linear-gradient(135deg,' + color + ',' + color + 'bb)';
}

function updatePreview() {
  const name = document.querySelector('[name=name]').value || 'Nome do Plano';
  const desc = document.querySelector('[name=description]').value || 'Descrição';
  const rate = parseFloat(document.querySelector('[name=daily_rate]').value.replace(',','.')) || 0;
  const cap  = parseFloat(document.querySelector('[name=cap_percent]').value.replace(',','.')) || 0;
  const min  = parseFloat(document.querySelector('[name=min_amount]').value.replace(/\./g,'').replace(',','.')) || 0;

  document.getElementById('prev-name').textContent = name;
  document.getElementById('prev-desc').textContent = desc;
  document.getElementById('prev-rate').textContent = rate ? rate + '%' : '0%';
  document.getElementById('prev-cap').textContent  = cap  ? cap  + '%' : '—';
  document.getElementById('prev-min').textContent  = min  ? 'R$ ' + min.toFixed(2).replace('.',',') : '—';

  if (min > 0 && rate > 0) {
    const daily = (min * rate / 100).toFixed(2).replace('.',',');
    document.getElementById('prev-daily').textContent = 'R$ ' + daily;
  }
  if (min > 0 && cap > 0) {
    const total = (min * cap / 100).toFixed(2).replace('.',',');
    document.getElementById('prev-total').textContent = 'R$ ' + total;

    const days = cap > 0 && rate > 0 ? Math.ceil((cap/100) / (rate/100)) : 0;
    const info = document.getElementById('calc-info');
    info.innerHTML =
      `✅ Sobre R$ ${min.toFixed(2).replace('.',',')} investido:<br>` +
      `· Rendimento diário: <strong>R$ ${(min*rate/100).toFixed(2).replace('.',',')}</strong><br>` +
      `· Teto máximo: <strong>R$ ${(min*cap/100).toFixed(2).replace('.',',')}</strong><br>` +
      `· Duração estimada: <strong>~${days} dias</strong>`;
  }
}
updatePreview();
</script>
</body>
</html>
