<?php

define("FXH_PORTAL", true);
require_once __DIR__."/../config.php";

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

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

if (!$data) {
    echo json_encode(["error"=>"Invalid JSON"]);
    exit;
}

$action = strtoupper($data["action"]);
$symbol = trim($data["symbol"]);
$sl     = (int)$data["sl"];
$tp     = (int)$data["tp"];
$mode   = strtoupper($data["mode"]);
$target = $data["target"] ?? null;

if (!in_array($action, ["BUY","SELL"])) {
    echo json_encode(["error"=>"INVALID ACTION"]);
    exit;
}

/* =============================
   GET TARGET LICENCES
============================= */

$targets = [];

if ($mode === "ALL") {

    $q = $conn->query(
    "SELECT license_key FROM fxh_licenses WHERE active = 1 AND license_key <> ''"
    );
    
    while ($row = $q->fetch_assoc()) {
        $targets[] = $row["license_key"];
    }

} elseif ($mode === "LICENSE" && $target) {

    $targets[] = $target;

} else {

    echo json_encode(["error"=>"INVALID MODE"]);
    exit;
}

/* =============================
   DISPATCH TO QUEUE
============================= */

$uuid = uniqid("FXH-", true);
$count = 0;

foreach ($targets as $license) {

    usleep(rand(150000,2500000));

    $lot = rand(5,25)/100;  // 0.05 – 0.25

    $comment = "FXH-".substr(md5(uniqid()),0,6);

    $stmt = $conn->prepare("
        INSERT INTO fxh_trade_queue
         (trade_uuid,license_key,action,symbol,
          volume,sl_points,tp_points,trade_comment)

        VALUES (?,?,?,?,?,?,?,?)
    ");

    $stmt->bind_param(
        "ssssdiss",
        $uuid,$license,$action,$symbol,
        $lot,$sl,$tp,$comment
    );

    $stmt->execute();

    $count++;
}

echo json_encode([
    "status"     => "OK",
    "uuid"       => $uuid,
    "dispatched" => $count
]);
