<?php
$userFilePath = __DIR__ . '/user.txt';

$mastertradeid = $_POST['mastertradeid'] ?? null;
$slavetradeid  = $_POST['slavetradeid'] ?? null;
$action        = $_POST['action'] ?? 'add';

if (!$mastertradeid || !$slavetradeid) {
    echo json_encode(['status' => 'error', 'message' => 'Missing master or slave trade id']);
    exit;
}

// Only remove if action = remove
if ($action === 'remove') {
    $lines = file_exists($userFilePath) ? file($userFilePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : [];
    $newLines = [];
    foreach ($lines as $line) {
        $parts = explode(",", $line);
        if (count($parts) >= 2) {
            if (!(trim($parts[0]) === trim($mastertradeid) && trim($parts[1]) === trim($slavetradeid))) {
                $newLines[] = $line;
            }
        }
    }
    file_put_contents($userFilePath, implode(PHP_EOL, $newLines) . PHP_EOL);
    echo json_encode(['status' => 'success', 'message' => 'Pair removed successfully']);
    exit;
}

// Otherwise keep existing add logic (unchanged)
$volumeselect = $_POST['volumeselect'] ?? 'fixed';
// $volume = $_POST['volume'] ?? 1.0;
if ($volumeselect == 'same') {
    $volume = 0;
} else {
    $volume = $_POST['volume'] ?? 1.0;
}

// $line = trim($mastertradeid) . ',' . trim($slavetradeid) . ',' . trim($volumeselect) . ',' . floatval($volume);
$line = trim($mastertradeid) . ',' .
        trim($slavetradeid) . ',' .
        trim($volumeselect) . ',' .
        floatval($volume);
file_put_contents($userFilePath, $line . PHP_EOL, FILE_APPEND);
echo json_encode(['status' => 'success', 'message' => 'Pair added successfully']);
?>
