<?php require_once "/var/www/html/config.database.php"; ?>
<?php
// ------------------------------------------------------------
// FX-HUNTER Webhook Signal Receiver (Option A - Auto Save)
// Creates:
//   /webhook/latest_signal.txt
//   /webhook/signals/YYYY-MM-DD_HH-MM-SS.txt
// ------------------------------------------------------------

date_default_timezone_set("UTC");

// Ensure signals directory exists
$signals_dir = __DIR__ . "/signals/";
if (!is_dir($signals_dir)) {
    mkdir($signals_dir, 0775, true);
}

// Read POST body
$raw_input = file_get_contents("php://input");
$data = json_decode($raw_input, true);

// Extract signal message
if (isset($data["message"])) {
    $signal = trim($data["message"]);
} else {
    // Fallback for plain text webhook
    $signal = trim($raw_input);
}

// Validate input
if ($signal == "" || strlen($signal) < 3) {
    http_response_code(400);
    echo json_encode([
        "status" => "ERROR",
        "error"  => "Empty or invalid signal"
    ]);
    exit;
}

// Prepare filenames
$timestamp = date("Y-m-d_H-i-s");
$history_file = $signals_dir . $timestamp . ".txt";
$latest_file  = __DIR__ . "/latest_signal.txt";

// Save signal history file
file_put_contents($history_file, $signal);

// Update latest signal
file_put_contents($latest_file, $signal);

// Return JSON output
echo json_encode([
    "status"     => "OK",
    "saved_as"   => basename($history_file),
    "latest"     => "latest_signal.txt",
    "signal"     => $signal
]);
?>
