<?php
/**
 * SIMPLE 14 FEB ROI FIX
 * Direct database approach - no date confusion
 */

date_default_timezone_set('Asia/Kolkata');
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

if (!isset($conn) || !$conn) {
    die("❌ Database connection failed!");
}

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>14 Feb ROI Fix</title>
    <style>
        body { font-family: 'Segoe UI', Arial; max-width: 1100px; margin: 20px auto; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
        .container { background: white; padding: 40px; border-radius: 15px; box-shadow: 0 10px 40px rgba(0,0,0,0.3); }
        h1 { color: #d32f2f; text-align: center; margin-bottom: 10px; }
        .subtitle { text-align: center; color: #666; margin-bottom: 30px; }
        .info { background: #e3f2fd; border-left: 4px solid #2196f3; padding: 15px; margin: 20px 0; border-radius: 5px; }
        .warning { background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin: 20px 0; border-radius: 5px; }
        .success { background: #d4edda; border-left: 4px solid #28a745; padding: 15px; margin: 20px 0; border-radius: 5px; }
        .error { background: #f8d7da; border-left: 4px solid #dc3545; padding: 15px; margin: 20px 0; border-radius: 5px; }
        .log { background: #1e1e1e; color: #0f0; padding: 20px; border-radius: 8px; font-family: 'Courier New'; font-size: 13px; max-height: 600px; overflow-y: auto; margin: 20px 0; line-height: 1.6; }
        .stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin: 30px 0; }
        .stat-box { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 25px; border-radius: 10px; text-align: center; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .stat-box h3 { margin: 0 0 10px 0; font-size: 14px; opacity: 0.9; }
        .stat-box p { margin: 0; font-size: 32px; font-weight: bold; }
        button { background: #28a745; color: white; border: none; padding: 15px 40px; font-size: 18px; border-radius: 8px; cursor: pointer; display: block; margin: 20px auto; box-shadow: 0 4px 15px rgba(40,167,69,0.3); transition: all 0.3s; }
        button:hover { background: #218838; transform: translateY(-2px); box-shadow: 0 6px 20px rgba(40,167,69,0.4); }
        .timestamp { text-align: center; color: #888; font-size: 14px; margin-top: 20px; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🚀 14 Feb ROI Distribution</h1>
        <p class="subtitle">Smart Flow FX - Emergency Fix</p>

        <div class="info">
            <strong>📅 Current India Time:</strong> <?php echo date('d M Y, h:i:s A'); ?><br>
            <strong>🎯 Distribution Date:</strong> 14 February 2026
        </div>

<?php

// First check what dates we have
$existingDates = mysqli_query($conn, "SELECT DISTINCT date, COUNT(*) as cnt FROM roi_logs GROUP BY date ORDER BY date DESC LIMIT 5");

echo "<div class='warning'><strong>📊 Existing ROI Dates:</strong><br>";
if ($existingDates) {
    echo "<ul style='margin: 10px 0;'>";
    while ($row = mysqli_fetch_assoc($existingDates)) {
        echo "<li>{$row['date']} - {$row['cnt']} entries</li>";
    }
    echo "</ul>";
} else {
    echo "No entries found.";
}
echo "</div>";

// Check specifically for 14 Feb
$check14Feb = mysqli_query($conn, "SELECT COUNT(*) as cnt FROM roi_logs WHERE date = '2026-02-14'");
$feb14Data = mysqli_fetch_assoc($check14Feb);

if ($feb14Data['cnt'] > 0) {
    echo "<div class='error'>";
    echo "<h3>⚠️ 14 Feb ROI Already Exists!</h3>";
    echo "<p>Found <strong>{$feb14Data['cnt']}</strong> entries for 14 Feb 2026.</p>";
    echo "<p>If you want to re-distribute, first run these SQL commands in phpMyAdmin:</p>";
    echo "<pre style='background:#fff; padding:10px; border-radius:5px;'>";
    echo "DELETE FROM roi_logs WHERE date = '2026-02-14';\n";
    echo "DELETE FROM level_logs WHERE date = '2026-02-14';";
    echo "</pre>";
    echo "</div>";
    echo "</div></body></html>";
    exit;
}

echo "<div class='success'>";
echo "✅ No 14 Feb entries found. Safe to proceed!";
echo "</div>";

echo "<div class='log'>";

function log_msg($msg) {
    echo "[" . date('H:i:s') . "] " . $msg . "\n";
    flush();
    if (ob_get_level() > 0) ob_flush();
}

$targetDate = '2026-02-14';
$now = date('Y-m-d H:i:s');

log_msg("========================================");
log_msg("ROI DISTRIBUTION STARTED");
log_msg("Target Date: $targetDate");
log_msg("========================================");
log_msg("");

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) return 0;
    $result = mysqli_fetch_assoc($query);
    return intval($result['cnt'] ?? 0);
}

$processed = 0;
$skipped = 0;
$errors = 0;
$totalRoi = 0;
$totalLevel = 0;
$roiData = [];

log_msg("PHASE 1: ROI DISTRIBUTION");
log_msg("");

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

if (!$usersQuery) {
    log_msg("❌ FATAL: Cannot fetch users - " . mysqli_error($conn));
    echo "</div></div></body></html>";
    exit;
}

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

while ($user = mysqli_fetch_assoc($usersQuery)) {
    $wallet = mysqli_real_escape_string($conn, $user['wallet']);
    $acc_id = mysqli_real_escape_string($conn, $user['account_id']);
    
    $invQuery = mysqli_query($conn, "SELECT SUM(amount) as total FROM deposits WHERE wallet = '$wallet' AND status = 'success'");
    if (!$invQuery) { $errors++; continue; }
    $investment = floatval(mysqli_fetch_assoc($invQuery)['total'] ?? 0);
    
    if ($investment < 25) { $skipped++; continue; }
    
    $histQuery = mysqli_query($conn, "SELECT SUM(roi_amount) as total, COUNT(*) as days FROM roi_logs WHERE wallet = '$wallet'");
    if (!$histQuery) { $errors++; continue; }
    $hist = mysqli_fetch_assoc($histQuery);
    $received = floatval($hist['total'] ?? 0);
    $days = intval($hist['days'] ?? 0);
    
    $maxRoi = $investment * 2;
    if ($received >= $maxRoi) { $skipped++; continue; }
    
    $fdQuery = mysqli_query($conn, "SELECT MIN(created_at) as fdate FROM deposits WHERE wallet = '$wallet' AND status = 'success'");
    if (!$fdQuery) { $errors++; continue; }
    $firstDep = mysqli_fetch_assoc($fdQuery)['fdate'] ?? null;
    if (!$firstDep) { $skipped++; continue; }
    
    $d7 = getDirectsInTimeframe($conn, $acc_id, $firstDep, 7);
    $d14 = getDirectsInTimeframe($conn, $acc_id, $firstDep, 14);
    $d29 = getDirectsInTimeframe($conn, $acc_id, $firstDep, 29);
    
    $rate = 2.0;
    $tier = "Bronze";
    $levelRate = 0;
    $booster = 0;
    
    if ($d29 >= 20) {
        $rate = 4.0; $tier = "Diamond"; $levelRate = 5; $booster = 1;
    } elseif ($d14 >= 10) {
        $rate = 3.0; $tier = "Gold"; $levelRate = 3; $booster = 1;
    } elseif ($d7 >= 5) {
        $rate = 2.5; $tier = "Silver"; $booster = 1;
    }
    
    $roiAmt = ($investment * $rate) / 100;
    if (($received + $roiAmt) > $maxRoi) {
        $roiAmt = $maxRoi - $received;
    }
    $roiAmt = round($roiAmt, 4);
    
    if ($roiAmt <= 0) { $skipped++; continue; }
    
    $day = $days + 1;
    
    mysqli_begin_transaction($conn);
    try {
        $sql = "INSERT INTO roi_logs (wallet, invested_amount, active_directs, is_booster, roi_rate, roi_amount, date, day_number, created_at) 
                VALUES ('$wallet', '$investment', '$d29', '$booster', '$rate', '$roiAmt', '$targetDate', '$day', '$now')";
        if (!mysqli_query($conn, $sql)) throw new Exception(mysqli_error($conn));
        
        if (!mysqli_query($conn, "UPDATE incomes SET roi_income = roi_income + $roiAmt WHERE wallet = '$wallet'")) {
            throw new Exception(mysqli_error($conn));
        }
        
        mysqli_commit($conn);
        $processed++;
        $totalRoi += $roiAmt;
        $roiData[$wallet] = ['roi' => $roiAmt, 'acc_id' => $acc_id, 'rate' => $levelRate, 'tier' => $tier];
        
        log_msg("✅ $wallet | Day $day | $tier | +$$roiAmt");
        
    } catch (Exception $e) {
        mysqli_rollback($conn);
        $errors++;
        log_msg("❌ $wallet failed");
    }
}

log_msg("");
log_msg("PHASE 2: LEVEL INCOME");
log_msg("");

$levelCount = 0;
foreach ($roiData as $upWallet => $data) {
    if ($data['rate'] <= 0) continue;
    
    $upRoi = $data['roi'];
    $upRate = $data['rate'];
    $upAccId = mysqli_real_escape_string($conn, $data['acc_id']);
    
    $dlQuery = mysqli_query($conn, "SELECT wallet FROM users WHERE referral_id = '$upAccId'");
    if (!$dlQuery) continue;
    
    while ($dl = mysqli_fetch_assoc($dlQuery)) {
        $dlWallet = mysqli_real_escape_string($conn, $dl['wallet']);
        $levelInc = round(($upRoi * $upRate) / 100, 4);
        
        if ($levelInc > 0) {
            mysqli_begin_transaction($conn);
            try {
                $sql = "INSERT INTO level_logs (wallet, from_wallet, amount, date, created_at) 
                        VALUES ('$dlWallet', '$upWallet', '$levelInc', '$targetDate', '$now')";
                if (!mysqli_query($conn, $sql)) throw new Exception();
                
                if (!mysqli_query($conn, "UPDATE incomes SET level_income = level_income + $levelInc WHERE wallet = '$dlWallet'")) {
                    throw new Exception();
                }
                
                mysqli_commit($conn);
                $levelCount++;
                $totalLevel += $levelInc;
                
                log_msg("⚡ $dlWallet got $$levelInc from $upWallet");
            } catch (Exception $e) {
                mysqli_rollback($conn);
            }
        }
    }
}

log_msg("");
log_msg("========================================");
log_msg("✅ DISTRIBUTION COMPLETED SUCCESSFULLY");
log_msg("========================================");
log_msg("Date: $targetDate");
log_msg("Processed: $processed users");
log_msg("Skipped: $skipped users");
log_msg("Errors: $errors users");
log_msg("Total ROI: $$totalRoi");
log_msg("Level Income: $$totalLevel ($levelCount distributions)");
log_msg("GRAND TOTAL: $" . round($totalRoi + $totalLevel, 2));
log_msg("========================================");

echo "</div>";

$grandTotal = round($totalRoi + $totalLevel, 2);

echo "<div class='success'>";
echo "<h2 style='margin-top:0;'>✅ 14 Feb ROI Distribution Complete!</h2>";
echo "<div class='stats'>";
echo "<div class='stat-box'><h3>✅ Processed</h3><p>$processed</p></div>";
echo "<div class='stat-box'><h3>⏭️ Skipped</h3><p>$skipped</p></div>";
echo "<div class='stat-box'><h3>💰 Total ROI</h3><p>$$totalRoi</p></div>";
echo "<div class='stat-box'><h3>⚡ Level Income</h3><p>$$totalLevel</p></div>";
echo "<div class='stat-box'><h3>💵 Grand Total</h3><p>$$grandTotal</p></div>";
echo "</div>";
echo "<p style='text-align:center; font-size:20px; margin-top:20px;'>";
echo "<strong>🎉 14 February की ROI successfully distribute हो गई है!</strong><br>";
echo "<span style='color:#666; font-size:16px;'>Dashboard check करें - सभी users को ROI मिल गई है।</span>";
echo "</p>";
echo "</div>";

mysqli_close($conn);
?>

        <p class="timestamp">Completed at: <?php echo date('d M Y, h:i:s A'); ?></p>
    </div>
</body>
</html>