<?php
include('connection.php');

// Get the raw POST data
$data = json_decode(file_get_contents("php://input"), true);

// Extract data from the request
$tradeId = $data['trade_id'];
$coinName = $data['coin_name'];
$coinPairName = $data['coinpair_name'];
$directionId = $data['direction_id'];  // Now receiving direction_id (1 for Long, 2 for Short)
$leverage = $data['leverage'];
$openPrice = $data['open_price'];
$closePrice = $data['close_price'];

// Start a transaction to ensure all updates succeed or none
$conn->begin_transaction();

try {
    // Fetch the current coin_id, coinpair_id, direction_id, and other values from the rr_410_history_input table for the given trade
    $stmt = $conn->prepare('
        SELECT coin_id, coinpair_id, direction_id, open_price, close_price, leverage
        FROM rr_410_history_input
        WHERE trade_id = ?
    ');
    $stmt->bind_param('i', $tradeId);
    $stmt->execute();
    $stmt->bind_result($coinId, $coinpairId, $dbDirectionId, $dbOpenPrice, $dbClosePrice, $dbLeverage);
    $stmt->fetch();
    $stmt->close();

    // 1. Update coin_name in rr_410_coin table
    $stmt = $conn->prepare('UPDATE rr_410_coin SET coin_name = ? WHERE coin_id = ?');
    $stmt->bind_param('si', $coinName, $coinId);
    $stmt->execute();
    $stmt->close();

    // 2. Update coinpair_name in rr_410_coinpair table
    $stmt = $conn->prepare('UPDATE rr_410_coinpair SET coinpair_name = ? WHERE coinpair_id = ?');
    $stmt->bind_param('si', $coinPairName, $coinpairId);
    $stmt->execute();
    $stmt->close();

    // 3. Update direction_id directly in rr_410_history_input (use direction_id, not the direction table)
    $stmt = $conn->prepare('UPDATE rr_410_history_input SET direction_id = ? WHERE trade_id = ?');
    $stmt->bind_param('ii', $directionId, $tradeId);  // 1 for Long, 2 for Short
    $stmt->execute();
    $stmt->close();

    // 4. If open_price or close_price has changed, calculate the new percent
    $newPercents = null;

    if ($openPrice != $dbOpenPrice || $closePrice != $dbClosePrice || $leverage != $dbLeverage) {
        $newPercents = calculatePercents($directionId === 1 ? 'long' : 'short', $openPrice, $closePrice, $leverage);
    }

    // 5. Update other fields in rr_410_history_input (open_price, close_price, leverage, percents, close_date)
    $stmt = $conn->prepare('
        UPDATE rr_410_history_input
        SET leverage = ?, open_price = ?, close_price = ?, percents = ?, close_date = ?
        WHERE trade_id = ?
    ');

    // If newPercents is null, use the existing percents
    if ($newPercents === null) {
        $stmt->bind_param('iddisi', $leverage, $openPrice, $closePrice, $dbPercents, $closeDate, $tradeId);
    } else {
        $stmt->bind_param('iddisi', $leverage, $openPrice, $closePrice, $newPercents, $closeDate, $tradeId);
    }

    $stmt->execute();
    $stmt->close();

    // Commit the transaction if everything is successful
    $conn->commit();

    echo json_encode(['success' => true]);
} catch (Exception $e) {
    // Rollback the transaction if there's any error
    $conn->rollback();
    echo json_encode(['error' => 'Failed to update trade: ' . $e->getMessage()]);
}

$conn->close();

// Function to calculate percents
function calculatePercents($direction, $open_price, $close_price, $leverage) {
    if ($direction === 'long') {
        $percentage = ((100 / $open_price) * $close_price - 100) * $leverage;
    } elseif ($direction === 'short') {
        $percentage = ((100 / $open_price) * $close_price - 100) * (-1) * $leverage;
    } else {
        return null;
    }
    
    return round($percentage, 2);
}
?>
