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

/*
|--------------------------------------------------------------------------
| FX-HUNTER OPTIMIZER — UPLOAD (FINAL, MATCHES PORTAL)
|--------------------------------------------------------------------------
*/

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

// Ensure DB connection exists
if (!isset($conn) || !($conn instanceof mysqli)) {
    http_response_code(500);
    echo json_encode(["error" => "db_not_loaded"]);
    exit;
}

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

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

// Validate license (CORRECT SIGNATURE)
$license = fxh_require_license($conn, $data);

// Required fields
foreach (["strategy", "symbol", "timeframe", "results"] as $f) {
    if (!isset($data[$f])) {
        http_response_code(422);
        echo json_encode(["error" => "missing_$f"]);
        exit;
    }
}

// Insert optimizer run
$stmt = $conn->prepare("
    INSERT INTO fxh_optimizer_runs
    (license_key, strategy, symbol, timeframe, results)
    VALUES (?, ?, ?, ?, ?)
");

$results_json = json_encode($data["results"], JSON_UNESCAPED_UNICODE);

$stmt->bind_param(
    "sssss",
    $license["license_key"],
    $data["strategy"],
    $data["symbol"],
    $data["timeframe"],
    $results_json
);

$stmt->execute();

echo json_encode(["status" => "ok"]);
exit;
