<?php
/**
 * Close Trade API - Updates trade result and wallet balance
 */
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/Auth.php';

if (session_status() === PHP_SESSION_NONE) session_start();

$user = auth()->getUser();
if (!$user) {
    echo json_encode(['success' => false, 'error' => 'Not logged in']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);

$tradeId = $input['trade_id'] ?? 0;
$exitPrice = (float)($input['exit_price'] ?? 0);
$result = $input['result'] ?? 'lost';
$profit = (float)($input['profit'] ?? 0);

if (!$tradeId) {
    echo json_encode(['success' => false, 'error' => 'Trade ID required']);
    exit;
}

try {
    // Get trade
    $trade = dbFetch("SELECT * FROM trades WHERE id = ? AND user_id = ?", [$tradeId, $user['id']]);
    
    if (!$trade) {
        echo json_encode(['success' => false, 'error' => 'Trade not found']);
        exit;
    }
    
    // Already closed?
    if ($trade['result'] !== 'pending') {
        echo json_encode(['success' => false, 'error' => 'Trade already closed']);
        exit;
    }
    
    $isDemo = (int)$trade['is_demo'];
    $amount = (float)$trade['amount'];
    
    // Calculate actual profit for binary
    if ($trade['trade_type'] === 'binary') {
        // We rely entirely on the frontend's natural result since place.php ensures 
        // the frontend manipulates the chart to visually match the forced result.
        
        if ($result === 'won') {
            $profit = $amount * ((float)$trade['payout_percent'] / 100);
        } else {
            $profit = 0; // Already deducted when trade placed
        }
    }
    
    // Update trade record
    dbQuery("UPDATE trades SET result = ?, actual_profit = ?, exit_price = ?, close_reason = 'manual', closed_at = NOW() WHERE id = ?",
        [$result, $profit, $exitPrice, $tradeId]);
    
    // Track turnover for binary trades (live only) - counts toward bonus withdrawal requirement
    if (!$isDemo && $trade['trade_type'] === 'binary') {
        dbQuery("UPDATE users SET turnover_completed = COALESCE(turnover_completed, 0) + ? WHERE id = ?",
            [$amount, $user['id']]);
    }
    
    // Update wallet balance
    if ($result === 'won') {
        // Return stake + profit
        $returnAmount = $amount + $profit;
        if ($isDemo) {
            dbQuery("UPDATE user_wallets SET demo_balance = demo_balance + ?, total_won = total_won + 1 WHERE user_id = ?", 
                [$returnAmount, $user['id']]);
        } else {
            dbQuery("UPDATE user_wallets SET balance = balance + ?, total_won = total_won + 1 WHERE user_id = ?", 
                [$returnAmount, $user['id']]);
        }
    } else {
        // For CFD with negative profit (loss)
        if ($trade['trade_type'] === 'cfd' && $profit < 0) {
            // Already deducted margin, now return remaining if any
            $remaining = $amount + $profit; // profit is negative
            if ($remaining > 0) {
                if ($isDemo) {
                    dbQuery("UPDATE user_wallets SET demo_balance = demo_balance + ? WHERE user_id = ?", 
                        [$remaining, $user['id']]);
                } else {
                    dbQuery("UPDATE user_wallets SET balance = balance + ? WHERE user_id = ?", 
                        [$remaining, $user['id']]);
                }
            }
        }
        // Update loss count
        if ($isDemo) {
            dbQuery("UPDATE user_wallets SET total_lost = total_lost + 1 WHERE user_id = ?", [$user['id']]);
        } else {
            dbQuery("UPDATE user_wallets SET total_lost = total_lost + 1 WHERE user_id = ?", [$user['id']]);
        }
    }
    
    // Get updated balance
    $wallet = dbFetch("SELECT * FROM user_wallets WHERE user_id = ?", [$user['id']]);
    $pendingData = dbFetch("SELECT COALESCE(SUM(amount), 0) as total FROM withdrawals WHERE user_id = ? AND status = 'pending'", [$user['id']]);
    
    echo json_encode([
        'success' => true,
        'result' => $result,
        'profit' => $profit,
        'balance' => (float)($wallet['balance'] ?? 0),
        'bonus_balance' => (float)($wallet['bonus_balance'] ?? 0),
        'demo_balance' => (float)($wallet['demo_balance'] ?? 10000),
        'pending_withdrawals' => (float)($pendingData['total'] ?? 0)
    ]);
    
} catch (Exception $e) {
    error_log("Trade Close Error: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
