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

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

$tradeId = $data['trade_id'] ?? null;
$coinName = $data['coin_name'] ?? null;
$coinPairName = $data['coinpair_name'] ?? null;
$directionId = $data['direction'] ?? null;
$leverage = $data['leverage'] ?? null;
$openPrice = $data['open_price'] ?? null;
$closePrice = $data['close_price'] ?? null;
$closeDate = $data['close_date'] ?? null;

if (!$tradeId) {
    echo json_encode(['error' => 'Trade ID is missing.']);
    exit;
}

$conn->begin_transaction();

try {
    // Fetch current trade details
    $stmt = $conn->prepare('
        SELECT c.coin_name, cp.coinpair_name, h.coin_id, h.coinpair_id, h.direction_id, h.open_price, 
               h.close_price, h.leverage, h.close_date, h.percents
        FROM rr_410_history_input h
        JOIN rr_410_coin c ON h.coin_id = c.coin_id
        JOIN rr_410_coinpair cp ON h.coinpair_id = cp.coinpair_id
        WHERE h.trade_id = ?
    ');
    $stmt->bind_param('i', $tradeId);
    $stmt->execute();
    $stmt->bind_result($dbCoinName, $dbCoinPairName, $coinId, $coinpairId, $dbDirectionId, $dbOpenPrice, $dbClosePrice, $dbLeverage, $dbCloseDate, $dbPercents);
    $stmt->fetch();
    $stmt->close();

    // Fallback to current database values if not provided in the update
    $coinName = $coinName ?? $dbCoinName;
    $coinPairName = $coinPairName ?? $dbCoinPairName;
    $directionId = $directionId ?? $dbDirectionId;
    $leverage = $leverage ?? $dbLeverage;
    $openPrice = $openPrice ?? $dbOpenPrice;
    $closePrice = $closePrice ?? $dbClosePrice;
    $closeDate = $closeDate ?? $dbCloseDate;

    // Handle coin name update or insertion
    if ($coinName) {
        $stmt = $conn->prepare('SELECT coin_id FROM rr_410_coin WHERE coin_name = ?');
        $stmt->bind_param('s', $coinName);
        $stmt->execute();
        $stmt->bind_result($existingCoinId);
        if ($stmt->fetch()) {
            // Coin already exists, use existing coin_id
            $coinId = $existingCoinId;
        } else {
            // Coin does not exist, insert new coin
            $stmt->close();
            $stmt = $conn->prepare('INSERT INTO rr_410_coin (coin_name) VALUES (?)');
            $stmt->bind_param('s', $coinName);
            $stmt->execute();
            $coinId = $stmt->insert_id; // Get the new coin_id
        }
        $stmt->close();
    }

    // Update coinpair_name if new value provided
    if ($coinPairName) {
        $stmt = $conn->prepare('UPDATE rr_410_coinpair SET coinpair_name = ? WHERE coinpair_id = ?');
        $stmt->bind_param('si', $coinPairName, $coinpairId);
        $stmt->execute();
        $stmt->close();
    }

    // Calculate new percents if needed
    $newPercents = null;
    if ($directionId != $dbDirectionId || $openPrice != $dbOpenPrice || $closePrice != $dbClosePrice || $leverage != $dbLeverage) {
        if ($openPrice != 0) {
            $newPercents = calculatePercents($directionId == 1 ? 'Long' : 'Short', $openPrice, $closePrice, $leverage);
        } else {
            $newPercents = 0;
        }
    }

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

    $percentsToUpdate = $newPercents ?? $dbPercents;
    $stmt->bind_param('iiiddisi', $coinId, $directionId, $leverage, $openPrice, $closePrice, $percentsToUpdate, $closeDate, $tradeId);
    $stmt->execute();
    $stmt->close();

    $conn->commit();

    echo json_encode(['success' => true]);
} catch (Exception $e) {
    $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 ($open_price == 0) return 0;

    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);
}
?>
