<?php
/**
 * Smart Flow fX - Daily ROI + Level Income Distribution
 * 
 * Schedule: Every day at 12:00 AM (Midnight) - EVERY DAY
 * 
 * CORRECT CRON COMMANDS:
 * UTC Time: 0 0 * * * /usr/bin/php /home/kidsf/public_html/backend/cron/distribute-roi.php
 * PKT Time: 0 19 * * * /usr/bin/php /home/kidsf/public_html/backend/cron/distribute-roi.php
 * IST Time: 30 18 * * * /usr/bin/php /home/kidsf/public_html/backend/cron/distribute-roi.php
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/cron_error.log');
set_time_limit(300); // 5 minutes max execution

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

date_default_timezone_set('Asia/Karachi');

// Log file path
$logFile = __DIR__ . '/distribution_log.txt';

function writeLog($message) {
    global $logFile;
    $timestamp = date('Y-m-d H:i:s');
    $logMessage = "[$timestamp] $message\n";
    file_put_contents($logFile, $logMessage, FILE_APPEND);
    echo $logMessage;
}

// Check if database connection exists
if (!isset($conn) || !$conn) {
    writeLog("❌ FATAL ERROR: Database connection failed!");
    exit;
}

writeLog("========================================");
writeLog("DISTRIBUTION CRON JOB STARTED");
writeLog("Server Time: " . date('Y-m-d H:i:s'));
writeLog("Timezone: " . date_default_timezone_get());
writeLog("========================================");

$today = date('Y-m-d');
$now   = date('Y-m-d H:i:s');

// ─── NO WEEKEND / DAY SKIP — ROI RUNS EVERY DAY ──────────────
writeLog("📅 Today: $today (" . date('l') . ") — ROI will be distributed.");
// ──────────────────────────────────────────────────────────────

// Create lock file to prevent concurrent execution
$lockFile = __DIR__ . '/cron.lock';
if (file_exists($lockFile)) {
    $lockTime = filemtime($lockFile);
    $timeDiff = time() - $lockTime;

    if ($timeDiff < 300) {
        writeLog("⚠️  Cron already running. Lock file age: {$timeDiff}s");
        writeLog("========================================\n");
        exit;
    } else {
        writeLog("⚠️  Removing stale lock file (age: {$timeDiff}s)");
        unlink($lockFile);
    }
}

// Create lock file
file_put_contents($lockFile, date('Y-m-d H:i:s'));
writeLog("✅ Lock file created");

// Check if already processed today
$checkToday = mysqli_query($conn, "SELECT COUNT(*) as cnt FROM roi_logs WHERE date = '$today'");
if (!$checkToday) {
    writeLog("❌ ERROR: Failed to check today's distribution - " . mysqli_error($conn));
    unlink($lockFile);
    exit;
}

$todayCheck = mysqli_fetch_assoc($checkToday);
if ($todayCheck['cnt'] > 0) {
    writeLog("⚠️  ROI already distributed today ($today). Total entries: " . $todayCheck['cnt']);
    writeLog("========================================\n");
    unlink($lockFile);
    exit;
}

writeLog("✅ No distribution done today. Proceeding...");

// Helper Function: Get Directs in Timeframe
function getDirectsInTimeframe($conn, $acc_id, $first_deposit_date, $days) {
    if (!$first_deposit_date) return 0;

    $deadline = date('Y-m-d H:i:s', strtotime($first_deposit_date . " + $days days"));

    $query = 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 = '$acc_id' 
        AND d.status = 'success' 
        AND u.created_at <= '$deadline'
    ");

    if (!$query) {
        writeLog("⚠️  Warning: Failed to get directs for $acc_id");
        return 0;
    }
    $result = mysqli_fetch_assoc($query);
    return intval($result['cnt'] ?? 0);
}

// Counters
$processedCount        = 0;
$skippedCount          = 0;
$errorCount            = 0;
$totalRoiDistributed   = 0;
$totalLevelDistributed = 0;
$userRoiData           = [];

writeLog("\n--- PHASE 1: ROI DISTRIBUTION ---");

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

if (!$usersQuery) {
    writeLog("❌ FATAL ERROR: Failed to fetch users - " . mysqli_error($conn));
    unlink($lockFile);
    exit;
}

$totalUsers = mysqli_num_rows($usersQuery);
writeLog("📊 Found $totalUsers users with deposits");

while ($user = mysqli_fetch_assoc($usersQuery)) {
    $wallet = mysqli_real_escape_string($conn, $user['wallet']);
    $acc_id = mysqli_real_escape_string($conn, $user['account_id']);

    try {
        // Get total investment
        $invQuery = mysqli_query($conn, "
            SELECT SUM(amount) as total 
            FROM deposits 
            WHERE wallet = '$wallet' AND status = 'success'
        ");

        if (!$invQuery) {
            writeLog("⚠️  Skipped $wallet: Failed to get investment");
            $errorCount++;
            continue;
        }

        $invData       = mysqli_fetch_assoc($invQuery);
        $my_investment = floatval($invData['total'] ?? 0);

        // Check minimum investment ($25)
        if ($my_investment < 25) {
            writeLog("⚠️  Skipped $wallet: Investment < \$25 (\${$my_investment})");
            $skippedCount++;
            continue;
        }

        // Calculate max ROI (200% cap)
        $maxRoi = $my_investment * 2;

        // Get ROI history
        $historyQuery = mysqli_query($conn, "
            SELECT SUM(roi_amount) as total, COUNT(*) as days 
            FROM roi_logs 
            WHERE wallet = '$wallet'
        ");

        if (!$historyQuery) {
            writeLog("⚠️  Skipped $wallet: Failed to get history");
            $errorCount++;
            continue;
        }

        $historyData   = mysqli_fetch_assoc($historyQuery);
        $totalReceived = floatval($historyData['total'] ?? 0);
        $daysUsed      = intval($historyData['days'] ?? 0);

        // Check if already reached 200% cap
        if ($totalReceived >= $maxRoi) {
            writeLog("⚠️  Skipped $wallet: 200% ROI cap reached (\${$totalReceived}/\${$maxRoi})");
            $skippedCount++;
            continue;
        }

        // Get first deposit date
        $firstDepQuery = mysqli_query($conn, "
            SELECT MIN(created_at) as fdate 
            FROM deposits 
            WHERE wallet = '$wallet' AND status = 'success'
        ");

        if (!$firstDepQuery) {
            writeLog("⚠️  Skipped $wallet: Failed to get first deposit");
            $errorCount++;
            continue;
        }

        $firstDepData = mysqli_fetch_assoc($firstDepQuery);
        $firstDepDate = $firstDepData['fdate'] ?? null;

        if (!$firstDepDate) {
            writeLog("⚠️  Skipped $wallet: No first deposit date");
            $skippedCount++;
            continue;
        }

        // Calculate directs in different timeframes
        $directs_7d  = getDirectsInTimeframe($conn, $acc_id, $firstDepDate, 7);
        $directs_14d = getDirectsInTimeframe($conn, $acc_id, $firstDepDate, 14);
        $directs_29d = getDirectsInTimeframe($conn, $acc_id, $firstDepDate, 29);

        // Determine ROI tier and rate
        $roi_rate         = 2.0;
        $tier             = "Bronze";
        $level_bonus_rate = 0;
        $is_booster       = 0;

        if ($directs_29d >= 20) {
            $roi_rate         = 4.0;
            $tier             = "Diamond";
            $level_bonus_rate = 5;
            $is_booster       = 1;
        } elseif ($directs_14d >= 10) {
            $roi_rate         = 3.0;
            $tier             = "Gold";
            $level_bonus_rate = 3;
            $is_booster       = 1;
        } elseif ($directs_7d >= 5) {
            $roi_rate         = 2.5;
            $tier             = "Silver";
            $level_bonus_rate = 0;
            $is_booster       = 1;
        }

        // Calculate daily ROI
        $roi_amount = ($my_investment * $roi_rate) / 100;

        // Ensure we don't exceed 200% cap
        if (($totalReceived + $roi_amount) > $maxRoi) {
            $roi_amount = $maxRoi - $totalReceived;
        }

        $roi_amount = round($roi_amount, 4);

        if ($roi_amount <= 0) {
            writeLog("⚠️  Skipped $wallet: ROI amount is zero");
            $skippedCount++;
            continue;
        }

        $dayNumber = $daysUsed + 1;

        // Start transaction
        mysqli_begin_transaction($conn);

        try {
            // Insert ROI log
            $insertSql = "INSERT INTO roi_logs 
                (wallet, invested_amount, active_directs, is_booster, roi_rate, roi_amount, date, day_number, created_at) 
                VALUES 
                ('$wallet', '$my_investment', '$directs_29d', '$is_booster', '$roi_rate', '$roi_amount', '$today', '$dayNumber', '$now')";

            if (!mysqli_query($conn, $insertSql)) {
                throw new Exception("Failed to insert ROI: " . mysqli_error($conn));
            }

            // Update incomes table
            $updateIncome = "UPDATE incomes SET roi_income = roi_income + $roi_amount WHERE wallet = '$wallet'";

            if (!mysqli_query($conn, $updateIncome)) {
                throw new Exception("Failed to update income: " . mysqli_error($conn));
            }

            // Commit transaction
            mysqli_commit($conn);

            $processedCount++;
            $totalRoiDistributed += $roi_amount;

            // Store data for level income distribution
            $userRoiData[$wallet] = [
                'roi'        => $roi_amount,
                'acc_id'     => $acc_id,
                'level_rate' => $level_bonus_rate,
                'tier'       => $tier
            ];

            writeLog("✅ $wallet | Day $dayNumber | $tier ({$roi_rate}%) | ROI: \${$roi_amount} | Total: $" . round($totalReceived + $roi_amount, 2) . "/\${$maxRoi}");

        } catch (Exception $e) {
            mysqli_rollback($conn);
            writeLog("❌ $wallet | Transaction failed: " . $e->getMessage());
            $errorCount++;
        }

    } catch (Exception $e) {
        writeLog("❌ ERROR processing $wallet: " . $e->getMessage());
        $errorCount++;
    }
}

writeLog("\n--- PHASE 2: LEVEL INCOME DISTRIBUTION ---");

$levelCount = 0;

foreach ($userRoiData as $upWallet => $data) {
    if ($data['level_rate'] <= 0) continue;

    $upRoi   = $data['roi'];
    $upRate  = $data['level_rate'];
    $upAccId = mysqli_real_escape_string($conn, $data['acc_id']);
    $upTier  = $data['tier'];

    $downlinesQuery = mysqli_query($conn, "
        SELECT wallet 
        FROM users 
        WHERE referral_id = '$upAccId'
    ");

    if (!$downlinesQuery) {
        writeLog("⚠️  Failed to get downlines for $upWallet");
        continue;
    }

    while ($downline = mysqli_fetch_assoc($downlinesQuery)) {
        $dlWallet = mysqli_real_escape_string($conn, $downline['wallet']);

        $level_income = ($upRoi * $upRate) / 100;
        $level_income = round($level_income, 4);

        if ($level_income > 0) {
            mysqli_begin_transaction($conn);

            try {
                $levelSql = "INSERT INTO level_logs 
                    (wallet, from_wallet, amount, date, created_at) 
                    VALUES 
                    ('$dlWallet', '$upWallet', '$level_income', '$today', '$now')";

                if (!mysqli_query($conn, $levelSql)) {
                    throw new Exception("Failed to insert level log");
                }

                $updateLevelSql = "UPDATE incomes 
                    SET level_income = level_income + $level_income 
                    WHERE wallet = '$dlWallet'";

                if (!mysqli_query($conn, $updateLevelSql)) {
                    throw new Exception("Failed to update level income");
                }

                mysqli_commit($conn);

                $levelCount++;
                $totalLevelDistributed += $level_income;

                writeLog("⚡ $dlWallet received \${$level_income} from $upWallet ($upTier - {$upRate}%)");

            } catch (Exception $e) {
                mysqli_rollback($conn);
                writeLog("❌ Level income failed: $dlWallet from $upWallet - " . $e->getMessage());
            }
        }
    }
}

// Remove lock file
unlink($lockFile);
writeLog("✅ Lock file removed");

// Final Summary
writeLog("\n========================================");
writeLog("DISTRIBUTION COMPLETED SUCCESSFULLY");
writeLog("========================================");
writeLog("📅 Date: $today");
writeLog("⏰ Completed at: " . date('H:i:s'));
writeLog("\n📊 ROI DISTRIBUTION:");
writeLog("   - Processed: $processedCount users");
writeLog("   - Skipped: $skippedCount users");
writeLog("   - Errors: $errorCount users");
writeLog("   - Total ROI: \${$totalRoiDistributed}");
writeLog("\n💰 LEVEL INCOME:");
writeLog("   - Distributions: $levelCount");
writeLog("   - Total Amount: \${$totalLevelDistributed}");
writeLog("\n💵 GRAND TOTAL: $" . round($totalRoiDistributed + $totalLevelDistributed, 2));
writeLog("========================================\n\n");

mysqli_close($conn);
?>