<?php
// admin/network/index.php — Visão Geral da Rede MLM
require_once '../../settings.php';
if (!$_settings->userdata('type') || $_settings->userdata('type') != 1) {
    header('Location: /admin'); exit();
}

// Estatísticas globais
$stats = $conn->query("SELECT
    (SELECT COUNT(*) FROM binary_tree WHERE parent_id IS NOT NULL) as total_membros,
    (SELECT COALESCE(SUM(amount),0) FROM binary_bonuses) as total_binary_paid,
    (SELECT COALESCE(SUM(commission_amount),0) FROM unilevel_commissions) as total_unilevel_paid,
    (SELECT COUNT(*) FROM binary_bonuses) as bonus_count,
    (SELECT COUNT(*) FROM unilevel_commissions) as commission_count
")->fetch_assoc();

// Top earners
$top_binary = $conn->query(
    "SELECT bt.customer_id, bt.total_binary_earned, bt.left_volume, bt.right_volume,
            c.firstname, c.lastname, c.phone
     FROM binary_tree bt
     JOIN customer_list c ON bt.customer_id = c.id
     WHERE bt.total_binary_earned > 0
     ORDER BY bt.total_binary_earned DESC LIMIT 10"
);

$top_unilevel = $conn->query(
    "SELECT beneficiary_id, SUM(commission_amount) as total,
            c.firstname, c.lastname, c.phone
     FROM unilevel_commissions uc
     JOIN customer_list c ON uc.beneficiary_id = c.id
     GROUP BY beneficiary_id
     ORDER BY total DESC LIMIT 10"
);

// Config taxas unilevel
$rates = $conn->query("SELECT * FROM unilevel_rates ORDER BY level");

// Processar atualização de taxas
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_rates'])) {
    foreach ($_POST['rate'] as $level => $rate) {
        $l = (int)$level;
        $r = (float)str_replace(',','.',$rate);
        $conn->query("UPDATE unilevel_rates SET rate=$r WHERE level=$l");
    }
    $msg = "✅ Taxas unilevel atualizadas!";
    header("Location: ?msg=" . urlencode($msg)); exit();
}

// Processar bônus manual
if (($_POST['action'] ?? '') === 'run_binary_now') {
    $secret = $_settings->info('cron_secret');
    $result = file_get_contents(BASE_URL . "admin/cron-mlm.php?secret=$secret&binary_only=1");
    $msg = "✅ Bônus binário processado manualmente!";
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Rede MLM — 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; }
.rate-input { width:70px; text-align:center; border-radius:8px; border:1px solid #e8e5f5;
              padding:4px 6px; font-weight:700; }
</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">🌐 Rede MLM</h4>
      <small class="text-muted">Binário + Unilevel — Gestão e Configuração</small>
    </div>
    <div class="d-flex gap-2">
      <a href="/admin" class="btn btn-outline-secondary btn-sm rounded-3">← Admin</a>
      <form method="POST" class="m-0">
        <button name="action" value="run_binary_now"
                class="btn btn-primary btn-sm rounded-3 fw-bold"
                onclick="return confirm('Processar bônus binário AGORA?')">
          ⚡ Processar Bônus Agora
        </button>
      </form>
    </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-md-3 col-6">
      <div class="stat-card" style="background:linear-gradient(135deg,#6c5ce7,#a29bfe)">
        <div class="small opacity-85">👥 Membros na Rede</div>
        <div class="fs-3 fw-bold"><?= number_format($stats['total_membros']) ?></div>
      </div>
    </div>
    <div class="col-md-3 col-6">
      <div class="stat-card" style="background:linear-gradient(135deg,#00b09b,#96c93d)">
        <div class="small opacity-85">🌐 Bônus Binário Pago</div>
        <div class="fs-3 fw-bold">R$ <?= number_format($stats['total_binary_paid'],2,',','.') ?></div>
      </div>
    </div>
    <div class="col-md-3 col-6">
      <div class="stat-card" style="background:linear-gradient(135deg,#fd79a8,#e17055)">
        <div class="small opacity-85">🔗 Comissões Unilevel</div>
        <div class="fs-3 fw-bold">R$ <?= number_format($stats['total_unilevel_paid'],2,',','.') ?></div>
      </div>
    </div>
    <div class="col-md-3 col-6">
      <div class="stat-card" style="background:linear-gradient(135deg,#2d3436,#636e72)">
        <div class="small opacity-85">📊 Transações MLM</div>
        <div class="fs-3 fw-bold">
          <?= number_format($stats['bonus_count'] + $stats['commission_count']) ?>
        </div>
      </div>
    </div>
  </div>

  <div class="row g-4">

    <!-- Top Binary Earners -->
    <div class="col-md-6">
      <div class="admin-card p-4">
        <h6 class="fw-bold mb-3">🏆 Top Bônus Binário</h6>
        <?php if ($top_binary->num_rows === 0): ?>
          <p class="text-muted text-center small py-3">Nenhum bônus pago ainda.</p>
        <?php else: ?>
        <div class="table-responsive">
          <table class="table align-middle table-sm">
            <thead class="table-light">
              <tr><th>#</th><th>Usuário</th><th>Esq.</th><th>Dir.</th><th>Total Ganho</th></tr>
            </thead>
            <tbody>
              <?php $i=1; while ($t = $top_binary->fetch_assoc()): ?>
              <tr>
                <td class="text-muted small"><?= $i++ ?></td>
                <td>
                  <div class="fw-semibold small"><?= htmlspecialchars($t['firstname'].' '.$t['lastname'][0].'.') ?></div>
                  <div class="text-muted" style="font-size:.7rem"><?= $t['phone'] ?></div>
                </td>
                <td class="small">R$ <?= number_format($t['left_volume'],2,',','.') ?></td>
                <td class="small">R$ <?= number_format($t['right_volume'],2,',','.') ?></td>
                <td class="fw-bold text-success">R$ <?= number_format($t['total_binary_earned'],2,',','.') ?></td>
              </tr>
              <?php endwhile; ?>
            </tbody>
          </table>
        </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Top Unilevel Earners -->
    <div class="col-md-6">
      <div class="admin-card p-4">
        <h6 class="fw-bold mb-3">🏆 Top Comissão Unilevel</h6>
        <?php if ($top_unilevel->num_rows === 0): ?>
          <p class="text-muted text-center small py-3">Nenhuma comissão paga ainda.</p>
        <?php else: ?>
        <div class="table-responsive">
          <table class="table align-middle table-sm">
            <thead class="table-light">
              <tr><th>#</th><th>Usuário</th><th>Total Comissão</th></tr>
            </thead>
            <tbody>
              <?php $i=1; while ($t = $top_unilevel->fetch_assoc()): ?>
              <tr>
                <td class="text-muted small"><?= $i++ ?></td>
                <td>
                  <div class="fw-semibold small"><?= htmlspecialchars($t['firstname'].' '.$t['lastname'][0].'.') ?></div>
                  <div class="text-muted" style="font-size:.7rem"><?= $t['phone'] ?></div>
                </td>
                <td class="fw-bold text-success">R$ <?= number_format($t['total'],2,',','.') ?></td>
              </tr>
              <?php endwhile; ?>
            </tbody>
          </table>
        </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Configuração das taxas Unilevel -->
    <div class="col-12">
      <div class="admin-card p-4">
        <h6 class="fw-bold mb-1">⚙️ Taxas Unilevel por Nível</h6>
        <small class="text-muted d-block mb-3">Configure a % de comissão paga em cada nível de profundidade</small>

        <form method="POST">
          <div class="row g-3">
            <?php $rates->data_seek(0); while ($r = $rates->fetch_assoc()): ?>
            <div class="col-6 col-md-2">
              <label class="form-label fw-semibold small">Nível <?= $r['level'] ?></label>
              <div class="input-group input-group-sm">
                <input type="number" name="rate[<?= $r['level'] ?>]"
                       class="form-control rate-input text-center fw-bold"
                       value="<?= $r['rate'] ?>" step="0.5" min="0" max="50">
                <span class="input-group-text">%</span>
              </div>
            </div>
            <?php endwhile; ?>
          </div>

          <div class="mt-3">
            <button type="submit" name="update_rates" value="1"
                    class="btn btn-primary rounded-3 px-4 fw-bold">
              💾 Salvar Taxas
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- Config Binário -->
    <div class="col-md-6">
      <div class="admin-card p-4">
        <h6 class="fw-bold mb-3">🌐 Configuração Bônus Binário</h6>
        <?php
        $binary_rate = $_settings->info('binary_bonus_rate') ?: '10';
        $binary_mode = $_settings->info('binary_flush_mode') ?: 'weekly';
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_binary_config'])) {
            $nr = (float)$_POST['binary_rate'];
            $nm = $conn->real_escape_string($_POST['binary_mode']);
            $conn->query("UPDATE system_info SET meta_value='$nr' WHERE meta_field='binary_bonus_rate'");
            $conn->query("UPDATE system_info SET meta_value='$nm' WHERE meta_field='binary_flush_mode'");
            echo '<div class="alert alert-success rounded-3 mb-2">✅ Salvo!</div>';
        }
        ?>
        <form method="POST">
          <div class="mb-3">
            <label class="form-label fw-semibold small">Taxa do Bônus Binário (%)</label>
            <div class="input-group">
              <input type="number" name="binary_rate" class="form-control"
                     value="<?= $binary_rate ?>" step="0.5" min="1" max="50">
              <span class="input-group-text">%</span>
            </div>
            <small class="text-muted">Percentual pago sobre o lado mais fraco</small>
          </div>
          <div class="mb-3">
            <label class="form-label fw-semibold small">Frequência de Pagamento</label>
            <select name="binary_mode" class="form-select">
              <option value="daily"   <?= $binary_mode==='daily'   ?'selected':'' ?>>Diário</option>
              <option value="weekly"  <?= $binary_mode==='weekly'  ?'selected':'' ?>>Semanal (toda segunda)</option>
              <option value="monthly" <?= $binary_mode==='monthly' ?'selected':'' ?>>Mensal (dia 1)</option>
            </select>
          </div>
          <button type="submit" name="update_binary_config" value="1"
                  class="btn btn-primary rounded-3 px-4 fw-bold">
            💾 Salvar
          </button>
        </form>
      </div>
    </div>

    <!-- Cron info -->
    <div class="col-md-6">
      <div class="admin-card p-4" style="background:linear-gradient(135deg,#1a1a2e,#2d3436);color:#fff">
        <h6 class="fw-bold mb-3">⚙️ Configuração do Cron Job</h6>
        <p class="small opacity-75 mb-2">Adicione no cPanel → Cron Jobs:</p>
        <div class="mb-2">
          <div class="small opacity-60 mb-1">MLM + Rendimentos (todo dia às 3h):</div>
          <code style="font-size:.7rem;background:rgba(255,255,255,.1);padding:6px 10px;border-radius:8px;display:block">
            0 3 * * * curl -s "<?= BASE_URL ?>admin/cron-mlm.php?secret=<?= $_settings->info('cron_secret') ?>"
          </code>
        </div>
        <div>
          <div class="small opacity-60 mb-1">Leilões (todo minuto):</div>
          <code style="font-size:.7rem;background:rgba(255,255,255,.1);padding:6px 10px;border-radius:8px;display:block">
            * * * * * curl -s "<?= BASE_URL ?>admin/cron-auctions.php?secret=<?= $_settings->info('cron_secret') ?>"
          </code>
        </div>
        <div class="mt-3 small opacity-60">
          🔑 Defina a chave em: Admin → Configurações → <strong>cron_secret</strong>
        </div>
      </div>
    </div>

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