<?php
/**
 * FX-HUNTER MANUAL TRADE COMMAND BRIDGE
 * React UI → webhook → MT5 EA
 */

ini_set("display_errors",1);
error_reporting(E_ALL);

header("Content-Type: application/json");

// ----------------------------------------------------
// INPUT
// ----------------------------------------------------
$raw = file_get_contents("php://input");
$data = json_decode($raw,true);

if(!$data){
    echo json_encode(["status"=>"ERROR","reason"=>"INVALID_JSON","raw"=>$raw]);
    exit;
}

$symbol = strtoupper(trim($data["symbol"] ?? ""));
$type   = strtoupper(trim($data["type"] ?? ""));
$lots   = floatval($data["lots"] ?? 0);
$sl     = trim($data["sl"] ?? "");
$tp     = trim($data["tp"] ?? "");

// ----------------------------------------------------
// VALIDATION
// ----------------------------------------------------
if(!$symbol || !$type || !$lots){
    echo json_encode([
        "status"=>"ERROR",
        "reason"=>"MISSING_FIELDS",
        "symbol"=>$symbol,
        "type"=>$type,
        "lots"=>$lots
    ]);
    exit;
}

if(!in_array($type,["BUY","SELL"])){
    echo json_encode(["status"=>"ERROR","reason"=>"INVALID_TYPE"]);
    exit;
}

// ----------------------------------------------------
// SAVE COMMAND TO LOG FILE (EA POLLS THIS FILE)
// ----------------------------------------------------
$cmd = [
    "symbol"=>$symbol,
    "type"=>$type,
    "lots"=>$lots,
    "sl"=>$sl,
    "tp"=>$tp,
    "time"=>gmdate("Y-m-d H:i:s")
];

$file = __DIR__ . "/logs/trade_commands.log";

file_put_contents(
    $file,
    json_encode($cmd).PHP_EOL,
    FILE_APPEND | LOCK_EX
);

echo json_encode([
    "status"=>"QUEUED",
    "command"=>$cmd
]);
