<?php
/**
 * FX-HUNTER — MANUAL DISPATCH ENDPOINT
 * Receives global or selective BUY/SELL commands
 * and pushes scheduled randomized signals into DB queue
 */

require_once __DIR__ . "/../portal/config.php";

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

// -------------------------------------------
// CONFIG
// -------------------------------------------
$ADMIN_TOKEN = "CHANGE_ME_TO_SECRET_TOKEN";


// -------------------------------------------
// AUTH CHECK
// -------------------------------------------
$headers = getallheaders();
$token   = $headers['X-ADMIN-TOKEN'] ?? '';

if($token !== $ADMIN_TOKEN){
    http_response_code(403);
    echo json_encode(["error"=>"Unauthorized"]);
    exit;
}

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

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

$action  = strtoupper(trim($data['action'] ?? ''));
$symbol  = strtoupper(trim($data['symbol'] ?? ''));
$mode    = strtoupper(trim($data['mode'] ?? 'ALL')); // ALL or SELECT
$targets = $data['licenses'] ?? [];

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

if(!$symbol){
    http_response_code(400);
    echo json_encode(["error"=>"Missing symbol"]);
    exit;
}


// -------------------------------------------
// LOAD LICENSES
// -------------------------------------------
$licenses = [];

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

    $q = $conn->query("SELECT decrypted AS license FROM fxh_licenses WHERE status='active'");

    while($r=$q->fetch_assoc()){
        $licenses[] = $r['license'];
    }

}else{

    foreach($targets as $lic){
        $clean = preg_replace('/[^A-Za-z0-9\-]/','',$lic);
        if($clean) $licenses[] = $clean;
    }
}


// -------------------------------------------
// DISPATCH SIGNALS
// -------------------------------------------
$total = 0;

foreach($licenses as $license){

    $delay = rand(1,60);   // 1–60 sec randomization

    $payload = json_encode([
        "type"   => "manual",
        "action"=> $action,
        "symbol"=> $symbol,
        "sl"    => $data['sl']   ?? 0,
        "tp"    => $data['tp']   ?? 0,
        "comment"=> "FXH_" . substr(md5($license.time()),0,6),
        "runup" => $data['runup'] ?? true,
        "trail" => $data['trail'] ?? true,
        "be"    => $data['be'] ?? true,
        "partial" => $data['partial'] ?? true
    ]);

    $execAt = date("Y-m-d H:i:s", time()+$delay);

    $stmt = $conn->prepare("
        INSERT INTO fxh_signal_queue
        (license, payload, scheduled_at)
        VALUES (?, ?, ?)
    ");

    $stmt->bind_param("sss", $license, $payload, $execAt);
    $stmt->execute();

    $total++;
}


echo json_encode([
    "status"=>"OK",
    "licenses_sent"=>$total
]);
