<?php
// This script runs via server cron job (e.g., once every hour)
require_once __DIR__ . "/../include/db.php";

// 1. Find all active investments that haven't been paid in the last 24 hours
$query = "SELECT * FROM investments WHERE status = 'active' AND last_payout <= DATE_SUB(NOW(), INTERVAL 24 HOUR)";
$result = mysqli_query($conn, $query);

while ($invest = mysqli_fetch_assoc($result)) {
    $investId = $invest['id'];
    $userId = $invest['user_id'];
    $amount = $invest['amount'];
    $rate = $invest['daily_return'];
    $endDate = strtotime($invest['end_at']);
    $now = time();

    // Calculate daily profit amount
    $dailyProfit = ($amount * ($rate / 100));

    mysqli_begin_transaction($conn);

    try {
        // A. Update User's Profit and Balance
        $updateUser = "UPDATE users SET profit = profit + $dailyProfit, balance = balance + $dailyProfit WHERE id = $userId";
        mysqli_query($conn, $updateUser);

        // B. Update Investment's last_payout to NOW
        $updateInvest = "UPDATE investments SET last_payout = NOW() WHERE id = $investId";
        mysqli_query($conn, $updateInvest);

        // C. Check if plan has expired
        if ($now >= $endDate) {
            mysqli_query($conn, "UPDATE investments SET status = 'completed' WHERE id = $investId");
        }

        mysqli_commit($conn);
        echo "Paid $dailyProfit to User ID $userId for Investment #$investId\n";

    } catch (Exception $e) {
        mysqli_rollback($conn);
        error_log("Cron Error: " . $e->getMessage());
    }
}
?>