<?php
declare(strict_types=1);
header("Content-Type: application/json");
ini_set("display_errors",0); error_reporting(0);
require_once __DIR__ . '/../config.php';

$lic=$_POST['license_key']??'';
$sym=$_POST['symbol']??'';
$tf =(int)($_POST['timeframe']??0);
$str=$_POST['strategy_id']??'DEFAULT';
$r  =(float)($_POST['r_multiple']??0);

if($lic===''||$sym===''||$tf<=0){ echo json_encode(['ok'=>false]); exit; }

$delta = ($r>0)? +5 : -10;   // win recovers, loss decays
$delta += max(-5,min(5,$r*2));

$sql = "
INSERT INTO fxh_ai_confidence (license_key,symbol,timeframe,strategy_id,confidence,trades,wins,losses,r_net)
VALUES (?,?,?,?,50,1,?, ?, ?)
ON DUPLICATE KEY UPDATE
 trades=trades+1,
 wins=wins+VALUES(wins),
 losses=losses+VALUES(losses),
 r_net=r_net+VALUES(r_net),
 confidence=LEAST(100,GREATEST(0,confidence+VALUES(confidence)))
";
$wins = $r>0?1:0; $loss=$r<=0?1:0;
$conf = $delta; $rnet=$r;

$stmt=mysqli_prepare($conn,$sql);
mysqli_stmt_bind_param($stmt,"ssisdiidd",
  $lic,$sym,$tf,$str,$conf,$wins,$loss,$rnet);
mysqli_stmt_execute($stmt);

echo json_encode(['ok'=>true]);
