<?php
/**
 * admin/cron-mlm.php
 * Cron Job do Módulo MLM
 * Roda diariamente
 *
 * Configure no servidor:
 *   0 3 * * * curl -s "https://seusite.com/admin/cron-mlm.php?secret=SEU_CRON_SECRET"
 */

require_once '../settings.php';

$secret = $_GET['secret'] ?? $_SERVER['HTTP_X_CRON_SECRET'] ?? '';
if ($secret !== $_settings->info('cron_secret') && php_sapi_name() !== 'cli') {
    http_response_code(403); die('Forbidden');
}

require_once '../includes/wallet-functions.php';
require_once '../classes/MLM.php';

$log = [];
$mlm = new MLM();

// ─────────────────────────────────────────────────────────
// 1. PROCESSAR BÔNUS BINÁRIO
// ─────────────────────────────────────────────────────────
$mode = $_settings->info('binary_flush_mode') ?: 'daily';
$should_run_binary = false;

if ($mode === 'daily') {
    $should_run_binary = true;
} elseif ($mode === 'weekly') {
    // Roda às segundas-feiras
    $should_run_binary = (date('N') == 1);
} elseif ($mode === 'monthly') {
    // Roda no 1º dia do mês
    $should_run_binary = (date('j') == 1);
}

if ($should_run_binary) {
    $bonus_log = $mlm->process_binary_bonuses();
    $log[] = "✅ Bônus binário processado: " . count($bonus_log) . " pagamentos.";
    foreach ($bonus_log as $b) {
        $log[] = "  → #{$b['customer_id']} {$b['name']}: R$" . number_format($b['bonus'],2,',','.')
                 . " (base R$" . number_format($b['weak_vol'],2,',','.') . ", sobra R$" . number_format($b['carry'],2,',','.') . ")";
    }
} else {
    $log[] = "⏭ Bônus binário — modo $mode — não é dia de processar.";
}

// ─────────────────────────────────────────────────────────
// 2. PROCESSAR RENDIMENTOS DE INVESTIMENTO
//    (Se este cron também for responsável pelos yields)
// ─────────────────────────────────────────────────────────
$investments = $conn->query(
    "SELECT i.*, p.name as plan_name, 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
     WHERE i.status = 1
     AND (i.last_yield_at IS NULL OR DATE(i.last_yield_at) < CURDATE())"
);

$yields_processed = 0;
while ($inv = $investments->fetch_assoc()) {
    $cid     = (int)   $inv['customer_id'];
    $inv_id  = (int)   $inv['id'];
    $rate    = (float) $inv['daily_rate'];
    $amount  = (float) $inv['amount_invested'];
    $earned  = (float) $inv['amount_earned'];
    $cap     = (float) $inv['cap_limit'];

    // Calcula rendimento do dia
    $yield = round($amount * ($rate / 100), 2);

    // Verifica se excede o teto
    if ($earned + $yield >= $cap) {
        $yield = round($cap - $earned, 2); // Paga só a diferença
        if ($yield < 0.01) {
            // Encerra
            $conn->query("UPDATE investments SET status=2, ended_at=NOW() WHERE id=$inv_id");
            continue;
        }
        // Encerra após pagar
        $conn->query("UPDATE investments SET
            amount_earned = $cap, status=2, ended_at=NOW(), last_yield_at=NOW()
            WHERE id=$inv_id");
        enqueue_whatsapp($cid, 'investment_completed', $amount);
        $log[] = "🎉 Investimento #$inv_id (cliente #$cid) atingiu o teto!";
    } else {
        $new_earned = $earned + $yield;
        $conn->query("UPDATE investments SET
            amount_earned = $new_earned, last_yield_at=NOW()
            WHERE id=$inv_id");
    }

    // Registra o yield
    $day_num = $conn->query(
        "SELECT COUNT(*)+1 as dn FROM investment_yields WHERE investment_id=$inv_id"
    )->fetch_assoc()['dn'];

    $conn->query("INSERT INTO investment_yields SET
        investment_id=$inv_id, customer_id=$cid, amount=$yield, day_number=$day_num");

    // Credita na carteira
    wallet_credit($cid, $yield, 'yield',
                  "Rendimento diário — " . $inv['plan_name'],
                  $inv_id, 'investment');

    // Notificação
    enqueue_whatsapp($cid, 'yield_received', $yield);

    // ── Comissões Unilevel (paga sobre o yield gerado) ──
    $mlm_logs = $mlm->process_unilevel_commissions($cid, $yield, $inv_id);
    if (count($mlm_logs)) {
        $log[] = "  🔗 Unilevel para investimento #$inv_id: " . count($mlm_logs) . " níveis pagos.";
    }

    // ── Atualiza volumes binários ───────────────────────
    $mlm->update_binary_volumes($cid, $yield);

    $yields_processed++;
    $log[] = "📈 Yield #$inv_id (#{$cid}): +R$" . number_format($yield,2,',','.');
}
$log[] = "✅ $yields_processed rendimentos processados.";

// ─────────────────────────────────────────────────────────
// 3. PROCESSAR FILA DE NOTIFICAÇÕES WHATSAPP
// ─────────────────────────────────────────────────────────
$wpp_url = $_settings->info('wpp_api_url');
$notif_sent = 0;

if ($wpp_url) {
    $pending = $conn->query(
        "SELECT * FROM notification_queue WHERE status=0 AND scheduled_for <= NOW()
         ORDER BY created_at ASC LIMIT 30"
    );
    while ($n = $pending->fetch_assoc()) {
        $sent   = drope_send_whatsapp($n['phone'], $n['message']);
        $status = $sent ? 1 : 2;
        $conn->query("UPDATE notification_queue SET status=$status, sent_at=NOW() WHERE id={$n['id']}");
        if ($sent) $notif_sent++;
    }
    $log[] = "📲 $notif_sent notificações WhatsApp enviadas.";
}

// Limpeza
$conn->query("DELETE FROM notification_queue WHERE status IN (1,2) AND created_at < DATE_SUB(NOW(), INTERVAL 30 DAY)");

// ─────────────────────────────────────────────────────────
// RESPOSTA FINAL
// ─────────────────────────────────────────────────────────
header('Content-Type: application/json');
echo json_encode([
    'timestamp'         => date('Y-m-d H:i:s'),
    'yields_processed'  => $yields_processed,
    'binary_ran'        => $should_run_binary,
    'notif_sent'        => $notif_sent,
    'log'               => $log,
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
