<?php require_once "/var/www/html/config.database.php"; ?>
<?php
require_once "../portal/config.php";

$data = file_get_contents("php://input");
if(!$data){
    http_response_code(400);
    echo "NO JSON";
    exit;
}

$json = json_decode($data, true);
if(!$json){
    http_response_code(400);
    echo "INVALID JSON";
    exit;
}

$license = $conn->real_escape_string($json['license_key']);
$account = $conn->real_escape_string($json['mt5_account']);

$positions = $json['positions'] ?? [];

if(!$license || !$account){
    http_response_code(400);
    echo "MISSING LICENSE/ACCOUNT";
    exit;
}

// REMOVE OLD POSITIONS FOR THIS ACCOUNT
$conn->query("
    DELETE FROM fxh_positions_live
    WHERE license_key = '$license'
");

// INSERT NEW POSITIONS
$stmt = $conn->prepare("
    INSERT INTO fxh_positions_live 
    (license_key, mt5_account, ticket, symbol, type, volume, open_price, sl, tp, profit, swap, commission, open_time)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");

foreach($positions as $p){
    $stmt->bind_param(
        "ssissddddddds",
        $license,
        $account,
        $p['ticket'],
        $p['symbol'],
        $p['type'],
        $p['volume'],
        $p['open_price'],
        $p['sl'],
        $p['tp'],
        $p['profit'],
        $p['swap'],
        $p['commission'],
        $p['open_time']
    );
    $stmt->execute();
}

echo "OK";
?>
