‰PNG

   IHDR         ôxÔú   sBIT|dˆ   	pHYs  Ä  Ä•+   tEXtSoftware www.inkscape.org›î<  ,àtEXtComment 
<?php
// Include database connection
require_once('includes/connect.php');

// Set timezone to match your server/database
date_default_timezone_set('Africa/Lagos'); 
$currentTime = date('Y-m-d H:i:s');

// Find all OPEN trades where the duration has expired
// We calculate: created_at + duration_minutes <= current time
$query = "SELECT * FROM trades 
          WHERE status = 'OPEN' 
          AND DATE_ADD(created_at, INTERVAL duration_minutes MINUTE) <= '$currentTime'";

$result = $conn->query($query);

if ($result && $result->num_rows > 0) {
    while ($trade = $result->fetch_assoc()) {
        $tradeId = $trade['id'];
        $userId = $trade['user_id'];
        $stakedAmount = floatval($trade['trade_amount']);
        $pnl = floatval($trade['pnl']); // This is the profit (or loss) we calculated in process_trade.php
        
        // Calculate total payout: Return their staked amount PLUS their profit/loss
        // If they lost (pnl is negative), the payout is $0.
        // If they won, payout is Staked Amount + Profit.
        $totalPayout = $stakedAmount + $pnl;
        if ($totalPayout < 0) {
            $totalPayout = 0; 
        }

        // 1. Mark the trade as CLOSED
        $closeStmt = $conn->prepare("UPDATE trades SET status = 'CLOSED', closed_at = ? WHERE id = ?");
        $closeStmt->bind_param("si", $currentTime, $tradeId);
        $closeStmt->execute();
        $closeStmt->close();

        // 2. Add the money to the User's Profit/Capital balances
        if ($totalPayout > 0) {
            // We return the staked amount to Capital, and the PNL to Profit.
            $updateUser = $conn->prepare("UPDATE members SET Capital = Capital + ?, Profit = Profit + ? WHERE ID = ?");
            $updateUser->bind_param("ddi", $stakedAmount, $pnl, $userId);
            $updateUser->execute();
            $updateUser->close();
        }
    }
}
?>