<?php
require_once __DIR__ . "/_bootstrap.php";

try {
    $pdo = fxh_optimizer_pdo();
    $lic = fxh_optimizer_require_license($pdo);

    $j = fxh_json_input();
    $objective = (string)($j["objective"] ?? "");
    $meta = $j["meta"] ?? [];
    $best = $j["best"] ?? [];

    if (!$objective) fxh_send(422, ["error"=>"Missing objective"]);

    // Create table if not exists (safe)
    $pdo->exec("
      CREATE TABLE IF NOT EXISTS fxh_optimizer_runs (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        license_key VARCHAR(64) NOT NULL,
        objective VARCHAR(64) NOT NULL,
        meta_json JSON NULL,
        best_json JSON NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        INDEX (license_key),
        INDEX (created_at)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");

    $stmt = $pdo->prepare("
      INSERT INTO fxh_optimizer_runs (license_key, objective, meta_json, best_json)
      VALUES (:lk, :obj, :meta, :best)
    ");
    $stmt->execute([
      ":lk" => $lic["license_key"],
      ":obj" => $objective,
      ":meta" => json_encode($meta, JSON_UNESCAPED_UNICODE),
      ":best" => json_encode($best, JSON_UNESCAPED_UNICODE),
    ]);

    fxh_send(200, ["status"=>"ok"]);

} catch (Throwable $e) {
    fxh_send(500, ["error"=>"Server error", "details"=>$e->getMessage()]);
}
