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

// 1) READ RAW BODY
$raw = file_get_contents("php://input");

// Debug
file_put_contents(__DIR__ . "/debug_last.txt", $raw);
file_put_contents(__DIR__ . "/debug_len.txt", strlen($raw));
file_put_contents(__DIR__ . "/debug_hex.txt", bin2hex($raw));

if (!$raw) {
    http_response_code(400);
    echo json_encode(["status" => "NO_BODY"]);
    exit;
}

// 2) JSON DECODE
$data = json_decode($raw, true);
if (!is_array($data)) {
    http_response_code(400);
    echo json_encode(["status" => "INVALID_JSON"]);
    exit;
}

// 3) Extract fields
$license   = trim($data['license_key'] ?? '');
$account   = trim($data['mt5_account'] ?? '');
$positions = $data['positions'] ?? [];

if ($license === '' || $account === '') {
    http_response_code(400);
    echo json_encode(["status" => "MISSING_LICENSE_OR_ACCOUNT"]);
    exit;
}

$esc_license = $db->real_escape_string($license);

// 4) Clear old rows
$db->query("DELETE FROM fxh_positions_live WHERE license_key = '$esc_license'");

// 5) Insert new rows
if (!empty($positions)) {

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

    foreach ($positions as $p) {

        $ticket     = intval($p['ticket']);
        $symbol     = $p['symbol'];
        $typeVal    = ($p['type'] === "buy" ? 0 : 1);
        $volume     = floatval($p['volume']);
        $open_price = floatval($p['open_price']);
        $sl         = floatval($p['sl']);
        $tp         = floatval($p['tp']);
        $profit     = floatval($p['profit']);
        $swap       = floatval($p['swap']);
        $commission = floatval($p['commission']);
        $open_time  = $p['open_time'];

        $stmt->bind_param(
            "ssissddddddds",
            $license,
            $account,
            $ticket,
            $symbol,
            $typeVal,
            $volume,
            $open_price,
            $sl,
            $tp,
            $profit,
            $swap,
            $commission,
            $open_time
        );

        if (!$stmt->execute()) {
            http_response_code(500);
            echo json_encode(["status" => "EXECUTE_FAIL", "error" => $stmt->error]);
            exit;
        }
    }
}

// 6) Final response
echo json_encode(["status" => "OK"]);
?>
