<?php
/**
 * LEOXCC - ROI CRON JOB (UPDATED)
 * 
 * Run this script daily at 12:00 AM (Mon-Fri only)
 * Crontab: 0 0 * * 1-5 php /path/to/roi-cron.php
 * 
 * 🔥 NEW ROI STRUCTURE:
 * - Tier 1: $20-$49 Investment = 0.25% Daily ROI
 * - Tier 2: $50+ Investment = 0.5% Daily ROI
 * - Base Duration: 400 Working Days
 * - With 3X Booster: 600 Working Days
 * - Max ROI: 200% of investment
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

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

// Check if today is a weekday (Mon=1 to Fri=5)
$dayOfWeek = date('N');
if ($dayOfWeek > 5) {
    echo "Weekend - No ROI distribution today.\n";
    exit;
}

$today = date('Y-m-d');
$processedCount = 0;
$skippedCount = 0;
$totalRoiDistributed = 0;

echo "=== LEOXCC ROI CRON JOB ===\n";
echo "Date: $today\n";
echo "Starting ROI distribution...\n\n";

// Get all users with active investments
$usersQuery = mysqli_query($conn, "
    SELECT DISTINCT u.wallet, u.account_id, u.has_3x_booster, u.created_at as user_created
    FROM users u
    JOIN deposits d ON u.wallet = d.wallet
    WHERE d.status = 'success'
");

while ($user = mysqli_fetch_assoc($usersQuery)) {
    $wallet = $user['wallet'];
    $accId = $user['account_id'];
    $hasBooster = intval($user['has_3x_booster'] ?? 0);
    
    // Check if ROI already given today
    $checkToday = mysqli_fetch_assoc(mysqli_query($conn, "
        SELECT id FROM roi_logs WHERE wallet = '$wallet' AND date = '$today'
    "));
    
    if ($checkToday) {
        echo "SKIP: $wallet - Already received ROI today\n";
        $skippedCount++;
        continue;
    }
    
    // Get total investment
    $invQuery = mysqli_fetch_assoc(mysqli_query($conn, "
        SELECT SUM(amount) as total FROM deposits WHERE wallet = '$wallet' AND status = 'success'
    "));
    $totalInvestment = floatval($invQuery['total'] ?? 0);
    
    // Skip if investment below minimum ($20)
    if ($totalInvestment < 20) {
        echo "SKIP: $wallet - Investment below minimum ($totalInvestment)\n";
        $skippedCount++;
        continue;
    }
    
    // 🔥 DETERMINE ROI RATE BASED ON TIER
    $roiRate = 0;
    $tierName = "";
    if ($totalInvestment >= 50) {
        $roiRate = 0.50;
        $tierName = "Premium";
    } else if ($totalInvestment >= 20) {
        $roiRate = 0.25;
        $tierName = "Starter";
    }
    
    // Calculate max ROI (200%)
    $maxRoi = $totalInvestment * 2;
    
    // Get total ROI already received
    $roiReceivedQuery = mysqli_fetch_assoc(mysqli_query($conn, "
        SELECT SUM(roi_amount) as total, COUNT(*) as days FROM roi_logs WHERE wallet = '$wallet'
    "));
    $totalRoiReceived = floatval($roiReceivedQuery['total'] ?? 0);
    $roiDaysUsed = intval($roiReceivedQuery['days'] ?? 0);
    
    // 🔥 DETERMINE MAX DAYS (400 or 600 with booster)
    $maxDays = $hasBooster ? 600 : 400;
    
    // Check if ROI complete (200% cap or max days reached)
    if ($totalRoiReceived >= $maxRoi) {
        echo "SKIP: $wallet - ROI cap (200%) reached\n";
        $skippedCount++;
        continue;
    }
    
    if ($roiDaysUsed >= $maxDays) {
        echo "SKIP: $wallet - Max days ($maxDays) completed\n";
        $skippedCount++;
        continue;
    }
    
    // Calculate today's ROI
    $todayRoi = ($totalInvestment * $roiRate) / 100;
    
    // Make sure we don't exceed 200% cap
    if (($totalRoiReceived + $todayRoi) > $maxRoi) {
        $todayRoi = $maxRoi - $totalRoiReceived;
    }
    
    // Get active directs count
    $directsQuery = mysqli_fetch_assoc(mysqli_query($conn, "
        SELECT COUNT(DISTINCT u.wallet) as cnt 
        FROM users u 
        JOIN deposits d ON u.wallet = d.wallet 
        WHERE u.referral_id = '$accId' AND d.status = 'success'
    "));
    $activeDirects = intval($directsQuery['cnt'] ?? 0);
    
    $dayNumber = $roiDaysUsed + 1;
    
    // Insert ROI log
    $insertQuery = mysqli_query($conn, "
        INSERT INTO roi_logs (wallet, date, day_number, invested_amount, roi_rate, roi_amount, active_directs, is_booster, created_at)
        VALUES ('$wallet', '$today', $dayNumber, $totalInvestment, $roiRate, $todayRoi, $activeDirects, $hasBooster, NOW())
    ");
    
    if ($insertQuery) {
        $processedCount++;
        $totalRoiDistributed += $todayRoi;
        echo "SUCCESS: $wallet | Tier: $tierName | Rate: $roiRate% | ROI: $$todayRoi | Day: $dayNumber/$maxDays | Booster: " . ($hasBooster ? "Yes" : "No") . "\n";
    } else {
        echo "ERROR: $wallet - Failed to insert ROI log\n";
    }
}

echo "\n=== SUMMARY ===\n";
echo "Processed: $processedCount users\n";
echo "Skipped: $skippedCount users\n";
echo "Total ROI Distributed: $" . number_format($totalRoiDistributed, 4) . "\n";
echo "=== CRON JOB COMPLETE ===\n";
?>