<?php
session_start();
require "../config.php";

$user_email = $_SESSION['email'] ?? null;
if (!$user_email) {
    echo "<div class='text-center text-red-500 py-4'>Not logged in</div>";
    exit;
}

// --- Fetch all active investments ---
$stmt = $pdo->prepare("
    SELECT * FROM invest 
    WHERE email = :email 
      AND status IN ('active','processing') 
    ORDER BY id DESC
");
$stmt->execute([':email' => $user_email]);
$investments = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (!$investments) {
    echo "<div class='text-center text-gray-400 py-6'>No active investments found</div>";
    exit;
}

foreach ($investments as $inv) {
    $investId  = (int)$inv['id'];
    $email     = $inv['email'];
    $amount    = (float)$inv['amount'];
    $percent   = (float)$inv['percent'];
    $duration  = (int)$inv['duration'];
    $roi_total = (float)$inv['roi_total'];
    $currency  = $inv['user_cur'] ?? '$';
    $user_rate = isset($inv['user_rate']) ? (float)$inv['user_rate'] : 1;
    $userTz    = $_SESSION['user_timezone'] ?? 'UTC';

    // Convert stored start time
    $startTime = $inv['local_time'] ?? $inv['date'];
    $startDt = new DateTime($startTime, new DateTimeZone($userTz));
    $endDt   = clone $startDt;
    $endDt->modify("+{$duration} minutes");
    $now     = new DateTime('now', new DateTimeZone($userTz));

    // Calculate elapsed 5-min intervals
    $elapsedIntervals = floor(($now->getTimestamp() - $startDt->getTimestamp()) / 300); // every 5 mins
    if ($elapsedIntervals < 1) continue;

    // How many ROI records already exist
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM roi_history WHERE invest_id = ?");
    $stmt->execute([$investId]);
    $existing = (int)$stmt->fetchColumn();

    // For each new 5-min slot, add ROI
    if ($elapsedIntervals > $existing && $now < $endDt) {
        $roiPerInterval = ($amount * $percent / 100) / ($duration / 5); 
        $profit = round($roiPerInterval, 2);

        // Insert ROI record
        $stmt = $pdo->prepare("
            INSERT INTO roi_history (invest_id, email, amount, percentage, created_at)
            VALUES (:iid, :email, :amt, :pct, NOW())
        ");
        $stmt->execute([
            ':iid' => $investId,
            ':email' => $email,
            ':amt' => $profit,
            ':pct' => $percent
        ]);

        // Update invest total ROI
        $pdo->prepare("UPDATE invest SET roi_total = roi_total + :p WHERE id = :id")
            ->execute([':p' => $profit, ':id' => $investId]);

        // Update user's profit balance
        $pdo->prepare("UPDATE logins SET iprofit = iprofit + :p WHERE email = :email")
            ->execute([':p' => $profit, ':email' => $email]);

        echo "
            <div class='text-green-400 text-sm'>
                [+] ROI +{$currency}{$profit} added for <b>{$inv['plan']}</b> ({$elapsedIntervals}×5 min)
            </div>
        ";
    }

    // Mark as completed if duration reached
    if ($now >= $endDt && strtolower($inv['status']) !== 'completed') {
        $pdo->prepare("UPDATE invest SET status='completed' WHERE id=:id")
            ->execute([':id' => $investId]);
        echo "<div class='text-yellow-400 text-sm'>Investment #{$investId} completed.</div>";
    }
}
?>
