<?php
require_once __DIR__ . "/../middleware/user_auth.php";
$license = $_SESSION['licenses'][0]['license_key'];
?>
<!DOCTYPE html>
<html>
<head>
<title>FX-HUNTER Strategy Optimizer</title>
<style>
body{background:#070b16;color:#e8f1ff;font-family:Arial}
.card{background:#0f1a2f;padding:20px;border-radius:12px;margin:20px}
button{background:#00e5ff;border:none;padding:10px 16px;border-radius:6px;font-weight:bold}
select,input{background:#091428;color:#fff;border:1px solid #1f3b5b;padding:6px}
</style>
</head>
<body>

<div class="card">
<h2>⚡ FX-HUNTER Strategy Optimizer</h2>
<p>License: <b><?= $license ?></b></p>
<a href="/optimizer/download_sample.php" target="_blank">
  <button type="button">⬇ Download Sample CSV</button>
</a>
<br><br>

<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="csv" required><br><br>
<label>Objective</label>
<select name="objective">
<option value="Net Profit">Net Profit</option>
<option value="Profit Factor">Profit Factor</option>
<option value="Max Drawdown">Lowest Drawdown</option>
<option value="Win Rate">Win Rate</option>
</select><br><br>
<button type="submit">Optimize</button>
</form>

<pre id="out"></pre>
</div>

<script>
let FXH_LICENSE = "";

// get license from query OR extension injected variable
const params = new URLSearchParams(window.location.search);
if(params.has("license")){
  FXH_LICENSE = params.get("license");
  document.getElementById("lic").textContent = FXH_LICENSE;
}

document.getElementById("uploadForm").onsubmit = async e=>{
  e.preventDefault();

  if(!FXH_LICENSE){
    alert("License not set");
    return;
  }

  let fd = new FormData(e.target);
  fd.append("license", FXH_LICENSE);

  let r = await fetch("/optimizer/import_csv.php", {
    method:"POST",
    headers:{
      "X-FXH-LICENSE": FXH_LICENSE
    },
    body: fd
  });

  let j = await r.json();
  if(j.error){
    document.getElementById("out").textContent = JSON.stringify(j,null,2);
    return;
  }

  let opt = await fetch("/optimizer/optimize.php", {
    method:"POST",
    headers:{
      "Content-Type":"application/json",
      "X-FXH-LICENSE": FXH_LICENSE
    },
    body: JSON.stringify({
      rows: j.rows,
      objective: e.target.objective.value,
      strategy: "TradingView",
      symbol: "ANY",
      timeframe: "ANY"
    })
  });

  document.getElementById("out").textContent =
    JSON.stringify(await opt.json(), null, 2);
};
</script>

</body>
</html>
