<?php
/**
 * MOVEX – Daily ROI Cron  (Updated)
 * Path: /backend/cron/daily-roi.php
 *
 * ════════════════════════════════════════════════
 *  LOSS LOGIC  (Updated - Automatic Per-User)
 * ════════════════════════════════════════════════
 *  - Admin sets day_type = 'loss'
 *  - loss_pct in DB:
 *      0  → each user loses THEIR OWN daily profit rate
 *           (4% earner → 4% loss, 5% earner → 5% loss, 7% → 7% loss)
 *      >0  → everyone loses that fixed % (override mode)
 *
 *  - Loss decreases user's `trading_fund` (principal deduction)
 *  - Blocked users (stop_all=1, stop_roi=1, status=blocked) are SKIPPED
 *  - Transaction recorded in `income_transactions` with type='loss'
 * ════════════════════════════════════════════════
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: text/plain');

require_once '../config/db.php';

$isManual = isset($_GET['manual']);
$log      = [];
$now      = date('Y-m-d H:i:s');
$today    = date('Y-m-d');

$log[] = "=== MOVEX Daily ROI ===";
$log[] = "Run: $now | Mode: " . ($isManual ? 'Manual' : 'Cron');

// ── Step 1: Get today's trade config ──
if (isWeekend()) {
    $log[] = "⏭  Weekend — skipping.";
    echo implode("\n", $log);
    exit;
}

$configRow = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT * FROM trade_config WHERE config_date='$today' LIMIT 1"
));

if (!$configRow) {
    // Auto-create default profit
    $base = floatval(getSetting($conn, 'base_profit_pct', 0.04));
    mysqli_query($conn, "
        INSERT IGNORE INTO trade_config (config_date, day_type, profit_pct, loss_pct, note, set_by_admin)
        VALUES ('$today','profit',$base,0,'Auto-created by cron',0)
    ");
    $configRow = ['day_type'=>'profit','profit_pct'=>$base,'loss_pct'=>0];
    $log[] = "ℹ  No config for today — auto-profit ($base)";
}

$dayType     = $configRow['day_type'];
$fixedLossPct = floatval($configRow['loss_pct']); // 0 = per-user rate, >0 = fixed

$log[] = "📅 Day Type: " . strtoupper($dayType);

if ($dayType === 'closed') {
    $log[] = "🔒 Market closed — no ROI distributed.";
    echo implode("\n", $log);
    exit;
}

// ── Step 2: Get settings ──
$base      = floatval(getSetting($conn, 'base_profit_pct',  0.04));
$highInv   = floatval(getSetting($conn, 'high_inv_pct',     0.05));
$tier1Rate = floatval(getSetting($conn, 'tier1_profit_pct', 0.05));
$tier2Rate = floatval(getSetting($conn, 'tier2_profit_pct', 0.06));
$tier3Rate = floatval(getSetting($conn, 'tier3_profit_pct', 0.07));

// Level ROI rates (%)
$levelRates = [
    1 => 0.05,  // 5%
    2 => 0.03,  // 3%
    3 => 0.02,  // 2%
    4 => 0.01,  // 1%
    5 => 0.005, // 0.5%
    6 => 0.005,
    7 => 0.005,
    8 => 0.005,
    9 => 0.005,
   10 => 0.005,
];

// ── Step 3: Fetch all active users ──
$usersQ = mysqli_query($conn, "
    SELECT * FROM users
    WHERE status = 'active'
      AND activation_amount > 0
    ORDER BY id ASC
");

if (!$usersQ || mysqli_num_rows($usersQ) === 0) {
    $log[] = "⚠  No active users found.";
    echo implode("\n", $log);
    exit;
}

$users       = [];
$userByWallet= [];
while ($u = mysqli_fetch_assoc($usersQ)) {
    $users[]                 = $u;
    $userByWallet[$u['wallet']] = $u;
}
$log[] = "👥 Active Users: " . count($users);

$totalROI   = 0;
$totalLoss  = 0;
$processed  = 0;
$skipped    = 0;

// ── Step 4: Loop users ──
foreach ($users as $user) {
    $wallet = $user['wallet'];
    $inv    = floatval($user['activation_amount']);
    $name   = $user['name'] ?? 'User';

    // ── Skip blocked / stop_all / stop_roi ──
    if ($user['stop_all'] == 1 || $user['stop_roi'] == 1) {
        $log[] = "  ⛔ SKIP $name (income stopped)";
        $skipped++;
        continue;
    }

    // ── Get user's effective rate ──
    $tierLevel = intval($user['tier_level'] ?? 0);
    if ($tierLevel >= 3)     $userRate = $tier3Rate;
    elseif ($tierLevel == 2) $userRate = $tier2Rate;
    elseif ($tierLevel == 1) $userRate = $tier1Rate;
    elseif ($inv >= 500)     $userRate = $highInv;
    else                     $userRate = $base;

    // ════════════════════════════════════════
    //  LOSS DAY — deduct from trading fund
    // ════════════════════════════════════════
    if ($dayType === 'loss') {
        // If admin set fixed loss %, use that; else use user's own profit rate
        $lossRate = ($fixedLossPct > 0) ? $fixedLossPct : $userRate;
        $lossAmt  = round($inv * $lossRate, 4);

        if ($lossAmt <= 0) { $skipped++; continue; }

        // Deduct from trading fund (activation_amount)
        $wEsc = mysqli_real_escape_string($conn, $wallet);
        mysqli_query($conn, "
            UPDATE users
            SET activation_amount = GREATEST(0, activation_amount - $lossAmt)
            WHERE wallet = '$wEsc'
        ");

        // Log loss transaction
        mysqli_query($conn, "
            INSERT INTO income_transactions
                (wallet, amount, type, description, created_at)
            VALUES
                ('$wEsc', $lossAmt, 'loss',
                 'Loss day: " . round($lossRate*100, 2) . "% of $" . number_format($inv,2) . " fund',
                 '$now')
        ");

        $log[] = "  📉 LOSS $name | Rate: " . round($lossRate*100,2) . "% | -\$$lossAmt";
        $totalLoss += $lossAmt;
        $processed++;
        continue;
    }

    // ════════════════════════════════════════
    //  PROFIT DAY — add to wallet balance
    // ════════════════════════════════════════
    $profitAmt = round($inv * $userRate, 4);
    if ($profitAmt <= 0) { $skipped++; continue; }

    $wEsc = mysqli_real_escape_string($conn, $wallet);

    // Add to user's balance
    mysqli_query($conn, "
        UPDATE users
        SET balance = balance + $profitAmt
        WHERE wallet = '$wEsc'
    ");

    // Log profit transaction
    mysqli_query($conn, "
        INSERT INTO income_transactions
            (wallet, amount, type, description, created_at)
        VALUES
            ('$wEsc', $profitAmt, 'roi',
             'ROI: " . round($userRate*100, 2) . "% of $" . number_format($inv,2) . " investment',
             '$now')
    ");

    $log[] = "  ✅ ROI $name | Rate: " . round($userRate*100,2) . "% | +\$$profitAmt";
    $totalROI += $profitAmt;
    $processed++;

    // ── Level ROI Distribution ──
    if ($user['stop_level'] == 1) continue;

    $sponsorWallet = $user['referral_wallet'] ?? null;
    $level         = 1;

    while ($sponsorWallet && $level <= 10) {
        $sponsor = $userByWallet[$sponsorWallet] ?? null;
        if (!$sponsor) break;

        // Check if this level is open for sponsor
        $sponsorLevels = $sponsor['levels'] ? json_decode($sponsor['levels'], true) : null;
        $levelOpen     = ($sponsorLevels === null) ? ($level <= 3) : ($sponsorLevels[$level] ?? false);

        if ($levelOpen && $sponsor['stop_all'] != 1 && $sponsor['stop_level'] != 1 && $sponsor['status'] === 'active') {
            $levelRate   = $levelRates[$level] ?? 0;
            $levelIncome = round($profitAmt * $levelRate, 4);

            if ($levelIncome > 0) {
                $sWallet = mysqli_real_escape_string($conn, $sponsor['wallet']);
                mysqli_query($conn, "
                    UPDATE users SET balance = balance + $levelIncome WHERE wallet='$sWallet'
                ");
                mysqli_query($conn, "
                    INSERT INTO income_transactions (wallet, amount, type, description, created_at)
                    VALUES ('$sWallet', $levelIncome, 'level_roi',
                        'Level $level ROI from {$user['account_id']}', '$now')
                ");
            }
        }

        $sponsorWallet = $sponsor['referral_wallet'] ?? null;
        $level++;
    }
}

// ── Summary ──
$log[] = "";
$log[] = "═══════════════════════════";
$log[] = "✅ Processed : $processed";
$log[] = "⏭  Skipped   : $skipped";
if ($dayType === 'profit') $log[] = "💰 Total ROI : \$" . number_format($totalROI, 4);
if ($dayType === 'loss')   $log[] = "📉 Total Loss: \$" . number_format($totalLoss, 4);
$log[] = "═══════════════════════════";
$log[] = "Done at " . date('H:i:s');

echo implode("\n", $log);

// ── Helpers ──
function getSetting($conn, $key, $default = null) {
    $k   = mysqli_real_escape_string($conn, $key);
    $row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT setting_value FROM trade_settings WHERE setting_key='$k' LIMIT 1"));
    return $row ? $row['setting_value'] : $default;
}

function isWeekend() {
    return in_array((int)date('N'), [6, 7]);
}