<?php
/**
 * SmartFlowFX - Fix ROI + Distribute Level Income
 * Run: http://localhost/smartflowfx2/backend/api/fix-and-run.php?secret=smartfix2026
 */
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: text/plain; charset=utf-8');

if (($_GET['secret'] ?? '') !== 'smartfix2026') die("Access denied.");

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

$today = date('Y-m-d');
$now   = date('Y-m-d H:i:s');
$LEVEL_RATES = [1=>30, 2=>20, 3=>15, 4=>10, 5=>8, 6=>7, 7=>5, 8=>5];

// Detect roi_logs columns
$roiCols = [];
$cQ = mysqli_query($conn, "SHOW COLUMNS FROM roi_logs");
while ($c = mysqli_fetch_assoc($cQ)) $roiCols[] = $c['Field'];
$has_pkg  = in_array('package_name',   $roiCols);
$has_inv  = in_array('invested_amount',$roiCols);
$has_dayno= in_array('day_number',     $roiCols);

echo "roi_logs columns: " . implode(', ', $roiCols) . "\n\n";

echo "═══════════════════════════════════════════\n";
echo "  SmartFlowFX Fix + Level Income Runner\n";
echo "  Date: $today\n";
echo "═══════════════════════════════════════════\n\n";

// ─── STEP 1: Fix wrong ROI in roi_logs ──────────────────
echo "STEP 1: Fixing wrong ROI amounts (roi_rate > 1)...\n";

$fixQ = mysqli_query($conn, "SELECT id, wallet, roi_rate, roi_amount" .
    ($has_inv ? ", invested_amount" : "") . " FROM roi_logs WHERE roi_rate > 1");
$fixCount = 0;

while ($row = mysqli_fetch_assoc($fixQ)) {
    $inv = $has_inv ? floatval($row['invested_amount']) : 0;
    if ($inv <= 0) {
        $inv = floatval(mysqli_fetch_assoc(mysqli_query($conn,
            "SELECT COALESCE(SUM(amount),0) AS amt FROM deposits WHERE wallet='{$row['wallet']}' AND status='success'"
        ))['amt']);
    }
    if ($inv < 500) continue;

    $correct_rate   = $inv >= 10000 ? round(8.0/30,6) : round(6.0/30,6);
    $correct_amount = round($inv * ($correct_rate / 100), 6);

    // Build UPDATE without package_name if column missing
    $setParts = ["roi_rate=$correct_rate", "roi_amount=$correct_amount"];
    if ($has_inv)  $setParts[] = "invested_amount=$inv";
    if ($has_pkg)  $setParts[] = "package_name='" . ($inv>=10000?'Premium':'Standard') . "'";
    $setSQL = implode(', ', $setParts);

    mysqli_query($conn, "UPDATE roi_logs SET $setSQL WHERE id={$row['id']}");

    echo "  FIXED | {$row['wallet']} | old={$row['roi_rate']}% \${$row['roi_amount']} → new={$correct_rate}% \${$correct_amount}\n";
    $fixCount++;
}
echo "  → Fixed $fixCount records\n\n";

// ─── STEP 2: Level income for today ─────────────────────
echo "STEP 2: Distributing level income for today...\n\n";

$roiTodayQ = mysqli_query($conn,
    "SELECT rl.wallet, rl.roi_amount, u.account_id
     FROM roi_logs rl JOIN users u ON rl.wallet=u.wallet
     WHERE DATE(rl.created_at)='$today'"
);

$lvlTotal = 0; $lvlCount = 0;

while ($earner = mysqli_fetch_assoc($roiTodayQ)) {
    $eWallet  = $earner['wallet'];
    $eAccId   = $earner['account_id'];
    $eRoi     = floatval($earner['roi_amount']);

    echo "  Earner: $eWallet | ROI=\$$eRoi\n";

    $curAccId = $eAccId;
    for ($lv = 1; $lv <= 8; $lv++) {
        // Find sponsor
        $sp = mysqli_fetch_assoc(mysqli_query($conn,
            "SELECT u.wallet, u.account_id, u.name
             FROM users u
             INNER JOIN users child ON child.referral_id = u.account_id
             WHERE child.account_id = '$curAccId' LIMIT 1"
        ));
        if (!$sp || empty($sp['wallet'])) { echo "    L$lv: chain ends.\n"; break; }

        $spWallet = $sp['wallet'];
        $spAccId  = $sp['account_id'];

        // Sponsor must have active investment
        $spInv = floatval(mysqli_fetch_assoc(mysqli_query($conn,
            "SELECT COALESCE(SUM(amount),0) AS amt FROM deposits WHERE wallet='$spWallet' AND status='success'"
        ))['amt']);
        if ($spInv < 500) {
            echo "    L$lv: {$sp['name']} not qualified (\$$spInv). Skip.\n";
            $curAccId = $spAccId; continue;
        }

        // Duplicate check
        $dup = mysqli_fetch_assoc(mysqli_query($conn,
            "SELECT id FROM level_logs WHERE wallet='$spWallet' AND from_user='$eWallet'
             AND level_no=$lv AND DATE(created_at)='$today' LIMIT 1"
        ));
        if ($dup) {
            echo "    L$lv: already done for {$sp['name']}.\n";
            $curAccId = $spAccId; continue;
        }

        $rate   = $LEVEL_RATES[$lv];
        $amount = round($eRoi * ($rate / 100), 6);
        if ($amount <= 0) { $curAccId = $spAccId; continue; }

        $ins = mysqli_query($conn,
            "INSERT INTO level_logs (wallet, from_user, level, level_no, percentage, amount, date, created_at)
             VALUES ('$spWallet','$eWallet',$lv,$lv,$rate,$amount,'$today','$now')"
        );

        if ($ins) {
            $lvlTotal += $amount; $lvlCount++;
            echo "    ✅ L$lv | +\$$amount → {$sp['name']} ($spWallet) | {$rate}% of \$$eRoi\n";
        } else {
            echo "    ❌ L$lv | DB Error: " . mysqli_error($conn) . "\n";
        }

        $curAccId = $spAccId;
    }
    echo "\n";
}

echo "═══════════════════════════════════════════\n";
echo "  ROI fixed         : $fixCount records\n";
echo "  Level distributions: $lvlCount\n";
echo "  Level income total : \$" . number_format($lvlTotal, 6) . "\n";
echo "═══════════════════════════════════════════\n";
?>